Search in sources :

Example 21 with AsyncCallback

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

the class SalesforceConsumer method processMessage.

public void processMessage(ClientSessionChannel channel, Message message) {
    final Exchange exchange = endpoint.createExchange();
    org.apache.camel.Message in = exchange.getIn();
    setHeaders(in, message);
    // get event data
    // TODO do we need to add NPE checks for message/data.get***???
    Map<String, Object> data = message.getDataAsMap();
    @SuppressWarnings("unchecked") final Map<String, Object> event = (Map<String, Object>) data.get(EVENT_PROPERTY);
    final Object eventType = event.get(TYPE_PROPERTY);
    Object createdDate = event.get(CREATED_DATE_PROPERTY);
    Object replayId = event.get(REPLAY_ID_PROPERTY);
    if (log.isDebugEnabled()) {
        log.debug(String.format("Received event %s on channel %s created on %s", eventType, channel.getChannelId(), createdDate));
    }
    in.setHeader("CamelSalesforceEventType", eventType);
    in.setHeader("CamelSalesforceCreatedDate", createdDate);
    if (replayId != null) {
        in.setHeader("CamelSalesforceReplayId", replayId);
    }
    // get SObject
    @SuppressWarnings("unchecked") final Map<String, Object> sObject = (Map<String, Object>) data.get(SOBJECT_PROPERTY);
    try {
        final String sObjectString = objectMapper.writeValueAsString(sObject);
        log.debug("Received SObject: {}", sObjectString);
        if (sObjectClass == null) {
            // return sobject map as exchange body
            in.setBody(sObject);
        } else {
            // create the expected SObject
            in.setBody(objectMapper.readValue(new StringReader(sObjectString), sObjectClass));
        }
    } catch (IOException e) {
        final String msg = String.format("Error parsing message [%s] from Topic %s: %s", message, topicName, e.getMessage());
        handleException(msg, new SalesforceException(msg, e));
    }
    try {
        getAsyncProcessor().process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
                // noop
                if (log.isTraceEnabled()) {
                    log.trace("Done processing event: {} {}", eventType.toString(), doneSync ? "synchronously" : "asynchronously");
                }
            }
        });
    } catch (Exception e) {
        String msg = String.format("Error processing %s: %s", exchange, e);
        handleException(msg, new SalesforceException(msg, e));
    } finally {
        Exception ex = exchange.getException();
        if (ex != null) {
            String msg = String.format("Unhandled exception: %s", ex.getMessage());
            handleException(msg, new SalesforceException(msg, ex));
        }
    }
}
Also used : AsyncCallback(org.apache.camel.AsyncCallback) IOException(java.io.IOException) IOException(java.io.IOException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) Exchange(org.apache.camel.Exchange) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) StringReader(java.io.StringReader) HashMap(java.util.HashMap) Map(java.util.Map)

Example 22 with AsyncCallback

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

the class RouteboxSedaConsumer method dispatchToInnerRoute.

private void dispatchToInnerRoute(BlockingQueue<Exchange> queue, final Exchange exchange) throws InterruptedException {
    Exchange result;
    if (exchange != null) {
        if (isRunAllowed()) {
            try {
                LOG.debug("Dispatching to inner route: {}", exchange);
                RouteboxDispatcher dispatcher = new RouteboxDispatcher(producer);
                result = dispatcher.dispatchAsync(getRouteboxEndpoint(), exchange);
                processor.process(result, new AsyncCallback() {

                    public void done(boolean doneSync) {
                    // noop
                    }
                });
            } catch (Exception e) {
                getExceptionHandler().handleException("Error processing exchange", exchange, e);
            }
        } else {
            if (LOG.isWarnEnabled()) {
                LOG.warn("This consumer is stopped during polling an exchange, so putting it back on the seda queue: " + exchange);
            }
            queue.put(exchange);
        }
    }
}
Also used : Exchange(org.apache.camel.Exchange) AsyncCallback(org.apache.camel.AsyncCallback) RouteboxDispatcher(org.apache.camel.component.routebox.strategy.RouteboxDispatcher)

Example 23 with AsyncCallback

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

the class NettyProducer method process.

public boolean process(final Exchange exchange, AsyncCallback callback) {
    if (!isRunAllowed()) {
        if (exchange.getException() == null) {
            exchange.setException(new RejectedExecutionException());
        }
        callback.done(true);
        return true;
    }
    Object body;
    try {
        body = getRequestBody(exchange);
        if (body == null) {
            noReplyLogger.log("No payload to send for exchange: " + exchange);
            callback.done(true);
            return true;
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // set the exchange encoding property
    if (getConfiguration().getCharsetName() != null) {
        exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.normalizeCharset(getConfiguration().getCharsetName()));
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("Pool[active={}, idle={}]", pool.getNumActive(), pool.getNumIdle());
    }
    // get a channel from the pool
    Channel existing;
    try {
        existing = pool.borrowObject();
        if (existing != null) {
            LOG.trace("Got channel from pool {}", existing);
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // we must have a channel
    if (existing == null) {
        exchange.setException(new CamelExchangeException("Cannot get channel from pool", exchange));
        callback.done(true);
        return true;
    }
    if (exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT) != null) {
        long timeoutInMs = exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT, Long.class);
        ChannelHandler oldHandler = existing.getPipeline().get("timeout");
        ReadTimeoutHandler newHandler = new ReadTimeoutHandler(getEndpoint().getTimer(), timeoutInMs, TimeUnit.MILLISECONDS);
        if (oldHandler == null) {
            existing.getPipeline().addBefore("handler", "timeout", newHandler);
        } else {
            existing.getPipeline().replace(oldHandler, "timeout", newHandler);
        }
    }
    // need to declare as final
    final Channel channel = existing;
    final AsyncCallback producerCallback = new NettyProducerCallback(channel, callback);
    // setup state as attachment on the channel, so we can access the state later when needed
    channel.setAttachment(new NettyCamelState(producerCallback, exchange));
    InetSocketAddress remoteAddress = null;
    if (!isTcp()) {
        // Need to specify the remoteAddress for udp connection
        remoteAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    }
    // write body
    NettyHelper.writeBodyAsync(LOG, channel, remoteAddress, body, exchange, new ChannelFutureListener() {

        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            LOG.trace("Operation complete {}", channelFuture);
            if (!channelFuture.isSuccess()) {
                // no success then exit, (any exception has been handled by ClientChannelHandler#exceptionCaught)
                return;
            }
            // if we do not expect any reply then signal callback to continue routing
            if (!configuration.isSync()) {
                try {
                    // should channel be closed after complete?
                    Boolean close;
                    if (ExchangeHelper.isOutCapable(exchange)) {
                        close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                    } else {
                        close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                    }
                    // should we disconnect, the header can override the configuration
                    boolean disconnect = getConfiguration().isDisconnect();
                    if (close != null) {
                        disconnect = close;
                    }
                    if (disconnect) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Closing channel when complete at address: {}", getEndpoint().getConfiguration().getAddress());
                        }
                        NettyHelper.close(channel);
                    }
                } finally {
                    // signal callback to continue routing
                    producerCallback.done(false);
                }
            }
        }
    });
    // continue routing asynchronously
    return false;
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) CamelExchangeException(org.apache.camel.CamelExchangeException) InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) AsyncCallback(org.apache.camel.AsyncCallback) ChannelHandler(org.jboss.netty.channel.ChannelHandler) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CamelException(org.apache.camel.CamelException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ConnectException(java.net.ConnectException) CamelExchangeException(org.apache.camel.CamelExchangeException) ReadTimeoutHandler(org.jboss.netty.handler.timeout.ReadTimeoutHandler)

Example 24 with AsyncCallback

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

the class ClientChannelHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    messageReceived = true;
    if (LOG.isTraceEnabled()) {
        LOG.trace("Message received: {}", messageEvent);
    }
    ChannelHandler handler = ctx.getPipeline().get("timeout");
    if (handler != null) {
        LOG.trace("Removing timeout channel as we received message");
        ctx.getPipeline().remove(handler);
    }
    Exchange exchange = getExchange(ctx);
    if (exchange == null) {
        // we just ignore the received message as the channel is closed
        return;
    }
    AsyncCallback callback = getAsyncCallback(ctx);
    Message message;
    try {
        message = getResponseMessage(exchange, messageEvent);
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(false);
        return;
    }
    // set the result on either IN or OUT on the original exchange depending on its pattern
    if (ExchangeHelper.isOutCapable(exchange)) {
        exchange.setOut(message);
    } else {
        exchange.setIn(message);
    }
    try {
        // should channel be closed after complete?
        Boolean close;
        if (ExchangeHelper.isOutCapable(exchange)) {
            close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
        } else {
            close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
        }
        // check the setting on the exchange property
        if (close == null) {
            close = exchange.getProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
        }
        // should we disconnect, the header can override the configuration
        boolean disconnect = producer.getConfiguration().isDisconnect();
        if (close != null) {
            disconnect = close;
        }
        if (disconnect) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Closing channel when complete at address: {}", producer.getConfiguration().getAddress());
            }
            NettyHelper.close(ctx.getChannel());
        }
    } finally {
        // signal callback
        callback.done(false);
    }
}
Also used : Exchange(org.apache.camel.Exchange) Message(org.apache.camel.Message) AsyncCallback(org.apache.camel.AsyncCallback) ChannelHandler(org.jboss.netty.channel.ChannelHandler) CamelExchangeException(org.apache.camel.CamelExchangeException)

Example 25 with AsyncCallback

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

the class ClientChannelHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent exceptionEvent) throws Exception {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Exception caught at Channel: " + ctx.getChannel(), exceptionEvent.getCause());
    }
    if (exceptionHandled) {
        // ignore subsequent exceptions being thrown
        return;
    }
    exceptionHandled = true;
    Throwable cause = exceptionEvent.getCause();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Closing channel as an exception was thrown from Netty", cause);
    }
    Exchange exchange = getExchange(ctx);
    AsyncCallback callback = getAsyncCallback(ctx);
    // the state may not be set
    if (exchange != null && callback != null) {
        Throwable initialCause = exchange.getException();
        if (initialCause != null && initialCause.getCause() == null) {
            initialCause.initCause(cause);
        } else {
            // set the cause on the exchange
            exchange.setException(cause);
        }
        // close channel in case an exception was thrown
        NettyHelper.close(exceptionEvent.getChannel());
        // signal callback
        callback.done(false);
    }
}
Also used : Exchange(org.apache.camel.Exchange) 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