Search in sources :

Example 21 with SynchronizationAdapter

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

the class RouteboxDispatcher method dispatchAsync.

public Exchange dispatchAsync(RouteboxEndpoint endpoint, Exchange exchange) throws Exception {
    URI dispatchUri;
    Exchange reply;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Dispatching exchange {} to endpoint {}", exchange, endpoint.getEndpointUri());
    }
    dispatchUri = selectDispatchUri(endpoint, exchange);
    if (exchange.getPattern() == ExchangePattern.InOnly) {
        producer.asyncSend(dispatchUri.toASCIIString(), exchange);
        reply = exchange;
    } else {
        Future<Exchange> future = producer.asyncCallback(dispatchUri.toASCIIString(), exchange, new SynchronizationAdapter());
        reply = future.get(endpoint.getConfig().getConnectionTimeout(), TimeUnit.MILLISECONDS);
    }
    return reply;
}
Also used : Exchange(org.apache.camel.Exchange) URI(java.net.URI) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 22 with SynchronizationAdapter

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

the class RouteboxSedaProducer method process.

public boolean process(final Exchange exchange, final AsyncCallback callback) {
    // use a new copy of the exchange to route async and handover the on completion to the new copy
    // so its the new copy that performs the on completion callback when its done
    Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, true);
    // set a new from endpoint to be the seda queue
    copy.setFromEndpoint(endpoint);
    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))) {
        // 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() {
                return false;
            }

            @Override
            public String toString() {
                return "onDone at [" + endpoint.getEndpointUri() + "]";
            }
        });
        queue.add(copy);
        if (timeout > 0) {
            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));
                // count down to indicate timeout
                latch.countDown();
            }
        } else {
            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
        queue.add(copy);
    }
    // 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 23 with SynchronizationAdapter

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

the class SedaInOutChainedWithOnCompletionTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("seda:a").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    // should come in last
                    exchange.addOnCompletion(new SynchronizationAdapter() {

                        @Override
                        public void onDone(Exchange exchange) {
                            template.sendBody("mock:c", "onCustomCompletion");
                        }
                    });
                }
            }).to("mock:a").transform(simple("${body}-a")).to("seda:b");
            from("seda:b").to("mock:b").transform(simple("${body}-b")).to("seda:c");
            from("seda:c").to("mock:c").transform(simple("${body}-c"));
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 24 with SynchronizationAdapter

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

the class SedaWaitForTaskCompleteOnCompletionTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            errorHandler(defaultErrorHandler().maximumRedeliveries(3).redeliveryDelay(0));
            from("direct:start").process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    exchange.addOnCompletion(new SynchronizationAdapter() {

                        @Override
                        public void onDone(Exchange exchange) {
                            done = done + "A";
                        }
                    });
                }
            }).to("seda:foo?waitForTaskToComplete=Always").process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    done = done + "B";
                }
            }).to("mock:result");
            from("seda:foo").errorHandler(noErrorHandler()).process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    done = done + "C";
                }
            }).throwException(new IllegalArgumentException("Forced"));
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 25 with SynchronizationAdapter

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

the class S3Endpoint method createExchange.

public Exchange createExchange(ExchangePattern pattern, S3Object s3Object) {
    LOG.trace("Getting object with key [{}] from bucket [{}]...", s3Object.getKey(), s3Object.getBucketName());
    ObjectMetadata objectMetadata = s3Object.getObjectMetadata();
    LOG.trace("Got object [{}]", s3Object);
    Exchange exchange = super.createExchange(pattern);
    Message message = exchange.getIn();
    if (configuration.isIncludeBody()) {
        message.setBody(s3Object.getObjectContent());
    } else {
        message.setBody(null);
    }
    message.setHeader(S3Constants.KEY, s3Object.getKey());
    message.setHeader(S3Constants.BUCKET_NAME, s3Object.getBucketName());
    message.setHeader(S3Constants.E_TAG, objectMetadata.getETag());
    message.setHeader(S3Constants.LAST_MODIFIED, objectMetadata.getLastModified());
    message.setHeader(S3Constants.VERSION_ID, objectMetadata.getVersionId());
    message.setHeader(S3Constants.CONTENT_TYPE, objectMetadata.getContentType());
    message.setHeader(S3Constants.CONTENT_MD5, objectMetadata.getContentMD5());
    message.setHeader(S3Constants.CONTENT_LENGTH, objectMetadata.getContentLength());
    message.setHeader(S3Constants.CONTENT_ENCODING, objectMetadata.getContentEncoding());
    message.setHeader(S3Constants.CONTENT_DISPOSITION, objectMetadata.getContentDisposition());
    message.setHeader(S3Constants.CACHE_CONTROL, objectMetadata.getCacheControl());
    message.setHeader(S3Constants.S3_HEADERS, objectMetadata.getRawMetadata());
    message.setHeader(S3Constants.SERVER_SIDE_ENCRYPTION, objectMetadata.getSSEAlgorithm());
    /**
         * If includeBody != true, it is safe to close the object here.  If includeBody == true,
         * the caller is responsible for closing the stream and object once the body has been fully consumed.
         * As of 2.17, the consumer does not close the stream or object on commit.
         */
    if (!configuration.isIncludeBody()) {
        try {
            s3Object.close();
        } catch (IOException e) {
        }
    } else {
        if (configuration.isAutocloseBody()) {
            exchange.addOnCompletion(new SynchronizationAdapter() {

                @Override
                public void onDone(Exchange exchange) {
                    try {
                        s3Object.close();
                    } catch (IOException e) {
                    }
                }
            });
        }
    }
    return exchange;
}
Also used : Exchange(org.apache.camel.Exchange) Message(org.apache.camel.Message) IOException(java.io.IOException) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) 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