Search in sources :

Example 26 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class CamelContextLazyLoadTypeConvertersTest method testConvert.

public void testConvert() throws Exception {
    TypeConverter converter = context.getTypeConverter();
    Integer value = converter.convertTo(Integer.class, "1000");
    assertNotNull(value);
    assertEquals("Converted to Integer", new Integer(1000), value);
    String text = converter.convertTo(String.class, value);
    assertEquals("Converted to String", "1000", text);
}
Also used : TypeConverter(org.apache.camel.TypeConverter)

Example 27 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class DefaultUndertowHttpBinding method toHttpRequest.

@Override
public Object toHttpRequest(ClientRequest clientRequest, Message message) {
    Object body = message.getBody();
    final HeaderMap requestHeaders = clientRequest.getRequestHeaders();
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        requestHeaders.put(Headers.CONTENT_TYPE, contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    //copy headers from Message to Request
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        String key = entry.getKey();
        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);
        while (it.hasNext()) {
            String headerValue = tc.convertTo(String.class, it.next());
            if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                LOG.trace("HTTP-Header: {}={}", key, headerValue);
                requestHeaders.add(new HttpString(key), headerValue);
            }
        }
    }
    return body;
}
Also used : TypeConverter(org.apache.camel.TypeConverter) HeaderMap(io.undertow.util.HeaderMap) HttpString(io.undertow.util.HttpString) HashMap(java.util.HashMap) HeaderMap(io.undertow.util.HeaderMap) Map(java.util.Map) HttpString(io.undertow.util.HttpString)

Example 28 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class DefaultUndertowHttpBinding method toHttpResponse.

@Override
public Object toHttpResponse(HttpServerExchange httpExchange, Message message) throws IOException {
    boolean failed = message.getExchange().isFailed();
    int defaultCode = failed ? 500 : 200;
    int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
    httpExchange.setResponseCode(code);
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    //copy headers from Message to Response
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        String key = entry.getKey();
        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);
        while (it.hasNext()) {
            String headerValue = tc.convertTo(String.class, it.next());
            if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                LOG.trace("HTTP-Header: {}={}", key, headerValue);
                httpExchange.getResponseHeaders().add(new HttpString(key), headerValue);
            }
        }
    }
    Object body = message.getBody();
    Exception exception = message.getExchange().getException();
    if (exception != null) {
        if (isTransferException()) {
            // we failed due an exception, and transfer it as java serialized object
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(exception.getCause());
            oos.flush();
            IOHelper.close(oos, bos);
            // the body should be the serialized java object of the exception
            body = ByteBuffer.wrap(bos.toByteArray());
            // force content type to be serialized java object
            message.setHeader(Exchange.CONTENT_TYPE, "application/x-java-serialized-object");
        } else {
            // we failed due an exception so print it as plain text
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            exception.getCause().printStackTrace(pw);
            // the body should then be the stacktrace
            body = ByteBuffer.wrap(sw.toString().getBytes());
            // force content type to be text/plain as that is what the stacktrace is
            message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
        }
        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(message.getExchange());
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        httpExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    return body;
}
Also used : HttpString(io.undertow.util.HttpString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) IOException(java.io.IOException) TypeConverter(org.apache.camel.TypeConverter) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) HeaderMap(io.undertow.util.HeaderMap) Map(java.util.Map) HttpString(io.undertow.util.HttpString) PrintWriter(java.io.PrintWriter)

Example 29 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class ResourceConverterTest method getResourceTypeConverter.

private TypeConverter getResourceTypeConverter() {
    CamelContext camelContext = new DefaultCamelContext();
    TypeConverter typeConverter = camelContext.getTypeConverterRegistry().lookup(InputStream.class, Resource.class);
    return typeConverter;
}
Also used : CamelContext(org.apache.camel.CamelContext) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) TypeConverter(org.apache.camel.TypeConverter) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext)

Example 30 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class DefaultNettyHttpBinding method toNettyResponse.

@Override
public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toNettyResponse: {}", message);
    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpResponse) {
        return (HttpResponse) message.getBody();
    }
    Object body = message.getBody();
    Exception cause = message.getExchange().getException();
    // support bodies as native Netty
    ByteBuf buffer;
    // the response code is 200 for OK and 500 for failed
    boolean failed = message.getExchange().isFailed();
    int defaultCode = failed ? 500 : 200;
    int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
    LOG.trace("HTTP Status Code: {}", code);
    // if there was an exception then use that as body
    if (cause != null) {
        if (configuration.isTransferException()) {
            // we failed due an exception, and transfer it as java serialized object
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(cause);
            oos.flush();
            IOHelper.close(oos, bos);
            // the body should be the serialized java object of the exception
            body = NettyConverter.toByteBuffer(bos.toByteArray());
            // force content type to be serialized java object
            message.setHeader(Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
        } else {
            // we failed due an exception so print it as plain text
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            cause.printStackTrace(pw);
            // the body should then be the stacktrace
            body = NettyConverter.toByteBuffer(sw.toString().getBytes());
            // force content type to be text/plain as that is what the stacktrace is
            message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
        }
        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(message.getExchange());
    }
    if (body instanceof ByteBuf) {
        buffer = (ByteBuf) body;
    } else {
        // try to convert to buffer first
        buffer = message.getBody(ByteBuf.class);
        if (buffer == null) {
            // fallback to byte array as last resort
            byte[] data = message.getBody(byte[].class);
            if (data != null) {
                buffer = NettyConverter.toByteBuffer(data);
            } else {
                // and if byte array fails then try String
                String str;
                if (body != null) {
                    str = message.getMandatoryBody(String.class);
                } else {
                    str = "";
                }
                buffer = NettyConverter.toByteBuffer(str.getBytes());
            }
        }
    }
    HttpResponse response = null;
    if (buffer != null) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), buffer);
        // We just need to reset the readerIndex this time
        if (buffer.readerIndex() == buffer.writerIndex()) {
            buffer.setIndex(0, buffer.writerIndex());
        }
        // TODO How to enable the chunk transport 
        int len = buffer.readableBytes();
        // set content-length
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), len);
        LOG.trace("Content-Length: {}", len);
    } else {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code));
    }
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    // must use entrySet to ensure case of keys is preserved
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        String key = entry.getKey();
        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);
        while (it.hasNext()) {
            String headerValue = tc.convertTo(String.class, it.next());
            if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                LOG.trace("HTTP-Header: {}={}", key, headerValue);
                response.headers().add(key, headerValue);
            }
        }
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(HttpHeaderNames.CONNECTION.toString(), String.class);
    // Read the connection header from the exchange property
    if (connection == null) {
        connection = message.getExchange().getProperty(HttpHeaderNames.CONNECTION.toString(), String.class);
    }
    if (connection == null) {
        // fallback and use the keep alive from the configuration
        if (configuration.isKeepAlive()) {
            connection = HttpHeaderValues.KEEP_ALIVE.toString();
        } else {
            connection = HttpHeaderValues.CLOSE.toString();
        }
    }
    response.headers().set(HttpHeaderNames.CONNECTION.toString(), connection);
    // Just make sure we close the channel when the connection value is close
    if (connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString())) {
        message.setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
    }
    LOG.trace("Connection: {}", connection);
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuf(io.netty.buffer.ByteBuf) ObjectOutputStream(java.io.ObjectOutputStream) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TypeConverter(org.apache.camel.TypeConverter) StringWriter(java.io.StringWriter) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Aggregations

TypeConverter (org.apache.camel.TypeConverter)48 Map (java.util.Map)13 FallbackConverter (org.apache.camel.FallbackConverter)9 InputStream (java.io.InputStream)6 HashMap (java.util.HashMap)6 Exchange (org.apache.camel.Exchange)6 RuntimeCamelException (org.apache.camel.RuntimeCamelException)6 ArrayList (java.util.ArrayList)5 NoTypeConversionAvailableException (org.apache.camel.NoTypeConversionAvailableException)5 HttpString (io.undertow.util.HttpString)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 ObjectOutputStream (java.io.ObjectOutputStream)4 PrintWriter (java.io.PrintWriter)4 StringWriter (java.io.StringWriter)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 List (java.util.List)4 HeaderMap (io.undertow.util.HeaderMap)3 IOException (java.io.IOException)3 URI (java.net.URI)3 Message (org.apache.camel.Message)3