Search in sources :

Example 71 with CamelExchangeException

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

the class SlackProducer method process.

@Override
public void process(Exchange exchange) throws Exception {
    // Create an HttpClient and Post object
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(slackEndpoint.getWebhookUrl());
    // Build Helper object
    SlackMessage slackMessage;
    Object payload = exchange.getIn().getBody();
    if (payload instanceof SlackMessage) {
        slackMessage = (SlackMessage) payload;
    } else {
        slackMessage = new SlackMessage();
        slackMessage.setText(exchange.getIn().getBody(String.class));
    }
    slackMessage.setChannel(slackEndpoint.getChannel());
    slackMessage.setUsername(slackEndpoint.getUsername());
    slackMessage.setIconUrl(slackEndpoint.getIconUrl());
    slackMessage.setIconEmoji(slackEndpoint.getIconEmoji());
    // use charset from exchange or fallback to the default charset
    String charset = IOHelper.getCharsetName(exchange, true);
    // Set the post body
    String json = asJson(slackMessage);
    StringEntity body = new StringEntity(json, charset);
    // Do the post
    httpPost.setEntity(body);
    HttpResponse response = client.execute(httpPost);
    // 2xx is OK, anything else we regard as failure
    if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
        throw new CamelExchangeException("Error POSTing to Slack API: " + response.toString(), exchange);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) CamelExchangeException(org.apache.camel.CamelExchangeException) HttpClient(org.apache.http.client.HttpClient) SlackMessage(org.apache.camel.component.slack.helper.SlackMessage) HttpResponse(org.apache.http.HttpResponse) JSONObject(org.json.simple.JSONObject)

Example 72 with CamelExchangeException

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

the class UnaryExpression method createIncExpression.

private Expression createIncExpression(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 73 with CamelExchangeException

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

the class CxfRsProducer method invokeHttpClient.

protected void invokeHttpClient(Exchange exchange) throws Exception {
    Message inMessage = exchange.getIn();
    JAXRSClientFactoryBean cfb = clientFactoryBeanCache.get(CxfEndpointUtils.getEffectiveAddress(exchange, ((CxfRsEndpoint) getEndpoint()).getAddress()));
    Bus bus = ((CxfRsEndpoint) getEndpoint()).getBus();
    // We need to apply the bus setting from the CxfRsEndpoint which is not use the default bus
    if (bus != null) {
        cfb.setBus(bus);
    }
    WebClient client = cfb.createWebClient();
    ((CxfRsEndpoint) getEndpoint()).getChainedCxfRsEndpointConfigurer().configureClient(client);
    String httpMethod = inMessage.getHeader(Exchange.HTTP_METHOD, String.class);
    Class<?> responseClass = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Class.class);
    Type genericType = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE, Type.class);
    Object[] pathValues = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, Object[].class);
    String path = inMessage.getHeader(Exchange.HTTP_PATH, String.class);
    if (LOG.isTraceEnabled()) {
        LOG.trace("HTTP method = {}", httpMethod);
        LOG.trace("path = {}", path);
        LOG.trace("responseClass = {}", responseClass);
    }
    // set the path
    if (path != null) {
        if (ObjectHelper.isNotEmpty(pathValues) && pathValues.length > 0) {
            client.path(path, pathValues);
        } else {
            client.path(path);
        }
    }
    CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint();
    CxfRsBinding binding = cxfRsEndpoint.getBinding();
    Object body = getBody(exchange, inMessage, httpMethod, cxfRsEndpoint, binding);
    setupClientMatrix(client, exchange);
    setupClientQueryAndHeaders(client, exchange);
    // handle cookies
    CookieHandler cookieHandler = ((CxfRsEndpoint) getEndpoint()).getCookieHandler();
    loadCookies(exchange, client, cookieHandler);
    // invoke the client
    Object response = null;
    if (responseClass == null || Response.class.equals(responseClass)) {
        response = client.invoke(httpMethod, body);
    } else {
        if (Collection.class.isAssignableFrom(responseClass)) {
            if (genericType instanceof ParameterizedType) {
                // Get the collection member type first
                Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
                response = client.invokeAndGetCollection(httpMethod, body, (Class<?>) actualTypeArguments[0]);
            } else {
                throw new CamelExchangeException("Header " + CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE + " not found in message", exchange);
            }
        } else {
            response = client.invoke(httpMethod, body, responseClass);
        }
    }
    int statesCode = client.getResponse().getStatus();
    // handle cookies
    saveCookies(exchange, client, cookieHandler);
    //http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
    if (throwException) {
        if (response instanceof Response) {
            Integer respCode = ((Response) response).getStatus();
            if (respCode > 207) {
                throw populateCxfRsProducerException(exchange, (Response) response, respCode);
            }
        }
    }
    // set response
    if (exchange.getPattern().isOutCapable()) {
        LOG.trace("Response body = {}", response);
        exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
        exchange.getOut().setBody(binding.bindResponseToCamelBody(response, exchange));
        exchange.getOut().getHeaders().putAll(binding.bindResponseHeadersToCamelHeaders(response, exchange));
        exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, statesCode);
    } else {
        // just close the input stream of the response object
        if (response instanceof Response) {
            ((Response) response).close();
        }
    }
}
Also used : Bus(org.apache.cxf.Bus) CamelExchangeException(org.apache.camel.CamelExchangeException) Message(org.apache.camel.Message) JAXRSClientFactoryBean(org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean) WebClient(org.apache.cxf.jaxrs.client.WebClient) Response(javax.ws.rs.core.Response) ParameterizedType(java.lang.reflect.ParameterizedType) GenericType(javax.ws.rs.core.GenericType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) CookieHandler(org.apache.camel.http.common.cookie.CookieHandler)

Example 74 with CamelExchangeException

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

the class MulticastProcessor method doProcessSequential.

private boolean doProcessSequential(final Exchange original, final AtomicExchange result, final Iterable<ProcessorExchangePair> pairs, final Iterator<ProcessorExchangePair> it, final ProcessorExchangePair pair, final AsyncCallback callback, final AtomicInteger total) {
    boolean sync = true;
    final Exchange exchange = pair.getExchange();
    Processor processor = pair.getProcessor();
    final Producer producer = pair.getProducer();
    TracedRouteNodes traced = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getTracedRouteNodes() : null;
    // compute time taken if sending to another endpoint
    final StopWatch watch = producer != null ? new StopWatch() : null;
    try {
        // prepare tracing starting from a new block
        if (traced != null) {
            traced.pushBlock();
        }
        if (producer != null) {
            EventHelper.notifyExchangeSending(exchange.getContext(), exchange, producer.getEndpoint());
        }
        // let the prepared process it, remember to begin the exchange pair
        AsyncProcessor async = AsyncProcessorConverterHelper.convert(processor);
        pair.begin();
        sync = async.process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
                // we are done with the exchange pair
                pair.done();
                // okay we are done, so notify the exchange was sent
                if (producer != null) {
                    long timeTaken = watch.stop();
                    Endpoint endpoint = producer.getEndpoint();
                    // emit event that the exchange was sent to the endpoint
                    EventHelper.notifyExchangeSent(exchange.getContext(), exchange, endpoint, timeTaken);
                }
                // we only have to handle async completion of the routing slip
                if (doneSync) {
                    return;
                }
                // continue processing the multicast asynchronously
                Exchange subExchange = exchange;
                // Decide whether to continue with the multicast or not; similar logic to the Pipeline
                // remember to test for stop on exception and aggregate before copying back results
                boolean continueProcessing = PipelineHelper.continueProcessing(subExchange, "Sequential processing failed for number " + total.get(), LOG);
                if (stopOnException && !continueProcessing) {
                    if (subExchange.getException() != null) {
                        // wrap in exception to explain where it failed
                        subExchange.setException(new CamelExchangeException("Sequential processing failed for number " + total, subExchange, subExchange.getException()));
                    } else {
                        // we want to stop on exception, and the exception was handled by the error handler
                        // this is similar to what the pipeline does, so we should do the same to not surprise end users
                        // so we should set the failed exchange as the result and be done
                        result.set(subExchange);
                    }
                    // and do the done work
                    doDone(original, subExchange, pairs, callback, false, true);
                    return;
                }
                try {
                    if (parallelAggregate) {
                        doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
                    } else {
                        doAggregate(getAggregationStrategy(subExchange), result, subExchange);
                    }
                } catch (Throwable e) {
                    // wrap in exception to explain where it failed
                    subExchange.setException(new CamelExchangeException("Sequential processing failed for number " + total, subExchange, e));
                    // and do the done work
                    doDone(original, subExchange, pairs, callback, false, true);
                    return;
                }
                total.incrementAndGet();
                // maybe there are more processors to multicast
                while (it.hasNext()) {
                    // prepare and run the next
                    ProcessorExchangePair pair = it.next();
                    subExchange = pair.getExchange();
                    updateNewExchange(subExchange, total.get(), pairs, it);
                    boolean sync = doProcessSequential(original, result, pairs, it, pair, callback, total);
                    if (!sync) {
                        LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", original.getExchangeId());
                        return;
                    }
                    // Decide whether to continue with the multicast or not; similar logic to the Pipeline
                    // remember to test for stop on exception and aggregate before copying back results
                    continueProcessing = PipelineHelper.continueProcessing(subExchange, "Sequential processing failed for number " + total.get(), LOG);
                    if (stopOnException && !continueProcessing) {
                        if (subExchange.getException() != null) {
                            // wrap in exception to explain where it failed
                            subExchange.setException(new CamelExchangeException("Sequential processing failed for number " + total, subExchange, subExchange.getException()));
                        } else {
                            // we want to stop on exception, and the exception was handled by the error handler
                            // this is similar to what the pipeline does, so we should do the same to not surprise end users
                            // so we should set the failed exchange as the result and be done
                            result.set(subExchange);
                        }
                        // and do the done work
                        doDone(original, subExchange, pairs, callback, false, true);
                        return;
                    }
                    // must catch any exceptions from aggregation
                    try {
                        if (parallelAggregate) {
                            doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
                        } else {
                            doAggregate(getAggregationStrategy(subExchange), result, subExchange);
                        }
                    } catch (Throwable e) {
                        // wrap in exception to explain where it failed
                        subExchange.setException(new CamelExchangeException("Sequential processing failed for number " + total, subExchange, e));
                        // and do the done work
                        doDone(original, subExchange, pairs, callback, false, true);
                        return;
                    }
                    total.incrementAndGet();
                }
                // do the done work
                subExchange = result.get() != null ? result.get() : null;
                doDone(original, subExchange, pairs, callback, false, true);
            }
        });
    } finally {
        // pop the block so by next round we have the same staring point and thus the tracing looks accurate
        if (traced != null) {
            traced.popBlock();
        }
    }
    return sync;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) AsyncProcessor(org.apache.camel.AsyncProcessor) Processor(org.apache.camel.Processor) AsyncCallback(org.apache.camel.AsyncCallback) StopWatch(org.apache.camel.util.StopWatch) AtomicExchange(org.apache.camel.util.concurrent.AtomicExchange) Exchange(org.apache.camel.Exchange) Producer(org.apache.camel.Producer) Endpoint(org.apache.camel.Endpoint) AsyncProcessor(org.apache.camel.AsyncProcessor) TracedRouteNodes(org.apache.camel.spi.TracedRouteNodes)

Example 75 with CamelExchangeException

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

the class Enricher method process.

/**
     * Enriches the input data (<code>exchange</code>) by first obtaining
     * additional data from an endpoint represented by an endpoint
     * <code>producer</code> and second by aggregating input data and additional
     * data. Aggregation of input data and additional data is delegated to an
     * {@link AggregationStrategy} object set at construction time. If the
     * message exchange with the resource endpoint fails then no aggregation
     * will be done and the failed exchange content is copied over to the
     * original message exchange.
     *
     * @param exchange input data.
     */
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    // which producer to use
    final Producer producer;
    final Endpoint endpoint;
    // use dynamic endpoint so calculate the endpoint to use
    Object recipient = null;
    try {
        recipient = expression.evaluate(exchange, Object.class);
        endpoint = resolveEndpoint(exchange, recipient);
        // acquire the consumer from the cache
        producer = producerCache.acquireProducer(endpoint);
    } catch (Throwable e) {
        if (isIgnoreInvalidEndpoint()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Endpoint uri is invalid: " + recipient + ". This exception will be ignored.", e);
            }
        } else {
            exchange.setException(e);
        }
        callback.done(true);
        return true;
    }
    final Exchange resourceExchange = createResourceExchange(exchange, ExchangePattern.InOut);
    final Endpoint destination = producer.getEndpoint();
    EventHelper.notifyExchangeSending(exchange.getContext(), resourceExchange, destination);
    // record timing for sending the exchange using the producer
    final StopWatch watch = new StopWatch();
    AsyncProcessor ap = AsyncProcessorConverterHelper.convert(producer);
    boolean sync = ap.process(resourceExchange, new AsyncCallback() {

        public void done(boolean doneSync) {
            // we only have to handle async completion of the routing slip
            if (doneSync) {
                return;
            }
            // emit event that the exchange was sent to the endpoint
            long timeTaken = watch.stop();
            EventHelper.notifyExchangeSent(resourceExchange.getContext(), resourceExchange, destination, timeTaken);
            if (!isAggregateOnException() && resourceExchange.isFailed()) {
                // copy resource exchange onto original exchange (preserving pattern)
                copyResultsPreservePattern(exchange, resourceExchange);
            } else {
                prepareResult(exchange);
                try {
                    // prepare the exchanges for aggregation
                    ExchangeHelper.prepareAggregation(exchange, resourceExchange);
                    Exchange aggregatedExchange = aggregationStrategy.aggregate(exchange, resourceExchange);
                    if (aggregatedExchange != null) {
                        // copy aggregation result onto original exchange (preserving pattern)
                        copyResultsPreservePattern(exchange, aggregatedExchange);
                    }
                } catch (Throwable e) {
                    // if the aggregationStrategy threw an exception, set it on the original exchange
                    exchange.setException(new CamelExchangeException("Error occurred during aggregation", exchange, e));
                    callback.done(false);
                    // we failed so break out now
                    return;
                }
            }
            // set property with the uri of the endpoint enriched so we can use that for tracing etc
            exchange.setProperty(Exchange.TO_ENDPOINT, producer.getEndpoint().getEndpointUri());
            // return the producer back to the cache
            try {
                producerCache.releaseProducer(endpoint, producer);
            } catch (Exception e) {
            // ignore
            }
            callback.done(false);
        }
    });
    if (!sync) {
        LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", exchange.getExchangeId());
        // so we break out now, then the callback will be invoked which then continue routing from where we left here
        return false;
    }
    LOG.trace("Processing exchangeId: {} is continued being processed synchronously", exchange.getExchangeId());
    // emit event that the exchange was sent to the endpoint
    long timeTaken = watch.stop();
    EventHelper.notifyExchangeSent(resourceExchange.getContext(), resourceExchange, destination, timeTaken);
    if (!isAggregateOnException() && resourceExchange.isFailed()) {
        // copy resource exchange onto original exchange (preserving pattern)
        copyResultsPreservePattern(exchange, resourceExchange);
    } else {
        prepareResult(exchange);
        try {
            // prepare the exchanges for aggregation
            ExchangeHelper.prepareAggregation(exchange, resourceExchange);
            Exchange aggregatedExchange = aggregationStrategy.aggregate(exchange, resourceExchange);
            if (aggregatedExchange != null) {
                // copy aggregation result onto original exchange (preserving pattern)
                copyResultsPreservePattern(exchange, aggregatedExchange);
            }
        } catch (Throwable e) {
            // if the aggregationStrategy threw an exception, set it on the original exchange
            exchange.setException(new CamelExchangeException("Error occurred during aggregation", exchange, e));
            callback.done(true);
            // we failed so break out now
            return true;
        }
    }
    // set property with the uri of the endpoint enriched so we can use that for tracing etc
    exchange.setProperty(Exchange.TO_ENDPOINT, producer.getEndpoint().getEndpointUri());
    // return the producer back to the cache
    try {
        producerCache.releaseProducer(endpoint, producer);
    } catch (Exception e) {
    // ignore
    }
    callback.done(true);
    return true;
}
Also used : Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) CamelExchangeException(org.apache.camel.CamelExchangeException) Producer(org.apache.camel.Producer) Endpoint(org.apache.camel.Endpoint) AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncCallback(org.apache.camel.AsyncCallback) CamelExchangeException(org.apache.camel.CamelExchangeException) StopWatch(org.apache.camel.util.StopWatch)

Aggregations

CamelExchangeException (org.apache.camel.CamelExchangeException)82 IApplication (com.openshift.client.IApplication)23 Exchange (org.apache.camel.Exchange)17 IOException (java.io.IOException)10 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)8 IEnvironmentVariable (com.openshift.client.IEnvironmentVariable)5 InputStream (java.io.InputStream)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 AsyncCallback (org.apache.camel.AsyncCallback)5 CamelExecutionException (org.apache.camel.CamelExecutionException)5 Message (org.apache.camel.Message)5 File (java.io.File)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Processor (org.apache.camel.Processor)4 RouteBuilder (org.apache.camel.builder.RouteBuilder)4 IEmbeddedCartridge (com.openshift.client.cartridge.IEmbeddedCartridge)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Serializable (java.io.Serializable)3 URI (java.net.URI)3 List (java.util.List)3