Search in sources :

Example 1 with CamelExchangeException

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

the class LanguageProducer method process.

public void process(Exchange exchange) throws Exception {
    String script = null;
    // is there a custom expression in the header?
    Expression exp = exchange.getIn().getHeader(Exchange.LANGUAGE_SCRIPT, Expression.class);
    if (exp == null) {
        script = exchange.getIn().getHeader(Exchange.LANGUAGE_SCRIPT, String.class);
        if (script != null) {
            // the script may be a file: so resolve it before using
            script = getEndpoint().resolveScript(script);
            exp = getEndpoint().getLanguage().createExpression(script);
        }
    }
    // if not fallback to use expression from endpoint
    if (exp == null && getEndpoint().isCacheScript()) {
        exp = getEndpoint().getExpression();
    }
    // the script can be a resource from the endpoint,
    // or refer to a resource itself
    // or just be a plain string
    InputStream is = null;
    // fallback and use resource uri from endpoint
    if (exp == null) {
        script = getEndpoint().getScript();
        if (script == null && getEndpoint().getResourceUri() == null) {
            // no script to execute
            throw new CamelExchangeException("No script to evaluate", exchange);
        }
        if (script == null) {
            is = getEndpoint().getResourceAsInputStream();
        } else if (ResourceHelper.hasScheme(script)) {
            is = ResourceHelper.resolveMandatoryResourceAsInputStream(getEndpoint().getCamelContext(), script);
        }
        if (is != null && !getEndpoint().isBinary()) {
            try {
                script = getEndpoint().getCamelContext().getTypeConverter().convertTo(String.class, exchange, is);
            } finally {
                IOHelper.close(is);
            }
        }
    }
    // if we have a text based script then use and evaluate it
    if (script != null) {
        // create the expression from the script
        exp = getEndpoint().getLanguage().createExpression(script);
        // expression was resolved from resource
        getEndpoint().setContentResolvedFromResource(true);
        // if we cache then set this as expression on endpoint so we don't re-create it again
        if (getEndpoint().isCacheScript()) {
            getEndpoint().setExpression(exp);
        }
    }
    // the result is either the result of the expression or the input stream as-is because its binary content
    Object result;
    if (exp != null) {
        try {
            result = exp.evaluate(exchange, Object.class);
            log.debug("Evaluated expression as: {} with: {}", result, exchange);
        } finally {
            if (!getEndpoint().isCacheScript()) {
                // some languages add themselves as a service which we then need to remove if we are not cached
                ServiceHelper.stopService(exp);
                getEndpoint().getCamelContext().removeService(exp);
            }
        }
    } else {
        // use the result as-is
        result = is;
    }
    // set message body if transform is enabled
    if (getEndpoint().isTransform()) {
        if (exchange.hasOut()) {
            exchange.getOut().setBody(result);
        } else {
            exchange.getIn().setBody(result);
        }
    }
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Expression(org.apache.camel.Expression) InputStream(java.io.InputStream)

Example 2 with CamelExchangeException

use of org.apache.camel.CamelExchangeException 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 3 with CamelExchangeException

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

the class MulticastProcessor method doProcessSequential.

protected boolean doProcessSequential(Exchange original, AtomicExchange result, Iterable<ProcessorExchangePair> pairs, AsyncCallback callback) throws Exception {
    AtomicInteger total = new AtomicInteger();
    Iterator<ProcessorExchangePair> it = pairs.iterator();
    while (it.hasNext()) {
        ProcessorExchangePair pair = it.next();
        // in case the iterator returns null then continue to next
        if (pair == null) {
            continue;
        }
        Exchange subExchange = pair.getExchange();
        updateNewExchange(subExchange, total.get(), pairs, it);
        boolean sync = doProcessSequential(original, result, pairs, it, pair, callback, total);
        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", pair.getExchange().getExchangeId());
            }
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: {} is continued being processed synchronously", pair.getExchange().getExchangeId());
        }
        // 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
                CamelExchangeException cause = new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException());
                subExchange.setException(cause);
            }
            // 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);
            return true;
        }
        LOG.trace("Sequential processing complete for number {} exchange: {}", total, subExchange);
        if (parallelAggregate) {
            doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
        } else {
            doAggregate(getAggregationStrategy(subExchange), result, subExchange);
        }
        total.incrementAndGet();
    }
    LOG.debug("Done sequential processing {} exchanges", total);
    return true;
}
Also used : AtomicExchange(org.apache.camel.util.concurrent.AtomicExchange) Exchange(org.apache.camel.Exchange) CamelExchangeException(org.apache.camel.CamelExchangeException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 4 with CamelExchangeException

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

the class PollEnricher 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 org.apache.camel.processor.aggregate.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.
     */
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    try {
        preCheckPoll(exchange);
    } catch (Exception e) {
        exchange.setException(new CamelExchangeException("Error during pre poll check", exchange, e));
        callback.done(true);
        return true;
    }
    // which consumer to use
    PollingConsumer consumer;
    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
        consumer = consumerCache.acquirePollingConsumer(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;
    }
    // grab the real delegate consumer that performs the actual polling
    Consumer delegate = consumer;
    if (consumer instanceof EventDrivenPollingConsumer) {
        delegate = ((EventDrivenPollingConsumer) consumer).getDelegateConsumer();
    }
    // is the consumer bridging the error handler?
    boolean bridgeErrorHandler = false;
    if (delegate instanceof DefaultConsumer) {
        ExceptionHandler handler = ((DefaultConsumer) delegate).getExceptionHandler();
        if (handler != null && handler instanceof BridgeExceptionHandlerToErrorHandler) {
            bridgeErrorHandler = true;
        }
    }
    Exchange resourceExchange;
    try {
        if (timeout < 0) {
            LOG.debug("Consumer receive: {}", consumer);
            resourceExchange = consumer.receive();
        } else if (timeout == 0) {
            LOG.debug("Consumer receiveNoWait: {}", consumer);
            resourceExchange = consumer.receiveNoWait();
        } else {
            LOG.debug("Consumer receive with timeout: {} ms. {}", timeout, consumer);
            resourceExchange = consumer.receive(timeout);
        }
        if (resourceExchange == null) {
            LOG.debug("Consumer received no exchange");
        } else {
            LOG.debug("Consumer received: {}", resourceExchange);
        }
    } catch (Exception e) {
        exchange.setException(new CamelExchangeException("Error during poll", exchange, e));
        callback.done(true);
        return true;
    } finally {
        // return the consumer back to the cache
        consumerCache.releasePollingConsumer(endpoint, consumer);
    }
    // remember current redelivery stats
    Object redeliveried = exchange.getIn().getHeader(Exchange.REDELIVERED);
    Object redeliveryCounter = exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER);
    Object redeliveryMaxCounter = exchange.getIn().getHeader(Exchange.REDELIVERY_MAX_COUNTER);
    // if we are bridging error handler and failed then remember the caused exception
    Throwable cause = null;
    if (resourceExchange != null && bridgeErrorHandler) {
        cause = resourceExchange.getException();
    }
    try {
        if (!isAggregateOnException() && (resourceExchange != null && resourceExchange.isFailed())) {
            // copy resource exchange onto original exchange (preserving pattern)
            // and preserve redelivery headers
            copyResultsPreservePattern(exchange, resourceExchange);
        } else {
            prepareResult(exchange);
            // prepare the exchanges for aggregation
            ExchangeHelper.prepareAggregation(exchange, resourceExchange);
            // must catch any exception from aggregation
            Exchange aggregatedExchange = aggregationStrategy.aggregate(exchange, resourceExchange);
            if (aggregatedExchange != null) {
                // copy aggregation result onto original exchange (preserving pattern)
                copyResultsPreservePattern(exchange, aggregatedExchange);
                // handover any synchronization
                if (resourceExchange != null) {
                    resourceExchange.handoverCompletions(exchange);
                }
            }
        }
        // if we failed then restore caused exception
        if (cause != null) {
            // restore caused exception
            exchange.setException(cause);
            // remove the exhausted marker as we want to be able to perform redeliveries with the error handler
            exchange.removeProperties(Exchange.REDELIVERY_EXHAUSTED);
            // preserve the redelivery stats
            if (redeliveried != null) {
                if (exchange.hasOut()) {
                    exchange.getOut().setHeader(Exchange.REDELIVERED, redeliveried);
                } else {
                    exchange.getIn().setHeader(Exchange.REDELIVERED, redeliveried);
                }
            }
            if (redeliveryCounter != null) {
                if (exchange.hasOut()) {
                    exchange.getOut().setHeader(Exchange.REDELIVERY_COUNTER, redeliveryCounter);
                } else {
                    exchange.getIn().setHeader(Exchange.REDELIVERY_COUNTER, redeliveryCounter);
                }
            }
            if (redeliveryMaxCounter != null) {
                if (exchange.hasOut()) {
                    exchange.getOut().setHeader(Exchange.REDELIVERY_MAX_COUNTER, redeliveryMaxCounter);
                } else {
                    exchange.getIn().setHeader(Exchange.REDELIVERY_MAX_COUNTER, redeliveryMaxCounter);
                }
            }
        }
        // set header with the uri of the endpoint enriched so we can use that for tracing etc
        if (exchange.hasOut()) {
            exchange.getOut().setHeader(Exchange.TO_ENDPOINT, consumer.getEndpoint().getEndpointUri());
        } else {
            exchange.getIn().setHeader(Exchange.TO_ENDPOINT, consumer.getEndpoint().getEndpointUri());
        }
    } catch (Throwable e) {
        exchange.setException(new CamelExchangeException("Error occurred during aggregation", exchange, e));
        callback.done(true);
        return true;
    }
    callback.done(true);
    return true;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) PollingConsumer(org.apache.camel.PollingConsumer) EventDrivenPollingConsumer(org.apache.camel.impl.EventDrivenPollingConsumer) DefaultConsumer(org.apache.camel.impl.DefaultConsumer) EventDrivenPollingConsumer(org.apache.camel.impl.EventDrivenPollingConsumer) CamelExchangeException(org.apache.camel.CamelExchangeException) BridgeExceptionHandlerToErrorHandler(org.apache.camel.impl.BridgeExceptionHandlerToErrorHandler) ExceptionHandler(org.apache.camel.spi.ExceptionHandler) Exchange(org.apache.camel.Exchange) Endpoint(org.apache.camel.Endpoint) PollingConsumer(org.apache.camel.PollingConsumer) Consumer(org.apache.camel.Consumer) EventDrivenPollingConsumer(org.apache.camel.impl.EventDrivenPollingConsumer) DefaultConsumer(org.apache.camel.impl.DefaultConsumer)

Example 5 with CamelExchangeException

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

the class FileConsumePollEnrichFileUsingProcessorTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("file://target/enrich?move=.done").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    String name = exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY, String.class);
                    name = FileUtil.stripExt(name) + ".dat";
                    // use a consumer template to get the data file
                    Exchange data = null;
                    ConsumerTemplate con = exchange.getContext().createConsumerTemplate();
                    try {
                        // try to get the data file
                        data = con.receive("file://target/enrichdata?move=.done&fileName=" + name, 5000);
                    } finally {
                        // stop the consumer as it does not need to poll for files anymore
                        con.stop();
                    }
                    // if we found the data file then process it by sending it to the direct:data endpoint
                    if (data != null) {
                        template.send("direct:data", data);
                    } else {
                        // otherwise do a rollback
                        throw new CamelExchangeException("Cannot find the data file " + name, exchange);
                    }
                }
            }).to("mock:start");
            from("direct:data").to("mock:result");
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) ConsumerTemplate(org.apache.camel.ConsumerTemplate) CamelExchangeException(org.apache.camel.CamelExchangeException) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder)

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