Search in sources :

Example 11 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 12 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 13 with NoTypeConversionAvailableException

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

the class AbstractSalesforceProcessor method getParameter.

/**
     * Gets value for a parameter from header, endpoint config, or exchange body (optional).
     *
     * @param exchange          exchange to inspect
     * @param convertInBody     converts In body to parameterClass value if true
     * @param propName          name of property
     * @param optional          if {@code true} returns null, otherwise throws RestException
     * @param parameterClass    parameter type
     * @return value of property, or {@code null} for optional parameters if not found.
     * @throws org.apache.camel.component.salesforce.api.SalesforceException
     *          if the property can't be found or on conversion errors.
     */
protected final <T> T getParameter(String propName, Exchange exchange, boolean convertInBody, boolean optional, Class<T> parameterClass) throws SalesforceException {
    final Message in = exchange.getIn();
    T propValue = in.getHeader(propName, parameterClass);
    if (propValue == null) {
        // check if type conversion failed
        if (in.getHeader(propName) != null) {
            throw new IllegalArgumentException("Header " + propName + " could not be converted to type " + parameterClass.getName());
        }
        final Object value = endpointConfigMap.get(propName);
        if (value == null || parameterClass.isInstance(value)) {
            propValue = parameterClass.cast(value);
        } else {
            try {
                propValue = exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterClass, value);
            } catch (NoTypeConversionAvailableException e) {
                throw new SalesforceException(e);
            }
        }
    }
    propValue = (propValue == null && convertInBody) ? in.getBody(parameterClass) : propValue;
    // error if property was not set
    if (propValue == null && !optional) {
        String msg = "Missing property " + propName + (convertInBody ? ", message body could not be converted to type " + parameterClass.getName() : "");
        throw new SalesforceException(msg, null);
    }
    return propValue;
}
Also used : SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) Message(org.apache.camel.Message) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException)

Example 14 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 DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriForRequest);
    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);
            }
        }
    }
    Object body = message.getBody();
    if (body != null) {
        // support bodies as native Netty
        ChannelBuffer buffer;
        if (body instanceof ChannelBuffer) {
            buffer = (ChannelBuffer) body;
        } else {
            // try to convert to buffer first
            buffer = message.getBody(ChannelBuffer.class);
            if (buffer == null) {
                // fallback to byte array as last resort
                byte[] data = message.getMandatoryBody(byte[].class);
                buffer = ChannelBuffers.copiedBuffer(data);
            }
        }
        if (buffer != null) {
            request.setContent(buffer);
            int len = buffer.readableBytes();
            // set content-length
            request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
            LOG.trace("Content-Length: {}", len);
        } else {
            // we do not support this kind of body
            throw new NoTypeConversionAvailableException(body, ChannelBuffer.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);
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, 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(HttpHeaders.Names.HOST, hostHeader);
    LOG.trace("Host: {}", hostHeader);
    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
    if (connection == null) {
        // fallback and use the keep alive from the configuration
        if (configuration.isKeepAlive()) {
            connection = HttpHeaders.Values.KEEP_ALIVE;
        } else {
            connection = HttpHeaders.Values.CLOSE;
        }
    }
    request.headers().set(HttpHeaders.Names.CONNECTION, connection);
    LOG.trace("Connection: {}", connection);
    return request;
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) URI(java.net.URI) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) TypeConverter(org.apache.camel.TypeConverter) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) Map(java.util.Map) HttpMethod(org.jboss.netty.handler.codec.http.HttpMethod)

Example 15 with NoTypeConversionAvailableException

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

the class JmsBinding method createJmsMessageForType.

/**
     *
     * Create the {@link Message}
     *
     * @return jmsMessage or null if the mapping was not successfully
     */
protected Message createJmsMessageForType(Exchange exchange, Object body, Map<String, Object> headers, Session session, CamelContext context, JmsMessageType type) throws JMSException {
    switch(type) {
        case Text:
            {
                TextMessage message = session.createTextMessage();
                if (body != null) {
                    String payload = context.getTypeConverter().convertTo(String.class, exchange, body);
                    message.setText(payload);
                }
                return message;
            }
        case Bytes:
            {
                BytesMessage message = session.createBytesMessage();
                if (body != null) {
                    byte[] payload = context.getTypeConverter().convertTo(byte[].class, exchange, body);
                    message.writeBytes(payload);
                }
                return message;
            }
        case Map:
            {
                MapMessage message = session.createMapMessage();
                if (body != null) {
                    Map<?, ?> payload = context.getTypeConverter().convertTo(Map.class, exchange, body);
                    populateMapMessage(message, payload, context);
                }
                return message;
            }
        case Object:
            ObjectMessage message = session.createObjectMessage();
            if (body != null) {
                try {
                    Serializable payload = context.getTypeConverter().mandatoryConvertTo(Serializable.class, exchange, body);
                    message.setObject(payload);
                } catch (NoTypeConversionAvailableException e) {
                    // cannot convert to serializable then thrown an exception to avoid sending a null message
                    JMSException cause = new MessageFormatException(e.getMessage());
                    cause.initCause(e);
                    throw cause;
                }
            }
            return message;
        default:
            break;
    }
    return null;
}
Also used : MessageFormatException(javax.jms.MessageFormatException) Serializable(java.io.Serializable) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) ObjectMessage(javax.jms.ObjectMessage) MapMessage(javax.jms.MapMessage) BytesMessage(javax.jms.BytesMessage) JMSException(javax.jms.JMSException) HashMap(java.util.HashMap) Map(java.util.Map) TextMessage(javax.jms.TextMessage)

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