Search in sources :

Example 16 with HeaderFilterStrategy

use of org.apache.camel.spi.HeaderFilterStrategy in project camel by apache.

the class JettyHttpComponent method createEndpoint.

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    // must extract well known parameters before we create the endpoint
    List<Handler> handlerList = resolveAndRemoveReferenceListParameter(parameters, "handlers", Handler.class);
    HttpBinding binding = resolveAndRemoveReferenceParameter(parameters, "httpBindingRef", HttpBinding.class);
    JettyHttpBinding jettyBinding = resolveAndRemoveReferenceParameter(parameters, "jettyHttpBindingRef", JettyHttpBinding.class);
    Boolean enableJmx = getAndRemoveParameter(parameters, "enableJmx", Boolean.class);
    Boolean enableMultipartFilter = getAndRemoveParameter(parameters, "enableMultipartFilter", Boolean.class, true);
    Filter multipartFilter = resolveAndRemoveReferenceParameter(parameters, "multipartFilterRef", Filter.class);
    List<Filter> filters = resolveAndRemoveReferenceListParameter(parameters, "filtersRef", Filter.class);
    Boolean enableCors = getAndRemoveParameter(parameters, "enableCORS", Boolean.class, false);
    HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
    UrlRewrite urlRewrite = resolveAndRemoveReferenceParameter(parameters, "urlRewrite", UrlRewrite.class);
    SSLContextParameters sslContextParameters = resolveAndRemoveReferenceParameter(parameters, "sslContextParametersRef", SSLContextParameters.class);
    SSLContextParameters ssl = sslContextParameters != null ? sslContextParameters : this.sslContextParameters;
    String proxyHost = getAndRemoveParameter(parameters, "proxyHost", String.class, getProxyHost());
    Integer proxyPort = getAndRemoveParameter(parameters, "proxyPort", Integer.class, getProxyPort());
    Integer httpClientMinThreads = getAndRemoveParameter(parameters, "httpClientMinThreads", Integer.class, this.httpClientMinThreads);
    Integer httpClientMaxThreads = getAndRemoveParameter(parameters, "httpClientMaxThreads", Integer.class, this.httpClientMaxThreads);
    HttpClient httpClient = resolveAndRemoveReferenceParameter(parameters, "httpClient", HttpClient.class);
    Boolean async = getAndRemoveParameter(parameters, "async", Boolean.class);
    // extract httpClient. parameters
    Map<String, Object> httpClientParameters = IntrospectionSupport.extractProperties(parameters, "httpClient.");
    // extract filterInit. parameters
    Map<String, String> filterInitParameters = IntrospectionSupport.extractStringProperties(IntrospectionSupport.extractProperties(parameters, "filterInit."));
    String address = remaining;
    URI addressUri = new URI(UnsafeUriCharactersEncoder.encodeHttpURI(address));
    URI endpointUri = URISupport.createRemainingURI(addressUri, parameters);
    // need to keep the httpMethodRestrict parameter for the endpointUri
    String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
    // restructure uri to be based on the parameters left as we dont want to include the Camel internal options
    URI httpUri = URISupport.createRemainingURI(addressUri, parameters);
    // create endpoint after all known parameters have been extracted from parameters
    // include component scheme in the uri
    String scheme = ObjectHelper.before(uri, ":");
    endpointUri = new URI(scheme + ":" + endpointUri);
    JettyHttpEndpoint endpoint = createEndpoint(endpointUri, httpUri);
    if (async != null) {
        endpoint.setAsync(async);
    }
    if (headerFilterStrategy != null) {
        endpoint.setHeaderFilterStrategy(headerFilterStrategy);
    } else {
        setEndpointHeaderFilterStrategy(endpoint);
    }
    // setup the proxy host and proxy port
    if (proxyHost != null) {
        endpoint.setProxyHost(proxyHost);
        endpoint.setProxyPort(proxyPort);
    }
    if (urlRewrite != null) {
        // let CamelContext deal with the lifecycle of the url rewrite
        // this ensures its being shutdown when Camel shutdown etc.
        getCamelContext().addService(urlRewrite);
        endpoint.setUrlRewrite(urlRewrite);
    }
    if (httpClientParameters != null && !httpClientParameters.isEmpty()) {
        endpoint.setHttpClientParameters(httpClientParameters);
    }
    if (filterInitParameters != null && !filterInitParameters.isEmpty()) {
        endpoint.setFilterInitParameters(filterInitParameters);
    }
    if (handlerList.size() > 0) {
        endpoint.setHandlers(handlerList);
    }
    // prefer to use endpoint configured over component configured
    if (binding == null) {
        // fallback to component configured
        binding = getHttpBinding();
    }
    if (binding != null) {
        endpoint.setBinding(binding);
    }
    // prefer to use endpoint configured over component configured
    if (jettyBinding == null) {
        // fallback to component configured
        jettyBinding = getJettyHttpBinding();
    }
    if (jettyBinding != null) {
        endpoint.setJettyBinding(jettyBinding);
    }
    if (enableJmx != null) {
        endpoint.setEnableJmx(enableJmx);
    } else {
        // set this option based on setting of JettyHttpComponent
        endpoint.setEnableJmx(isEnableJmx());
    }
    endpoint.setEnableMultipartFilter(enableMultipartFilter);
    if (multipartFilter != null) {
        endpoint.setMultipartFilter(multipartFilter);
        endpoint.setEnableMultipartFilter(true);
    }
    if (enableCors) {
        endpoint.setEnableCORS(enableCors);
        if (filters == null) {
            filters = new ArrayList<Filter>(1);
        }
        filters.add(new CrossOriginFilter());
    }
    if (filters != null) {
        endpoint.setFilters(filters);
    }
    if (httpMethodRestrict != null) {
        endpoint.setHttpMethodRestrict(httpMethodRestrict);
    }
    if (ssl != null) {
        endpoint.setSslContextParameters(ssl);
    }
    if (httpClientMinThreads != null) {
        endpoint.setHttpClientMinThreads(httpClientMinThreads);
    }
    if (httpClientMaxThreads != null) {
        endpoint.setHttpClientMaxThreads(httpClientMaxThreads);
    }
    if (httpClient != null) {
        endpoint.setHttpClient(httpClient);
    }
    endpoint.setSendServerVersion(isSendServerVersion());
    setProperties(endpoint, parameters);
    // re-create http uri after all parameters has been set on the endpoint, as the remainders are for http uri
    httpUri = URISupport.createRemainingURI(addressUri, parameters);
    endpoint.setHttpUri(httpUri);
    return endpoint;
}
Also used : UrlRewrite(org.apache.camel.http.common.UrlRewrite) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) Handler(org.eclipse.jetty.server.Handler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) HttpRestHeaderFilterStrategy(org.apache.camel.http.common.HttpRestHeaderFilterStrategy) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) URI(java.net.URI) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) Filter(javax.servlet.Filter) MultiPartFilter(org.eclipse.jetty.servlets.MultiPartFilter) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) HttpClient(org.eclipse.jetty.client.HttpClient) HttpBinding(org.apache.camel.http.common.HttpBinding)

Example 17 with HeaderFilterStrategy

use of org.apache.camel.spi.HeaderFilterStrategy in project camel by apache.

the class JettyHttpProducer method processInternal.

private void processInternal(Exchange exchange, AsyncCallback callback) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url from the uri
    url = uri.toASCIIString();
    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
        // update url and query string from the rewritten url
        url = rewriteUrl;
    }
    String methodName = HttpHelper.createMethod(exchange, getEndpoint(), exchange.getIn().getBody() != null).name();
    JettyContentExchange httpExchange = getEndpoint().createContentExchange();
    httpExchange.init(exchange, getBinding(), client, callback);
    // url must have scheme
    try {
        uri = new URI(url);
        String scheme = uri.getScheme();
        if (scheme == null) {
            throw new IllegalArgumentException("Url must include scheme: " + url + ". If you are bridging endpoints set bridgeEndpoint=true." + " If you want to call a specific url, then you may need to remove all CamelHttp* headers in the route before this." + " See more details at: http://camel.apache.org/how-to-remove-the-http-protocol-headers-in-the-camel-message.html");
        }
    } catch (URISyntaxException e) {
    // ignore
    }
    // Url has to be set first
    httpExchange.setURL(url);
    httpExchange.setMethod(methodName);
    if (getEndpoint().getHttpClientParameters() != null) {
        // For jetty 9 these parameters can not be set on the client
        // so we need to set them on the httpExchange
        String timeout = (String) getEndpoint().getHttpClientParameters().get("timeout");
        if (timeout != null) {
            httpExchange.setTimeout(new Long(timeout));
        }
        String supportRedirect = (String) getEndpoint().getHttpClientParameters().get("supportRedirect");
        if (supportRedirect != null) {
            httpExchange.setSupportRedirect(Boolean.valueOf(supportRedirect));
        }
    }
    LOG.trace("Using URL: {} with method: {}", url, methodName);
    // if there is a body to send as data
    if (exchange.getIn().getBody() != null) {
        String contentType = ExchangeHelper.getContentType(exchange);
        if (contentType != null) {
            httpExchange.setRequestContentType(contentType);
        }
        if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
            if (getEndpoint().getComponent().isAllowJavaSerializedObject() || getEndpoint().isTransferException()) {
                // serialized java object
                Serializable obj = exchange.getIn().getMandatoryBody(Serializable.class);
                // write object to output stream
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                try {
                    HttpHelper.writeObjectToStream(bos, obj);
                    httpExchange.setRequestContent(bos.toByteArray());
                } finally {
                    IOHelper.close(bos, "body", LOG);
                }
            } else {
                throw new RuntimeCamelException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed");
            }
        } else {
            Object body = exchange.getIn().getBody();
            if (body instanceof String) {
                String data = (String) body;
                // be a bit careful with String as any type can most likely be converted to String
                // so we only do an instanceof check and accept String if the body is really a String
                // do not fallback to use the default charset as it can influence the request
                // (for example application/x-www-form-urlencoded forms being sent)
                String charset = IOHelper.getCharsetName(exchange, false);
                httpExchange.setRequestContent(data, charset);
            } else {
                // then fallback to input stream
                InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, exchange.getIn().getBody());
                httpExchange.setRequestContent(is);
                // setup the content length if it is possible
                String length = exchange.getIn().getHeader(Exchange.CONTENT_LENGTH, String.class);
                if (ObjectHelper.isNotEmpty(length)) {
                    httpExchange.addRequestHeader(Exchange.CONTENT_LENGTH, length);
                }
            }
        }
    }
    // 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 (getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
        String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
        }
    }
    // propagate headers as HTTP headers
    Message in = exchange.getIn();
    HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();
    for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object headerValue = in.getHeader(key);
        if (headerValue != null) {
            // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
            final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);
            // the values to add as a request header
            final List<String> values = new ArrayList<String>();
            // should be combined into a single value
            while (it.hasNext()) {
                String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
                // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
                if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                    continue;
                }
                if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    values.add(value);
                }
            }
            // add the value(s) as a http request header
            if (values.size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = values.size() > 1 ? values.toString() : values.get(0);
                httpExchange.addRequestHeader(key, s);
            }
        }
    }
    if (getEndpoint().isConnectionClose()) {
        httpExchange.addRequestHeader("Connection", "close");
    }
    //if this option is set, and the exchange Host header is not null, we will set it's current value on the httpExchange
    if (getEndpoint().isPreserveHostHeader()) {
        String hostHeader = exchange.getIn().getHeader("Host", String.class);
        if (hostHeader != null) {
            //HttpClient 4 will check to see if the Host header is present, and use it if it is, see org.apache.http.protocol.RequestTargetHost in httpcore
            httpExchange.addRequestHeader("Host", hostHeader);
        }
    }
    // set the callback, which will handle all the response logic
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending HTTP request to: {}", httpExchange.getUrl());
    }
    if (getEndpoint().getCookieHandler() != null) {
        // this will store the cookie in the cookie store
        CookieStore cookieStore = getEndpoint().getCookieHandler().getCookieStore(exchange);
        if (!client.getCookieStore().equals(cookieStore)) {
            client.setCookieStore(cookieStore);
        }
    }
    httpExchange.send(client);
}
Also used : Serializable(java.io.Serializable) Message(org.apache.camel.Message) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) URISyntaxException(java.net.URISyntaxException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URI(java.net.URI) CookieStore(java.net.CookieStore) RuntimeCamelException(org.apache.camel.RuntimeCamelException) Map(java.util.Map)

Example 18 with HeaderFilterStrategy

use of org.apache.camel.spi.HeaderFilterStrategy in project camel by apache.

the class HttpPollingConsumer method doReceive.

protected Exchange doReceive(int timeout) {
    Exchange exchange = endpoint.createExchange();
    HttpMethod method = createMethod(exchange);
    // set optional timeout in millis
    if (timeout > 0) {
        method.getParams().setSoTimeout(timeout);
    }
    try {
        // execute request
        int responseCode = httpClient.executeMethod(method);
        Object body = HttpHelper.readResponseBodyFromInputStream(method.getResponseBodyAsStream(), exchange);
        // lets store the result in the output message.
        Message message = exchange.getOut();
        message.setBody(body);
        // lets set the headers
        Header[] headers = method.getResponseHeaders();
        HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy();
        for (Header header : headers) {
            String name = header.getName();
            // mapping the content-type
            if (name.toLowerCase().equals("content-type")) {
                name = Exchange.CONTENT_TYPE;
            }
            String value = header.getValue();
            if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
                message.setHeader(name, value);
            }
        }
        message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
        message.setHeader(Exchange.HTTP_RESPONSE_TEXT, method.getStatusText());
        return exchange;
    } catch (IOException e) {
        throw new RuntimeCamelException(e);
    } finally {
        method.releaseConnection();
    }
}
Also used : Exchange(org.apache.camel.Exchange) Message(org.apache.camel.Message) Header(org.apache.commons.httpclient.Header) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 19 with HeaderFilterStrategy

use of org.apache.camel.spi.HeaderFilterStrategy in project camel by apache.

the class DirectVmProducer method process.

@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    // send to consumer
    DirectVmConsumer consumer = endpoint.getComponent().getConsumer(endpoint);
    if (consumer == null) {
        if (endpoint.isFailIfNoConsumers()) {
            exchange.setException(new DirectVmConsumerNotAvailableException("No consumers available on endpoint: " + endpoint, exchange));
        } else {
            log.debug("message ignored, no consumers available on endpoint: " + endpoint);
        }
        callback.done(true);
        return true;
    }
    final HeaderFilterStrategy headerFilterStrategy = endpoint.getHeaderFilterStrategy();
    // Only clone the Exchange if we actually need to filter out properties or headers.
    final Exchange submitted = (!endpoint.isPropagateProperties() || headerFilterStrategy != null) ? exchange.copy(true) : exchange;
    // Clear properties in the copy if we are not propagating them.
    if (!endpoint.isPropagateProperties()) {
        submitted.getProperties().clear();
    }
    // Filter headers by Header Filter Strategy if there is one set.
    if (headerFilterStrategy != null) {
        submitted.getIn().getHeaders().entrySet().removeIf(e -> headerFilterStrategy.applyFilterToCamelHeaders(e.getKey(), e.getValue(), submitted));
    }
    return consumer.getAsyncProcessor().process(submitted, done -> {
        Message msg = submitted.hasOut() ? submitted.getOut() : submitted.getIn();
        if (headerFilterStrategy != null) {
            msg.getHeaders().entrySet().removeIf(e -> headerFilterStrategy.applyFilterToExternalHeaders(e.getKey(), e.getValue(), submitted));
        }
        if (exchange != submitted) {
            exchange.setException(submitted.getException());
            exchange.getOut().copyFrom(msg);
        }
        if (endpoint.isPropagateProperties()) {
            exchange.getProperties().putAll(submitted.getProperties());
        }
        callback.done(done);
    });
}
Also used : Exchange(org.apache.camel.Exchange) Message(org.apache.camel.Message) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy)

Example 20 with HeaderFilterStrategy

use of org.apache.camel.spi.HeaderFilterStrategy in project camel by apache.

the class SnsProducer method translateAttributes.

private Map<String, MessageAttributeValue> translateAttributes(Map<String, Object> headers, Exchange exchange) {
    Map<String, MessageAttributeValue> result = new HashMap<String, MessageAttributeValue>();
    HeaderFilterStrategy headerFilterStrategy = getEndpoint().getHeaderFilterStrategy();
    for (Entry<String, Object> entry : headers.entrySet()) {
        // only put the message header which is not filtered into the message attribute
        if (!headerFilterStrategy.applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), exchange)) {
            Object value = entry.getValue();
            if (value instanceof String) {
                MessageAttributeValue mav = new MessageAttributeValue();
                mav.setDataType("String");
                mav.withStringValue((String) value);
                result.put(entry.getKey(), mav);
            } else if (value instanceof ByteBuffer) {
                MessageAttributeValue mav = new MessageAttributeValue();
                mav.setDataType("Binary");
                mav.withBinaryValue((ByteBuffer) value);
                result.put(entry.getKey(), mav);
            } else {
                // cannot translate the message header to message attribute value
                LOG.warn("Cannot put the message header key={}, value={} into Sns MessageAttribute", entry.getKey(), entry.getValue());
            }
        }
    }
    return result;
}
Also used : HashMap(java.util.HashMap) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) ByteBuffer(java.nio.ByteBuffer) MessageAttributeValue(com.amazonaws.services.sns.model.MessageAttributeValue)

Aggregations

HeaderFilterStrategy (org.apache.camel.spi.HeaderFilterStrategy)23 URI (java.net.URI)8 HashMap (java.util.HashMap)8 Message (org.apache.camel.Message)7 Exchange (org.apache.camel.Exchange)6 HttpBinding (org.apache.camel.http.common.HttpBinding)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Map (java.util.Map)3 Endpoint (org.apache.camel.Endpoint)3 RuntimeCamelException (org.apache.camel.RuntimeCamelException)3 HttpRestHeaderFilterStrategy (org.apache.camel.http.common.HttpRestHeaderFilterStrategy)3 UrlRewrite (org.apache.camel.http.common.UrlRewrite)3 Test (org.junit.Test)3 MessageAttributeValue (com.amazonaws.services.sqs.model.MessageAttributeValue)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 ByteBuffer (java.nio.ByteBuffer)2 ResolveEndpointFailedException (org.apache.camel.ResolveEndpointFailedException)2 HttpProtocolHeaderFilterStrategy (org.apache.camel.http.common.HttpProtocolHeaderFilterStrategy)2