Search in sources :

Example 26 with SynchronizationAdapter

use of org.apache.camel.support.SynchronizationAdapter in project camel by apache.

the class SedaProducer method process.

@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    WaitForTaskToComplete wait = waitForTaskToComplete;
    if (exchange.getProperty(Exchange.ASYNC_WAIT) != null) {
        wait = exchange.getProperty(Exchange.ASYNC_WAIT, WaitForTaskToComplete.class);
    }
    if (wait == WaitForTaskToComplete.Always || (wait == WaitForTaskToComplete.IfReplyExpected && ExchangeHelper.isOutCapable(exchange))) {
        // do not handover the completion as we wait for the copy to complete, and copy its result back when it done
        Exchange copy = prepareCopy(exchange, false);
        // latch that waits until we are complete
        final CountDownLatch latch = new CountDownLatch(1);
        // we should wait for the reply so install a on completion so we know when its complete
        copy.addOnCompletion(new SynchronizationAdapter() {

            @Override
            public void onDone(Exchange response) {
                // check for timeout, which then already would have invoked the latch
                if (latch.getCount() == 0) {
                    if (log.isTraceEnabled()) {
                        log.trace("{}. Timeout occurred so response will be ignored: {}", this, response.hasOut() ? response.getOut() : response.getIn());
                    }
                    return;
                } else {
                    if (log.isTraceEnabled()) {
                        log.trace("{} with response: {}", this, response.hasOut() ? response.getOut() : response.getIn());
                    }
                    try {
                        ExchangeHelper.copyResults(exchange, response);
                    } finally {
                        // always ensure latch is triggered
                        latch.countDown();
                    }
                }
            }

            @Override
            public boolean allowHandover() {
                // at this point in the routing (at this leg), instead of at the very last (this ensure timeout is honored)
                return false;
            }

            @Override
            public String toString() {
                return "onDone at endpoint: " + endpoint;
            }
        });
        log.trace("Adding Exchange to queue: {}", copy);
        try {
            // do not copy as we already did the copy
            addToQueue(copy, false);
        } catch (SedaConsumerNotAvailableException e) {
            exchange.setException(e);
            callback.done(true);
            return true;
        }
        if (timeout > 0) {
            if (log.isTraceEnabled()) {
                log.trace("Waiting for task to complete using timeout (ms): {} at [{}]", timeout, endpoint.getEndpointUri());
            }
            // lets see if we can get the task done before the timeout
            boolean done = false;
            try {
                done = latch.await(timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
            // ignore
            }
            if (!done) {
                exchange.setException(new ExchangeTimedOutException(exchange, timeout));
                // remove timed out Exchange from queue
                endpoint.getQueue().remove(copy);
                // count down to indicate timeout
                latch.countDown();
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Waiting for task to complete (blocking) at [{}]", endpoint.getEndpointUri());
            }
            // no timeout then wait until its done
            try {
                latch.await();
            } catch (InterruptedException e) {
            // ignore
            }
        }
    } else {
        // no wait, eg its a InOnly then just add to queue and return
        try {
            addToQueue(exchange, true);
        } catch (SedaConsumerNotAvailableException e) {
            exchange.setException(e);
            callback.done(true);
            return true;
        }
    }
    // we use OnCompletion on the Exchange to callback and wait for the Exchange to be done
    // so we should just signal the callback we are done synchronously
    callback.done(true);
    return true;
}
Also used : Exchange(org.apache.camel.Exchange) WaitForTaskToComplete(org.apache.camel.WaitForTaskToComplete) CountDownLatch(java.util.concurrent.CountDownLatch) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 27 with SynchronizationAdapter

use of org.apache.camel.support.SynchronizationAdapter in project camel by apache.

the class DefaultProducerTemplateAsyncTest method testAsyncCallbackBodyInOut.

public void testAsyncCallbackBodyInOut() throws Exception {
    ORDER.set(0);
    final CountDownLatch latch = new CountDownLatch(1);
    template.asyncCallbackRequestBody("direct:echo", "Hello", new SynchronizationAdapter() {

        @Override
        public void onDone(Exchange exchange) {
            assertEquals("HelloHello", exchange.getOut().getBody());
            ORDER.addAndGet(2);
            latch.countDown();
        }
    });
    ORDER.addAndGet(1);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    ORDER.addAndGet(4);
    assertEquals(7, ORDER.get());
}
Also used : Exchange(org.apache.camel.Exchange) CountDownLatch(java.util.concurrent.CountDownLatch) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 28 with SynchronizationAdapter

use of org.apache.camel.support.SynchronizationAdapter in project camel by apache.

the class DefaultProducerTemplateAsyncTest method testAsyncCallbackExchangeInOutWithFailure.

public void testAsyncCallbackExchangeInOutWithFailure() throws Exception {
    ORDER.set(0);
    final CountDownLatch latch = new CountDownLatch(1);
    Exchange exchange = context.getEndpoint("direct:error").createExchange();
    exchange.getIn().setBody("Hello");
    exchange.setPattern(ExchangePattern.InOut);
    template.asyncCallback("direct:error", exchange, new SynchronizationAdapter() {

        @Override
        public void onFailure(Exchange exchange) {
            assertEquals("Damn forced by unit test", exchange.getException().getMessage());
            ORDER.addAndGet(2);
            latch.countDown();
        }
    });
    ORDER.addAndGet(1);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    ORDER.addAndGet(4);
    assertEquals(7, ORDER.get());
}
Also used : Exchange(org.apache.camel.Exchange) CountDownLatch(java.util.concurrent.CountDownLatch) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 29 with SynchronizationAdapter

use of org.apache.camel.support.SynchronizationAdapter in project camel by apache.

the class DefaultProducerTemplateAsyncTest method testAsyncCallbackBodyInOutGetResult.

public void testAsyncCallbackBodyInOutGetResult() throws Exception {
    ORDER.set(0);
    Future<Object> future = template.asyncCallbackRequestBody("direct:echo", "Hello", new SynchronizationAdapter() {

        @Override
        public void onDone(Exchange exchange) {
            assertEquals("HelloHello", exchange.getOut().getBody());
            ORDER.addAndGet(2);
        }
    });
    ORDER.addAndGet(1);
    Object reply = future.get(10, TimeUnit.SECONDS);
    ORDER.addAndGet(4);
    assertEquals(7, ORDER.get());
    assertEquals("HelloHello", reply);
}
Also used : Exchange(org.apache.camel.Exchange) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 30 with SynchronizationAdapter

use of org.apache.camel.support.SynchronizationAdapter in project camel by apache.

the class DefaultProducerTemplateAsyncTest method testAsyncCallbackExchangeInOnlyWithFailure.

public void testAsyncCallbackExchangeInOnlyWithFailure() throws Exception {
    ORDER.set(0);
    final CountDownLatch latch = new CountDownLatch(1);
    Exchange exchange = context.getEndpoint("direct:error").createExchange();
    exchange.getIn().setBody("Hello");
    template.asyncCallback("direct:error", exchange, new SynchronizationAdapter() {

        @Override
        public void onFailure(Exchange exchange) {
            assertEquals("Damn forced by unit test", exchange.getException().getMessage());
            ORDER.addAndGet(2);
            latch.countDown();
        }
    });
    ORDER.addAndGet(1);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    ORDER.addAndGet(4);
    assertEquals(7, ORDER.get());
}
Also used : Exchange(org.apache.camel.Exchange) CountDownLatch(java.util.concurrent.CountDownLatch) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Aggregations

Exchange (org.apache.camel.Exchange)34 SynchronizationAdapter (org.apache.camel.support.SynchronizationAdapter)34 CountDownLatch (java.util.concurrent.CountDownLatch)13 Processor (org.apache.camel.Processor)13 RouteBuilder (org.apache.camel.builder.RouteBuilder)10 Message (org.apache.camel.Message)4 ExchangeTimedOutException (org.apache.camel.ExchangeTimedOutException)3 RuntimeCamelException (org.apache.camel.RuntimeCamelException)3 WaitForTaskToComplete (org.apache.camel.WaitForTaskToComplete)3 Async (io.vertx.ext.unit.Async)2 Endpoint (org.apache.camel.Endpoint)2 ProducerTemplate (org.apache.camel.ProducerTemplate)2 Test (org.junit.Test)2 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)1 Channel (io.netty.channel.Channel)1 ChannelFuture (io.netty.channel.ChannelFuture)1 ChannelFutureListener (io.netty.channel.ChannelFutureListener)1 ChannelHandler (io.netty.channel.ChannelHandler)1 EpollDatagramChannel (io.netty.channel.epoll.EpollDatagramChannel)1 EpollSocketChannel (io.netty.channel.epoll.EpollSocketChannel)1