Search in sources :

Example 6 with AsyncCallback

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

the class ChoiceProcessor method process.

public boolean process(final Exchange exchange, final AsyncCallback callback) {
    Iterator<Processor> processors = next().iterator();
    // callback to restore existing FILTER_MATCHED property on the Exchange
    final Object existing = exchange.getProperty(Exchange.FILTER_MATCHED);
    final AsyncCallback choiceCallback = new AsyncCallback() {

        @Override
        public void done(boolean doneSync) {
            if (existing != null) {
                exchange.setProperty(Exchange.FILTER_MATCHED, existing);
            } else {
                exchange.removeProperty(Exchange.FILTER_MATCHED);
            }
            callback.done(doneSync);
        }
    };
    // and if not, we just continue without using any processor
    while (processors.hasNext()) {
        // get the next processor
        Processor processor = processors.next();
        // evaluate the predicate on filter predicate early to be faster
        // and avoid issues when having nested choices
        // as we should only pick one processor
        boolean matches = false;
        if (processor instanceof FilterProcessor) {
            FilterProcessor filter = (FilterProcessor) processor;
            try {
                matches = filter.matches(exchange);
                // as we have pre evaluated the predicate then use its processor directly when routing
                processor = filter.getProcessor();
            } catch (Throwable e) {
                exchange.setException(e);
            }
        } else {
            // its the otherwise processor, so its a match
            notFiltered++;
            matches = true;
        }
        // check for error if so we should break out
        if (!continueProcessing(exchange, "so breaking out of choice", LOG)) {
            break;
        }
        // if we did not match then continue to next filter
        if (!matches) {
            continue;
        }
        // okay we found a filter or its the otherwise we are processing
        AsyncProcessor async = AsyncProcessorConverterHelper.convert(processor);
        return async.process(exchange, choiceCallback);
    }
    // when no filter matches and there is no otherwise, then just continue
    choiceCallback.done(true);
    return true;
}
Also used : Processor(org.apache.camel.Processor) AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncCallback(org.apache.camel.AsyncCallback)

Example 7 with AsyncCallback

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

the class DdbStreamConsumer method processBatch.

@Override
public int processBatch(Queue<Object> exchanges) throws Exception {
    int processedExchanges = 0;
    while (!exchanges.isEmpty()) {
        final Exchange exchange = ObjectHelper.cast(Exchange.class, exchanges.poll());
        LOG.trace("Processing exchange [{}] started.", exchange);
        getAsyncProcessor().process(exchange, new AsyncCallback() {

            @Override
            public void done(boolean doneSync) {
                LOG.trace("Processing exchange [{}] done.", exchange);
            }
        });
        processedExchanges++;
    }
    return processedExchanges;
}
Also used : Exchange(org.apache.camel.Exchange) AsyncCallback(org.apache.camel.AsyncCallback)

Example 8 with AsyncCallback

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

the class IdempotentConsumer method process.

public boolean process(final Exchange exchange, final AsyncCallback callback) {
    final AsyncCallback target;
    final String messageId;
    try {
        messageId = messageIdExpression.evaluate(exchange, String.class);
        if (messageId == null) {
            exchange.setException(new NoMessageIdException(exchange, messageIdExpression));
            callback.done(true);
            return true;
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    try {
        boolean newKey;
        if (eager) {
            // add the key to the repository
            if (idempotentRepository instanceof ExchangeIdempotentRepository) {
                newKey = ((ExchangeIdempotentRepository<String>) idempotentRepository).add(exchange, messageId);
            } else {
                newKey = idempotentRepository.add(messageId);
            }
        } else {
            // check if we already have the key
            if (idempotentRepository instanceof ExchangeIdempotentRepository) {
                newKey = !((ExchangeIdempotentRepository<String>) idempotentRepository).contains(exchange, messageId);
            } else {
                newKey = !idempotentRepository.contains(messageId);
            }
        }
        if (!newKey) {
            // mark the exchange as duplicate
            exchange.setProperty(Exchange.DUPLICATE_MESSAGE, Boolean.TRUE);
            // we already have this key so its a duplicate message
            onDuplicate(exchange, messageId);
            if (skipDuplicate) {
                // if we should skip duplicate then we are done
                LOG.debug("Ignoring duplicate message with id: {} for exchange: {}", messageId, exchange);
                callback.done(true);
                return true;
            }
        }
        final Synchronization onCompletion = new IdempotentOnCompletion(idempotentRepository, messageId, eager, removeOnFailure);
        target = new IdempotentConsumerCallback(exchange, onCompletion, callback, completionEager);
        if (!completionEager) {
            // the scope is to do the idempotent completion work as an unit of work on the exchange when its done being routed
            exchange.addOnCompletion(onCompletion);
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // process the exchange
    return processor.process(exchange, target);
}
Also used : AsyncCallback(org.apache.camel.AsyncCallback) Synchronization(org.apache.camel.spi.Synchronization) ExchangeIdempotentRepository(org.apache.camel.spi.ExchangeIdempotentRepository)

Example 9 with AsyncCallback

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

the class SendDynamicProcessor 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();
    // which endpoint to send to
    final Endpoint endpoint;
    final ExchangePattern destinationExchangePattern;
    // use dynamic endpoint so calculate the endpoint to use
    Object recipient = null;
    try {
        recipient = expression.evaluate(exchange, Object.class);
        endpoint = resolveEndpoint(exchange, recipient);
        destinationExchangePattern = EndpointHelper.resolveExchangePatternFromUrl(endpoint.getEndpointUri());
    } 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;
    }
    // send the exchange to the destination using the producer cache
    return producerCache.doInAsyncProducer(endpoint, 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, destinationExchangePattern, endpoint);
            LOG.debug(">>>> {} {}", endpoint, 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) Endpoint(org.apache.camel.Endpoint) Producer(org.apache.camel.Producer) ExchangePattern(org.apache.camel.ExchangePattern) AsyncProcessor(org.apache.camel.AsyncProcessor) AsyncCallback(org.apache.camel.AsyncCallback)

Example 10 with AsyncCallback

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

the class AsyncProcessorHelper method process.

/**
     * Calls the async version of the processor's process method and waits
     * for it to complete before returning. This can be used by {@link AsyncProcessor}
     * objects to implement their sync version of the process method.
     * <p/>
     * <b>Important:</b> This method is discouraged to be used, as its better to invoke the asynchronous
     * {@link AsyncProcessor#process(org.apache.camel.Exchange, org.apache.camel.AsyncCallback)} method, whenever possible.
     *
     * @param processor the processor
     * @param exchange  the exchange
     * @throws Exception can be thrown if waiting is interrupted
     */
public static void process(final AsyncProcessor processor, final Exchange exchange) throws Exception {
    final AsyncProcessorAwaitManager awaitManager = exchange.getContext().getAsyncProcessorAwaitManager();
    final CountDownLatch latch = new CountDownLatch(1);
    boolean sync = processor.process(exchange, new AsyncCallback() {

        public void done(boolean doneSync) {
            if (!doneSync) {
                awaitManager.countDown(exchange, latch);
            }
        }

        @Override
        public String toString() {
            return "Done " + processor;
        }
    });
    if (!sync) {
        awaitManager.await(exchange, latch);
    }
}
Also used : AsyncCallback(org.apache.camel.AsyncCallback) AsyncProcessorAwaitManager(org.apache.camel.spi.AsyncProcessorAwaitManager) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

AsyncCallback (org.apache.camel.AsyncCallback)67 Exchange (org.apache.camel.Exchange)47 AsyncProcessor (org.apache.camel.AsyncProcessor)12 CamelExchangeException (org.apache.camel.CamelExchangeException)8 Message (org.apache.camel.Message)5 Processor (org.apache.camel.Processor)5 CountDownLatch (java.util.concurrent.CountDownLatch)4 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)4 Endpoint (org.apache.camel.Endpoint)4 Producer (org.apache.camel.Producer)4 Synchronization (org.apache.camel.spi.Synchronization)4 StopWatch (org.apache.camel.util.StopWatch)4 InetSocketAddress (java.net.InetSocketAddress)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ExchangePattern (org.apache.camel.ExchangePattern)3 ChannelHandler (io.netty.channel.ChannelHandler)2 IOException (java.io.IOException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 ConnectException (java.net.ConnectException)2