Search in sources :

Example 1 with NoTypeConversionAvailableException

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

the class DefaultNettyHttpBinding method toNettyRequest.

@Override
public HttpRequest toNettyRequest(Message message, String uri, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toNettyRequest: {}", message);
    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpRequest) {
        return (HttpRequest) message.getBody();
    }
    String uriForRequest = uri;
    if (configuration.isUseRelativePath()) {
        int indexOfPath = uri.indexOf((new URI(uri)).getPath());
        if (indexOfPath > 0) {
            uriForRequest = uri.substring(indexOfPath);
        }
    }
    // just assume GET for now, we will later change that to the actual method to use
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriForRequest);
    Object body = message.getBody();
    if (body != null) {
        // support bodies as native Netty
        ByteBuf buffer;
        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.getMandatoryBody(byte[].class);
                buffer = NettyConverter.toByteBuffer(data);
            }
        }
        if (buffer != null) {
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriForRequest, buffer);
            int len = buffer.readableBytes();
            // set content-length
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), len);
            LOG.trace("Content-Length: {}", len);
        } else {
            // we do not support this kind of body
            throw new NoTypeConversionAvailableException(body, ByteBuf.class);
        }
    }
    // update HTTP method accordingly as we know if we have a body or not
    HttpMethod method = NettyHttpHelper.createMethod(message, body != null);
    request.setMethod(method);
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;
    if (configuration.isBridgeEndpoint()) {
        String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
        }
        // Need to remove the Host key as it should be not used
        message.getHeaders().remove("host");
    }
    // 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();
        // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
        if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
            continue;
        }
        // use an iterator as there can be multiple values. (must not use a delimiter)
        final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
        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);
                request.headers().add(key, headerValue);
            }
        }
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        request.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    // must include HOST header as required by HTTP 1.1
    // use URI as its faster than URL (no DNS lookup)
    URI u = new URI(uri);
    String hostHeader = u.getHost() + (u.getPort() == 80 ? "" : ":" + u.getPort());
    request.headers().set(HttpHeaderNames.HOST.toString(), hostHeader);
    LOG.trace("Host: {}", hostHeader);
    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(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();
        }
    }
    request.headers().set(HttpHeaderNames.CONNECTION.toString(), connection);
    LOG.trace("Connection: {}", connection);
    return request;
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) ByteBuf(io.netty.buffer.ByteBuf) URI(java.net.URI) TypeConverter(org.apache.camel.TypeConverter) Map(java.util.Map) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 2 with NoTypeConversionAvailableException

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

the class XQueryBuilder method createDynamicContext.

/**
     * Creates a dynamic context for the given exchange
     */
protected DynamicQueryContext createDynamicContext(Exchange exchange) throws Exception {
    Configuration config = getConfiguration();
    DynamicQueryContext dynamicQueryContext = new DynamicQueryContext(config);
    Message in = exchange.getIn();
    Item item = null;
    if (ObjectHelper.isNotEmpty(getHeaderName())) {
        item = in.getHeader(getHeaderName(), Item.class);
    } else {
        item = in.getBody(Item.class);
    }
    if (item != null) {
        dynamicQueryContext.setContextItem(item);
    } else {
        Object body = null;
        if (ObjectHelper.isNotEmpty(getHeaderName())) {
            body = in.getHeader(getHeaderName());
        } else {
            body = in.getBody();
        }
        // the underlying input stream, which we need to close to avoid locking files or other resources
        InputStream is = null;
        try {
            Source source;
            // only convert to input stream if really needed
            if (isInputStreamNeeded(exchange)) {
                if (ObjectHelper.isNotEmpty(getHeaderName())) {
                    is = exchange.getIn().getHeader(getHeaderName(), InputStream.class);
                } else {
                    is = exchange.getIn().getBody(InputStream.class);
                }
                source = getSource(exchange, is);
            } else {
                source = getSource(exchange, body);
            }
            // special for bean invocation
            if (source == null) {
                if (body instanceof BeanInvocation) {
                    // if its a null bean invocation then handle that
                    BeanInvocation bi = exchange.getContext().getTypeConverter().convertTo(BeanInvocation.class, body);
                    if (bi.getArgs() != null && bi.getArgs().length == 1 && bi.getArgs()[0] == null) {
                        // its a null argument from the bean invocation so use null as answer
                        source = null;
                    }
                }
            }
            if (source == null) {
                // indicate it was not possible to convert to a Source type
                throw new NoTypeConversionAvailableException(body, Source.class);
            }
            DocumentInfo doc = config.buildDocument(source);
            dynamicQueryContext.setContextItem(doc);
        } finally {
            // can deal if is is null
            IOHelper.close(is);
        }
    }
    configureQuery(dynamicQueryContext, exchange);
    // call the reset if the in message body is StreamCache
    MessageHelper.resetStreamCache(exchange.getIn());
    return dynamicQueryContext;
}
Also used : Item(net.sf.saxon.om.Item) Configuration(net.sf.saxon.Configuration) Message(org.apache.camel.Message) DynamicQueryContext(net.sf.saxon.query.DynamicQueryContext) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) InputStream(java.io.InputStream) BeanInvocation(org.apache.camel.component.bean.BeanInvocation) BytesSource(org.apache.camel.BytesSource) StringSource(org.apache.camel.StringSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SAXSource(javax.xml.transform.sax.SAXSource) StAXSource(javax.xml.transform.stax.StAXSource) DocumentInfo(net.sf.saxon.om.DocumentInfo)

Example 3 with NoTypeConversionAvailableException

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

the class UnaryExpression method createDecExpression.

private Expression createDecExpression(final Expression leftExp) {
    return new Expression() {

        @Override
        public <T> T evaluate(Exchange exchange, Class<T> type) {
            Number num = leftExp.evaluate(exchange, Number.class);
            if (num != null) {
                long val = num.longValue();
                val--;
                // convert value back to same type as input as we want to preserve type
                Object left = leftExp.evaluate(exchange, Object.class);
                try {
                    left = exchange.getContext().getTypeConverter().mandatoryConvertTo(left.getClass(), exchange, val);
                } catch (NoTypeConversionAvailableException e) {
                    throw ObjectHelper.wrapRuntimeCamelException(e);
                }
                // and return the result
                return exchange.getContext().getTypeConverter().convertTo(type, left);
            }
            // cannot convert the expression as a number
            Exception cause = new CamelExchangeException("Cannot evaluate " + leftExp + " as a number", exchange);
            throw ObjectHelper.wrapRuntimeCamelException(cause);
        }

        @Override
        public String toString() {
            return left + operator.toString();
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) CamelExchangeException(org.apache.camel.CamelExchangeException) Expression(org.apache.camel.Expression) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) SimpleParserException(org.apache.camel.language.simple.types.SimpleParserException) CamelExchangeException(org.apache.camel.CamelExchangeException)

Example 4 with NoTypeConversionAvailableException

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

the class BeanNoTypeConvertionPossibleTest method testBeanNoTypeConvertionPossibleFail.

public void testBeanNoTypeConvertionPossibleFail() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(0);
    // we send in a Date object which cannot be converted to XML so it should fail
    try {
        template.requestBody("direct:start", new Date());
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        NoTypeConversionAvailableException ntae = assertIsInstanceOf(NoTypeConversionAvailableException.class, e.getCause().getCause());
        assertEquals(Date.class, ntae.getFromType());
        assertEquals(Document.class, ntae.getToType());
        assertNotNull(ntae.getValue());
        assertNotNull(ntae.getMessage());
    }
    assertMockEndpointsSatisfied();
}
Also used : CamelExecutionException(org.apache.camel.CamelExecutionException) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) Document(org.w3c.dom.Document) Date(java.util.Date)

Example 5 with NoTypeConversionAvailableException

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

the class BeanOverloadedMethodFQNTest method testOrderFQNUnknown.

public void testOrderFQNUnknown() throws Exception {
    context.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start").bean(MyBean.class, "order(org.apache.camel.component.bean.BeanOverloadedMethodFQNTest$Unknown)").to("mock:result");
        }
    });
    context.start();
    try {
        template.sendBody("direct:start", new MyOrder());
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        NoTypeConversionAvailableException cause = assertIsInstanceOf(NoTypeConversionAvailableException.class, e.getCause().getCause());
        assertEquals("org.apache.camel.component.bean.BeanOverloadedMethodFQNTest$Unknown", cause.getValue());
    }
}
Also used : CamelExecutionException(org.apache.camel.CamelExecutionException) RouteBuilder(org.apache.camel.builder.RouteBuilder) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) CamelExecutionException(org.apache.camel.CamelExecutionException)

Aggregations

NoTypeConversionAvailableException (org.apache.camel.NoTypeConversionAvailableException)23 Exchange (org.apache.camel.Exchange)7 Map (java.util.Map)4 CamelExecutionException (org.apache.camel.CamelExecutionException)4 DefaultExchange (org.apache.camel.impl.DefaultExchange)4 Method (java.lang.reflect.Method)3 TypeConverter (org.apache.camel.TypeConverter)3 InputStream (java.io.InputStream)2 Serializable (java.io.Serializable)2 URI (java.net.URI)2 Timestamp (java.sql.Timestamp)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 BytesMessage (javax.jms.BytesMessage)2 JMSException (javax.jms.JMSException)2 MapMessage (javax.jms.MapMessage)2 MessageFormatException (javax.jms.MessageFormatException)2 ObjectMessage (javax.jms.ObjectMessage)2 TextMessage (javax.jms.TextMessage)2 CamelContext (org.apache.camel.CamelContext)2