Search in sources :

Example 36 with AsyncCallback

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

the class TransactionErrorHandler method processByErrorHandler.

/**
     * Processes the {@link Exchange} using the error handler.
     * <p/>
     * This implementation will invoke ensure this occurs synchronously, that means if the async routing engine
     * did kick in, then this implementation will wait for the task to complete before it continues.
     *
     * @param exchange the exchange
     */
protected void processByErrorHandler(final Exchange exchange) {
    final CountDownLatch latch = new CountDownLatch(1);
    boolean sync = super.process(exchange, new AsyncCallback() {

        public void done(boolean doneSync) {
            if (!doneSync) {
                log.trace("Asynchronous callback received for exchangeId: {}", exchange.getExchangeId());
                latch.countDown();
            }
        }

        @Override
        public String toString() {
            return "Done " + TransactionErrorHandler.this.toString();
        }
    });
    if (!sync) {
        log.trace("Waiting for asynchronous callback before continuing for exchangeId: {} -> {}", exchange.getExchangeId(), exchange);
        try {
            latch.await();
        } catch (InterruptedException e) {
            exchange.setException(e);
        }
        log.trace("Asynchronous callback received, will continue routing exchangeId: {} -> {}", exchange.getExchangeId(), exchange);
    }
}
Also used : AsyncCallback(org.apache.camel.AsyncCallback) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 37 with AsyncCallback

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

the class WebsocketConsumer method sendMessage.

public void sendMessage(final String connectionKey, final Object message) {
    final Exchange exchange = getEndpoint().createExchange();
    // set header and body
    exchange.getIn().setHeader(WebsocketConstants.CONNECTION_KEY, connectionKey);
    exchange.getIn().setBody(message);
    // send exchange using the async routing engine
    getAsyncProcessor().process(exchange, new AsyncCallback() {

        public void done(boolean doneSync) {
            if (exchange.getException() != null) {
                getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
            }
        }
    });
}
Also used : Exchange(org.apache.camel.Exchange) AsyncCallback(org.apache.camel.AsyncCallback)

Example 38 with AsyncCallback

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

the class ReplyManagerSupport method processReply.

public void processReply(ReplyHolder holder) {
    if (holder != null && isRunAllowed()) {
        try {
            Exchange exchange = holder.getExchange();
            boolean timeout = holder.isTimeout();
            if (timeout) {
                // timeout occurred do a WARN log so its easier to spot in the logs
                if (log.isWarnEnabled()) {
                    log.warn("Timeout occurred after {} millis waiting for reply message with correlationID [{}] on destination {}." + " Setting ExchangeTimedOutException on {} and continue routing.", holder.getRequestTimeout(), holder.getCorrelationId(), replyTo, ExchangeHelper.logIds(exchange));
                }
                // no response, so lets set a timed out exception
                String msg = "reply message with correlationID: " + holder.getCorrelationId() + " not received on destination: " + replyTo;
                exchange.setException(new ExchangeTimedOutException(exchange, holder.getRequestTimeout(), msg));
            } else {
                messageConverter.populateRabbitExchange(exchange, null, holder.getProperties(), holder.getMessage(), true);
                // restore correlation id in case the remote server messed with it
                if (holder.getOriginalCorrelationId() != null) {
                    if (exchange.hasOut()) {
                        exchange.getOut().setHeader(RabbitMQConstants.CORRELATIONID, holder.getOriginalCorrelationId());
                    } else {
                        exchange.getIn().setHeader(RabbitMQConstants.CORRELATIONID, holder.getOriginalCorrelationId());
                    }
                }
            }
        } finally {
            // notify callback
            AsyncCallback callback = holder.getCallback();
            callback.done(false);
        }
    }
}
Also used : Exchange(org.apache.camel.Exchange) AsyncCallback(org.apache.camel.AsyncCallback) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException)

Example 39 with AsyncCallback

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

the class HazelcastSedaConsumer method run.

public void run() {
    final BlockingQueue<?> queue = endpoint.getQueue();
    while (queue != null && isRunAllowed()) {
        final Exchange exchange = this.getEndpoint().createExchange();
        TransactionContext transactionCtx = null;
        if (endpoint.getConfiguration().isTransacted()) {
            // Get and begin transaction if exist
            transactionCtx = endpoint.getHazelcastInstance().newTransactionContext();
            if (transactionCtx != null) {
                log.trace("Begin transaction: {}", transactionCtx.getTxnId());
                transactionCtx.beginTransaction();
            }
        }
        try {
            final Object body = queue.poll(endpoint.getConfiguration().getPollTimeout(), TimeUnit.MILLISECONDS);
            if (body != null) {
                if (body instanceof DefaultExchangeHolder) {
                    DefaultExchangeHolder.unmarshal(exchange, (DefaultExchangeHolder) body);
                } else {
                    exchange.getIn().setBody(body);
                }
                try {
                    // process using the asynchronous routing engine
                    processor.process(exchange, new AsyncCallback() {

                        public void done(boolean asyncDone) {
                        // noop
                        }
                    });
                    if (exchange.getException() != null) {
                        // Rollback
                        if (transactionCtx != null) {
                            transactionCtx.rollbackTransaction();
                        }
                        getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
                    }
                } catch (Exception e) {
                    LOG.error("Hzlq Exception caught: " + e, e);
                    // Rollback
                    if (transactionCtx != null) {
                        log.trace("Rollback transaction: {}", transactionCtx.getTxnId());
                        transactionCtx.rollbackTransaction();
                    }
                }
            }
            // It's OK, I commit
            if (exchange.getException() == null && transactionCtx != null) {
                log.trace("Commit transaction: {}", transactionCtx.getTxnId());
                transactionCtx.commitTransaction();
            }
        } catch (InterruptedException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Hzlq Consumer Interrupted: " + e, e);
            }
            continue;
        } catch (Throwable e) {
            // Rollback
            if (transactionCtx != null) {
                log.trace("Rollback transaction: {}", transactionCtx.getTxnId());
                transactionCtx.rollbackTransaction();
            }
            getExceptionHandler().handleException("Error processing exchange", exchange, e);
        }
    }
}
Also used : Exchange(org.apache.camel.Exchange) DefaultExchangeHolder(org.apache.camel.impl.DefaultExchangeHolder) TransactionContext(com.hazelcast.transaction.TransactionContext) AsyncCallback(org.apache.camel.AsyncCallback)

Example 40 with AsyncCallback

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

the class SplunkConsumer method poll.

@Override
protected int poll() throws Exception {
    try {
        if (endpoint.getConfiguration().isStreaming()) {
            dataReader.read(new SplunkResultProcessor() {

                @Override
                public void process(SplunkEvent splunkEvent) {
                    final Exchange exchange = getEndpoint().createExchange();
                    Message message = exchange.getIn();
                    message.setBody(splunkEvent);
                    try {
                        LOG.trace("Processing exchange [{}]...", exchange);
                        getAsyncProcessor().process(exchange, new AsyncCallback() {

                            @Override
                            public void done(boolean doneSync) {
                                LOG.trace("Done processing exchange [{}]...", exchange);
                            }
                        });
                    } catch (Exception e) {
                        exchange.setException(e);
                    }
                    if (exchange.getException() != null) {
                        getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
                    }
                }
            });
            // Return 0: no exchanges returned by poll, as exchanges have been returned asynchronously
            return 0;
        } else {
            List<SplunkEvent> events = dataReader.read();
            Queue<Exchange> exchanges = createExchanges(events);
            return processBatch(CastUtils.cast(exchanges));
        }
    } catch (Exception e) {
        endpoint.reset(e);
        getExceptionHandler().handleException(e);
        return 0;
    }
}
Also used : SplunkEvent(org.apache.camel.component.splunk.event.SplunkEvent) Exchange(org.apache.camel.Exchange) SplunkResultProcessor(org.apache.camel.component.splunk.support.SplunkResultProcessor) Message(org.apache.camel.Message) AsyncCallback(org.apache.camel.AsyncCallback)

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