org.apache.camel.TypeConverter Java Examples

The following examples show how to use org.apache.camel.TypeConverter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KnativeHttpConsumer.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
private HttpServerResponse toHttpResponse(HttpServerRequest request, Message message) {
    final HttpServerResponse response = request.response();
    final boolean failed = message.getExchange().isFailed();
    final int defaultCode = failed ? 500 : 200;
    final int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
    final TypeConverter tc = message.getExchange().getContext().getTypeConverter();

    response.setStatusCode(code);

    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        final String key = entry.getKey();
        final Object value = entry.getValue();

        for (Object it: org.apache.camel.support.ObjectHelper.createIterable(value, null)) {
            String headerValue = tc.convertTo(String.class, it);
            if (headerValue == null) {
                continue;
            }
            if (!headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                response.putHeader(key, headerValue);
            }
        }
    }

    return response;
}
 
Example #2
Source File: ComponentCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the option with the given name and invokes the consumer performing
 * property placeholders resolution and type conversion.
 */
default <T> void consumeOption(CamelContext camelContext, Map<String, Object> options, String name, Class<T> type, Consumer<T> consumer) {
    Object val = options.remove(name);

    if (val != null) {
        try {
            if (val instanceof String) {
                val = camelContext.resolvePropertyPlaceholders((String)val);
            }

            if (type.isInstance(val)) {
                consumer.accept(type.cast(val));
            } else {
                TypeConverter converter = camelContext.getTypeConverter();
                consumer.accept(
                    converter.mandatoryConvertTo(type, val)
                );
            }
        } catch (Exception e) {
            throw new IllegalStateException("Unable to resolve or convert property named: " + name, e);
        }
    }
}
 
Example #3
Source File: SplitStepHandler.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Helper tries to convert given value to a String representation that can be split. For instance a remote file object
 * with Json array as content is converted to String and then split using the elements in that Json array.
 *
 * Some types are already supported by Camel's splitter such as List or Scanner. Do not touch these types and skip conversion.
 * @param value the value to convert.
 * @param exchange the current exchange.
 * @return converted value or original value itself if conversion failed or is not applicable.
 */
private static Object convert(Object value, Exchange exchange) {
    if (Arrays.stream(AutoConvertTypes.values()).noneMatch(type -> type.isInstance(value))) {
        return value;
    }

    TypeConverter converter = exchange.getContext().getTypeConverter();
    String answer = converter.convertTo(String.class, exchange, value);
    if (answer != null) {
        return answer;
    }

    answer = converter.tryConvertTo(String.class, exchange, value);
    if (answer != null) {
        return answer;
    }

    return value;
}
 
Example #4
Source File: PurchaseOrderConverter.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Converter
public static PurchaseOrder toPurchaseOrder(byte[] data, Exchange exchange) {
    TypeConverter converter = exchange.getContext().getTypeConverter();

    String s = converter.convertTo(String.class, data);
    if (s == null || s.length() < 30) {
        throw new IllegalArgumentException("data is invalid");
    }

    s = s.replaceAll("##START##", "");
    s = s.replaceAll("##END##", "");

    String name = s.substring(0, 10).trim();
    String s2 = s.substring(10, 20).trim();
    String s3 = s.substring(20).trim();

    BigDecimal price = new BigDecimal(s2);
    price.setScale(2);

    Integer amount = converter.convertTo(Integer.class, s3);

    PurchaseOrder order = new PurchaseOrder(name, price, amount);
    return order;
}
 
Example #5
Source File: PurchaseOrderConverter.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
@Converter
public static PurchaseOrder toPurchaseOrder(byte[] data, Exchange exchange) {
    TypeConverter converter = exchange.getContext().getTypeConverter();

    String s = converter.convertTo(String.class, data);
    if (s == null || s.length() < 30) {
        throw new IllegalArgumentException("data is invalid");
    }

    s = s.replaceAll("##START##", "");
    s = s.replaceAll("##END##", "");

    String name = s.substring(0, 9).trim();
    String s2 = s.substring(10, 19).trim();
    String s3 = s.substring(20).trim();

    BigDecimal price = new BigDecimal(s2);
    price.setScale(2);

    Integer amount = converter.convertTo(Integer.class, s3);

    PurchaseOrder order = new PurchaseOrder(name, price, amount);
    return order;
}
 
Example #6
Source File: AuthenticationCustomizerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetRefreshOAuth2Token() throws Exception {
    wiremock.givenThat(post("/oauth/authorize")
        .withRequestBody(equalTo("refresh_token=refresh-token&grant_type=refresh_token"))
        .willReturn(ok()
            .withBody("{\"access_token\":\"new-access-token\"}")));

    final AuthenticationCustomizer customizer = new AuthenticationCustomizer();

    final Map<String, Object> options = new HashMap<>();
    options.put("authenticationType", AuthenticationType.oauth2);
    options.put("accessToken", "{{accessToken}}");
    options.put("refreshToken", "{{refreshToken}}");
    final String authorizationEndpoint = "http://localhost:" + wiremock.port() + "/oauth/authorize";
    options.put("authorizationEndpoint", authorizationEndpoint);

    final ComponentProxyComponent component = new SwaggerProxyComponent("dataset-test", "dataset-test");
    final CamelContext context = mock(CamelContext.class);
    component.setCamelContext(context);

    when(context.resolvePropertyPlaceholders("{{accessToken}}")).thenReturn("access-token");
    when(context.resolvePropertyPlaceholders("{{refreshToken}}")).thenReturn("refresh-token");
    when(context.resolvePropertyPlaceholders(authorizationEndpoint)).thenReturn(authorizationEndpoint);
    final TypeConverter typeConverter = mock(TypeConverter.class);
    when(context.getTypeConverter()).thenReturn(typeConverter);

    customizer.customize(component, options);

    assertThat(options).doesNotContainKeys("authenticationType", "accessToken", "refreshToken", "authorizationEndpoint");

    assertAuthorizationHeaderSetTo(component, "Bearer new-access-token");
}
 
Example #7
Source File: QuarkusPlatformHttpConsumer.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
static Object toHttpResponse(HttpServerResponse response, Message message, HeaderFilterStrategy headerFilterStrategy) {
    final Exchange exchange = message.getExchange();

    final int code = determineResponseCode(exchange, message.getBody());
    response.setStatusCode(code);

    final TypeConverter tc = exchange.getContext().getTypeConverter();

    // copy headers from Message to Response
    if (headerFilterStrategy != null) {
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null);
            String firstValue = null;
            List<String> values = null;
            while (it.hasNext()) {
                final String headerValue = tc.convertTo(String.class, it.next());
                if (headerValue != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, exchange)) {
                    if (firstValue == null) {
                        firstValue = headerValue;
                    } else {
                        if (values == null) {
                            values = new ArrayList<String>();
                            values.add(firstValue);
                        }
                        values.add(headerValue);
                    }
                }
            }
            if (values != null) {
                response.putHeader(key, values);
            } else if (firstValue != null) {
                response.putHeader(key, firstValue);
            }
        }
    }

    Object body = message.getBody();
    final Exception exception = exchange.getException();

    if (exception != null) {
        // we failed due an exception so print it as plain text
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);

        // the body should then be the stacktrace
        body = ByteBuffer.wrap(sw.toString().getBytes(StandardCharsets.UTF_8));
        // force content type to be text/plain as that is what the stacktrace is
        message.setHeader(Exchange.CONTENT_TYPE, "text/plain; charset=utf-8");

        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(exchange);
    }

    // set the content-length if it can be determined, or chunked encoding
    final Integer length = determineContentLength(exchange, body);
    if (length != null) {
        response.putHeader("Content-Length", String.valueOf(length));
    } else {
        response.setChunked(true);
    }

    // set the content type in the response.
    final String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.putHeader("Content-Type", contentType);
    }
    return body;
}
 
Example #8
Source File: TypeConversionConfiguration.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Bean(destroyMethod = "")
// Camel handles the lifecycle of this bean
TypeConverter typeConverter(CamelContext camelContext) {
    return camelContext.getTypeConverter();
}
 
Example #9
Source File: NoConvertersTest.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Test(expected = NoSuchBeanDefinitionException.class)
public void shouldNotProvideConverter() {
    applicationContext.getBean(TypeConverter.class);
}