Search in sources :

Example 16 with AsyncProcessor

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

the class TryProcessor method process.

protected boolean process(final Exchange exchange, final AsyncCallback callback, final Iterator<Processor> processors, final AsyncProcessor processor, final Object lastHandled) {
    // this does the actual processing so log at trace level
    LOG.trace("Processing exchangeId: {} >>> {}", exchange.getExchangeId(), exchange);
    // implement asynchronous routing logic in callback so we can have the callback being
    // triggered and then continue routing where we left
    boolean sync = processor.process(exchange, new AsyncCallback() {

        public void done(boolean doneSync) {
            // we only have to handle async completion of the pipeline
            if (doneSync) {
                return;
            }
            // continue processing the try .. catch .. finally asynchronously
            while (continueRouting(processors, exchange)) {
                exchange.setProperty(Exchange.TRY_ROUTE_BLOCK, true);
                ExchangeHelper.prepareOutToIn(exchange);
                // process the next processor
                AsyncProcessor processor = AsyncProcessorConverterHelper.convert(processors.next());
                doneSync = process(exchange, callback, processors, processor, lastHandled);
                if (!doneSync) {
                    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;
                }
            }
            ExchangeHelper.prepareOutToIn(exchange);
            exchange.removeProperty(Exchange.TRY_ROUTE_BLOCK);
            exchange.setProperty(Exchange.EXCEPTION_HANDLED, lastHandled);
            LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange);
            callback.done(false);
        }
    });
    return sync;
}
Also used : AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncCallback(org.apache.camel.AsyncCallback)

Example 17 with AsyncProcessor

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

the class RoutingSlip method processExchange.

protected boolean processExchange(final Endpoint endpoint, final Exchange exchange, final Exchange original, final AsyncCallback callback, final RoutingSlipIterator iter) {
    // this does the actual processing so log at trace level
    log.trace("Processing exchangeId: {} >>> {}", exchange.getExchangeId(), exchange);
    boolean sync = producerCache.doInAsyncProducer(endpoint, exchange, null, callback, new AsyncProducerCallback() {

        public boolean doInAsyncProducer(Producer producer, AsyncProcessor asyncProducer, final Exchange exchange, ExchangePattern exchangePattern, final AsyncCallback callback) {
            // rework error handling to support fine grained error handling
            RouteContext routeContext = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
            AsyncProcessor target = createErrorHandler(routeContext, exchange, asyncProducer, endpoint);
            // set property which endpoint we send to
            exchange.setProperty(Exchange.TO_ENDPOINT, endpoint.getEndpointUri());
            exchange.setProperty(Exchange.SLIP_ENDPOINT, endpoint.getEndpointUri());
            boolean answer = target.process(exchange, new AsyncCallback() {

                public void done(boolean doneSync) {
                    // we only have to handle async completion of the routing slip
                    if (doneSync) {
                        callback.done(doneSync);
                        return;
                    }
                    // continue processing the routing slip asynchronously
                    Exchange current = prepareExchangeForRoutingSlip(exchange, endpoint);
                    while (iter.hasNext(current)) {
                        // we ignore some kind of exceptions and allow us to continue
                        if (isIgnoreInvalidEndpoints()) {
                            FailedToCreateProducerException e = current.getException(FailedToCreateProducerException.class);
                            if (e != null) {
                                if (log.isDebugEnabled()) {
                                    log.debug("Endpoint uri is invalid: " + endpoint + ". This exception will be ignored.", e);
                                }
                                current.setException(null);
                            }
                        }
                        // check for error if so we should break out
                        if (!continueProcessing(current, "so breaking out of the routing slip", log)) {
                            break;
                        }
                        Endpoint endpoint;
                        try {
                            endpoint = resolveEndpoint(iter, exchange);
                            // if no endpoint was resolved then try the next
                            if (endpoint == null) {
                                continue;
                            }
                        } catch (Exception e) {
                            // error resolving endpoint so we should break out
                            exchange.setException(e);
                            break;
                        }
                        // prepare and process the routing slip
                        boolean sync = processExchange(endpoint, current, original, callback, iter);
                        current = prepareExchangeForRoutingSlip(current, endpoint);
                        if (!sync) {
                            log.trace("Processing exchangeId: {} is continued being processed asynchronously", original.getExchangeId());
                            return;
                        }
                    }
                    // logging nextExchange as it contains the exchange that might have altered the payload and since
                    // we are logging the completion if will be confusing if we log the original instead
                    // we could also consider logging the original and the nextExchange then we have *before* and *after* snapshots
                    log.trace("Processing complete for exchangeId: {} >>> {}", original.getExchangeId(), current);
                    // copy results back to the original exchange
                    ExchangeHelper.copyResults(original, current);
                    if (target instanceof DeadLetterChannel) {
                        Processor deadLetter = ((DeadLetterChannel) target).getDeadLetter();
                        try {
                            ServiceHelper.stopService(deadLetter);
                        } catch (Exception e) {
                            log.warn("Error stopping DeadLetterChannel error handler on routing slip. This exception is ignored.", e);
                        }
                    }
                    callback.done(false);
                }
            });
            // stop error handler if we completed synchronously
            if (answer) {
                if (target instanceof DeadLetterChannel) {
                    Processor deadLetter = ((DeadLetterChannel) target).getDeadLetter();
                    try {
                        ServiceHelper.stopService(deadLetter);
                    } catch (Exception e) {
                        log.warn("Error stopping DeadLetterChannel error handler on routing slip. This exception is ignored.", e);
                    }
                }
            }
            return answer;
        }
    });
    return sync;
}
Also used : Processor(org.apache.camel.Processor) AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncCallback(org.apache.camel.AsyncCallback) FailedToCreateProducerException(org.apache.camel.FailedToCreateProducerException) RouteContext(org.apache.camel.spi.RouteContext) Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) FailedToCreateProducerException(org.apache.camel.FailedToCreateProducerException) AsyncProducerCallback(org.apache.camel.AsyncProducerCallback) Producer(org.apache.camel.Producer) Endpoint(org.apache.camel.Endpoint) ExchangePattern(org.apache.camel.ExchangePattern) AsyncProcessor(org.apache.camel.AsyncProcessor)

Example 18 with AsyncProcessor

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

the class SendProcessor method process.

public boolean process(Exchange exchange, final AsyncCallback callback) {
    if (!isStarted()) {
        exchange.setException(new IllegalStateException("SendProcessor has not been started: " + this));
        callback.done(true);
        return true;
    }
    // we should preserve existing MEP so remember old MEP
    // if you want to permanently to change the MEP then use .setExchangePattern in the DSL
    final ExchangePattern existingPattern = exchange.getPattern();
    counter++;
    // if we have a producer then use that as its optimized
    if (producer != null) {
        // record timing for sending the exchange using the producer
        final StopWatch watch = new StopWatch();
        final Exchange target = configureExchange(exchange, pattern);
        EventHelper.notifyExchangeSending(exchange.getContext(), target, destination);
        LOG.debug(">>>> {} {}", destination, exchange);
        boolean sync = true;
        try {
            sync = producer.process(exchange, new AsyncCallback() {

                @Override
                public void done(boolean doneSync) {
                    try {
                        // restore previous MEP
                        target.setPattern(existingPattern);
                        // emit event that the exchange was sent to the endpoint
                        long timeTaken = watch.stop();
                        EventHelper.notifyExchangeSent(target.getContext(), target, destination, timeTaken);
                    } finally {
                        callback.done(doneSync);
                    }
                }
            });
        } catch (Throwable throwable) {
            exchange.setException(throwable);
            callback.done(sync);
        }
        return sync;
    }
    // send the exchange to the destination using the producer cache for the non optimized producers
    return producerCache.doInAsyncProducer(destination, exchange, pattern, callback, new AsyncProducerCallback() {

        public boolean doInAsyncProducer(Producer producer, AsyncProcessor asyncProducer, final Exchange exchange, ExchangePattern pattern, final AsyncCallback callback) {
            final Exchange target = configureExchange(exchange, pattern);
            LOG.debug(">>>> {} {}", destination, exchange);
            return asyncProducer.process(target, new AsyncCallback() {

                public void done(boolean doneSync) {
                    // restore previous MEP
                    target.setPattern(existingPattern);
                    // signal we are done
                    callback.done(doneSync);
                }
            });
        }
    });
}
Also used : Exchange(org.apache.camel.Exchange) AsyncProducerCallback(org.apache.camel.AsyncProducerCallback) Producer(org.apache.camel.Producer) ExchangePattern(org.apache.camel.ExchangePattern) AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncCallback(org.apache.camel.AsyncCallback) StopWatch(org.apache.camel.util.StopWatch)

Example 19 with AsyncProcessor

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

the class QueueLoadBalancer method process.

public boolean process(final Exchange exchange, final AsyncCallback callback) {
    List<Processor> list = getProcessors();
    if (!list.isEmpty()) {
        Processor processor = chooseProcessor(list, exchange);
        if (processor == null) {
            Exception e = new IllegalStateException("No processors could be chosen to process " + exchange);
            exchange.setException(e);
        } else {
            if (processor instanceof AsyncProcessor) {
                AsyncProcessor async = (AsyncProcessor) processor;
                return async.process(exchange, callback);
            } else {
                try {
                    processor.process(exchange);
                } catch (Exception e) {
                    exchange.setException(e);
                }
                callback.done(true);
                return true;
            }
        }
    }
    // no processors but indicate we are done
    callback.done(true);
    return true;
}
Also used : Processor(org.apache.camel.Processor) AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncProcessor(org.apache.camel.AsyncProcessor)

Example 20 with AsyncProcessor

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

the class CircuitBreakerLoadBalancer method executeProcessor.

private boolean executeProcessor(final Exchange exchange, final AsyncCallback callback) {
    Processor processor = getProcessors().get(0);
    if (processor == null) {
        throw new IllegalStateException("No processors could be chosen to process CircuitBreaker");
    }
    // store state as exchange property
    exchange.setProperty(Exchange.CIRCUIT_BREAKER_STATE, stateAsString(state.get()));
    AsyncProcessor albp = AsyncProcessorConverterHelper.convert(processor);
    // Added a callback for processing the exchange in the callback
    boolean sync = albp.process(exchange, new CircuitBreakerCallback(exchange, callback));
    // We need to check the exception here as albp is use sync call
    if (sync) {
        boolean failed = hasFailed(exchange);
        if (!failed) {
            failures.set(0);
        } else {
            failures.incrementAndGet();
            lastFailure = System.currentTimeMillis();
        }
    } else {
        // CircuitBreakerCallback can take care of failure check of the
        // exchange
        log.trace("Processing exchangeId: {} is continued being processed asynchronously", exchange.getExchangeId());
        return false;
    }
    log.trace("Processing exchangeId: {} is continued being processed synchronously", exchange.getExchangeId());
    callback.done(true);
    return true;
}
Also used : Processor(org.apache.camel.Processor) AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncProcessor(org.apache.camel.AsyncProcessor)

Aggregations

AsyncProcessor (org.apache.camel.AsyncProcessor)23 AsyncCallback (org.apache.camel.AsyncCallback)11 Exchange (org.apache.camel.Exchange)11 Processor (org.apache.camel.Processor)10 Producer (org.apache.camel.Producer)7 Endpoint (org.apache.camel.Endpoint)5 StopWatch (org.apache.camel.util.StopWatch)5 ExchangePattern (org.apache.camel.ExchangePattern)4 FailedToCreateProducerException (org.apache.camel.FailedToCreateProducerException)4 AsyncProducerCallback (org.apache.camel.AsyncProducerCallback)3 CamelExchangeException (org.apache.camel.CamelExchangeException)3 DefaultExchange (org.apache.camel.impl.DefaultExchange)2 TracedRouteNodes (org.apache.camel.spi.TracedRouteNodes)2 AtomicExchange (org.apache.camel.util.concurrent.AtomicExchange)2 ByteBuf (io.netty.buffer.ByteBuf)1 InetSocketAddress (java.net.InetSocketAddress)1 ByteBuffer (java.nio.ByteBuffer)1 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)1 CamelContextAware (org.apache.camel.CamelContextAware)1 ErrorHandlerFactory (org.apache.camel.ErrorHandlerFactory)1