Search in sources :

Example 66 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 67 with AsyncCallback

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

the class SyslogReceiverCamelNettyImpl method run.

/**
 * The execution context.
 */
@Override
public void run() {
    // Setup logging and create the dispatcher
    super.run();
    SimpleRegistry registry = new SimpleRegistry();
    // Adding netty component to camel in order to resolve OSGi loading issues
    NettyComponent nettyComponent = new NettyComponent();
    m_camel = new DefaultCamelContext(registry);
    // Set the context name so that it shows up nicely in JMX
    // 
    // @see org.apache.camel.management.DefaultManagementNamingStrategy
    // 
    // m_camel.setManagementName("org.opennms.features.events.syslog.listener");
    m_camel.setName("syslogdListenerCamelNettyContext");
    m_camel.setManagementNameStrategy(new DefaultManagementNameStrategy(m_camel, "#name#", null));
    m_camel.addComponent("netty4", nettyComponent);
    m_camel.getShutdownStrategy().setShutdownNowOnTimeout(true);
    m_camel.getShutdownStrategy().setTimeout(15);
    m_camel.getShutdownStrategy().setTimeUnit(TimeUnit.SECONDS);
    try {
        m_camel.addRoutes(new RouteBuilder() {

            @Override
            public void configure() throws Exception {
                String from = String.format("netty4:udp://%s:%d?sync=false&allowDefaultCodec=false&receiveBufferSize=%d&connectTimeout=%d", InetAddressUtils.str(m_host), m_port, Integer.MAX_VALUE, SOCKET_TIMEOUT);
                from(from).routeId("syslogListen").process(new AsyncProcessor() {

                    @Override
                    public void process(Exchange exchange) throws Exception {
                        final ByteBuf buffer = exchange.getIn().getBody(ByteBuf.class);
                        // NettyConstants.NETTY_REMOTE_ADDRESS is a SocketAddress type but because
                        // we are listening on an InetAddress, it will always be of type InetAddressSocket
                        InetSocketAddress source = (InetSocketAddress) exchange.getIn().getHeader(NettyConstants.NETTY_REMOTE_ADDRESS);
                        // Synchronously invoke the dispatcher
                        m_dispatcher.send(new SyslogConnection(source, buffer.nioBuffer())).get();
                    }

                    @Override
                    public boolean process(Exchange exchange, AsyncCallback callback) {
                        final ByteBuf buffer = exchange.getIn().getBody(ByteBuf.class);
                        // NettyConstants.NETTY_REMOTE_ADDRESS is a SocketAddress type but because
                        // we are listening on an InetAddress, it will always be of type InetAddressSocket
                        InetSocketAddress source = (InetSocketAddress) exchange.getIn().getHeader(NettyConstants.NETTY_REMOTE_ADDRESS);
                        ByteBuffer bufferCopy = ByteBuffer.allocate(buffer.readableBytes());
                        buffer.getBytes(buffer.readerIndex(), bufferCopy);
                        m_dispatcher.send(new SyslogConnection(source, bufferCopy)).whenComplete((r, e) -> {
                            if (e != null) {
                                exchange.setException(e);
                            }
                            callback.done(false);
                        });
                        return false;
                    }
                });
            }
        });
        m_camel.start();
    } catch (Throwable e) {
        LOG.error("Could not configure Camel routes for syslog receiver", e);
    }
}
Also used : RouteBuilder(org.apache.camel.builder.RouteBuilder) SimpleRegistry(org.apache.camel.impl.SimpleRegistry) InetSocketAddress(java.net.InetSocketAddress) NettyComponent(org.apache.camel.component.netty4.NettyComponent) AsyncCallback(org.apache.camel.AsyncCallback) ByteBuf(io.netty.buffer.ByteBuf) ByteBuffer(java.nio.ByteBuffer) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) Exchange(org.apache.camel.Exchange) DefaultManagementNameStrategy(org.apache.camel.impl.DefaultManagementNameStrategy) AsyncProcessor(org.apache.camel.AsyncProcessor) SyslogConnection(org.opennms.netmgt.syslogd.api.SyslogConnection)

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