Search in sources :

Example 16 with ExchangeTimedOutException

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

the class DisruptorVmInOutChainedTimeoutTest method testDisruptorVmInOutChainedTimeout.

public void testDisruptorVmInOutChainedTimeout() throws Exception {
    StopWatch watch = new StopWatch();
    try {
        template2.requestBody("disruptor-vm:a?timeout=1000", "Hello World");
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        // the chained vm caused the timeout
        ExchangeTimedOutException cause = assertIsInstanceOf(ExchangeTimedOutException.class, e.getCause());
        assertEquals(200, cause.getTimeout());
    }
    long delta = watch.stop();
    assertTrue("Should be faster than 1 sec, was: " + delta, delta < 1100);
}
Also used : CamelExecutionException(org.apache.camel.CamelExecutionException) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) StopWatch(org.apache.camel.util.StopWatch)

Example 17 with ExchangeTimedOutException

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

the class DisruptorInOutChainedTimeoutTest method testDisruptorInOutChainedTimeout.

@Test
public void testDisruptorInOutChainedTimeout() throws Exception {
    // time timeout after 2 sec should trigger a immediately reply
    final StopWatch watch = new StopWatch();
    try {
        template.requestBody("disruptor:a?timeout=5000", "Hello World");
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        final ExchangeTimedOutException cause = assertIsInstanceOf(ExchangeTimedOutException.class, e.getCause());
        assertEquals(2000, cause.getTimeout());
    }
    final long delta = watch.stop();
    assertTrue("Should be faster than 4000 millis, was: " + delta, delta < 4000);
}
Also used : CamelExecutionException(org.apache.camel.CamelExecutionException) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) StopWatch(org.apache.camel.util.StopWatch) Test(org.junit.Test)

Example 18 with ExchangeTimedOutException

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

the class EtcdKeysProducer method processSet.

// *************************************************************************
// Processors
// *************************************************************************
private void processSet(EtcdClient client, String path, Exchange exchange) throws Exception {
    EtcdKeyPutRequest request = client.put(path, exchange.getIn().getBody(String.class));
    setRequestTimeToLive(request, exchange);
    setRequestTimeout(request, exchange);
    try {
        exchange.getIn().setHeader(EtcdConstants.ETCD_NAMESPACE, getNamespace());
        exchange.getIn().setBody(request.send().get());
    } catch (TimeoutException e) {
        throw new ExchangeTimedOutException(exchange, configuration.getTimeout());
    }
}
Also used : EtcdKeyPutRequest(mousio.etcd4j.requests.EtcdKeyPutRequest) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 19 with ExchangeTimedOutException

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

the class MinaProducer method doProcess.

protected void doProcess(Exchange exchange) throws Exception {
    if (session == null && !lazySessionCreation) {
        throw new IllegalStateException("Not started yet!");
    }
    if (session == null || !session.isConnected()) {
        openConnection();
    }
    // set the exchange encoding property
    if (getEndpoint().getConfiguration().getCharsetName() != null) {
        exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.normalizeCharset(getEndpoint().getConfiguration().getCharsetName()));
    }
    Object body = MinaPayloadHelper.getIn(getEndpoint(), exchange);
    if (body == null) {
        noReplyLogger.log("No payload to send for exchange: " + exchange);
        // exit early since nothing to write
        return;
    }
    // if textline enabled then covert to a String which must be used for textline
    if (getEndpoint().getConfiguration().isTextline()) {
        body = getEndpoint().getCamelContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, body);
    }
    // if sync is true then we should also wait for a response (synchronous mode)
    if (sync) {
        // only initialize latch if we should get a response
        latch = new CountDownLatch(1);
        // reset handler if we expect a response
        ResponseHandler handler = (ResponseHandler) session.getHandler();
        handler.reset();
    }
    // log what we are writing
    if (LOG.isDebugEnabled()) {
        Object out = body;
        if (body instanceof byte[]) {
            // byte arrays is not readable so convert to string
            out = exchange.getContext().getTypeConverter().convertTo(String.class, body);
        }
        LOG.debug("Writing body : {}", out);
    }
    // write the body
    MinaHelper.writeBody(session, body, exchange);
    if (sync) {
        // wait for response, consider timeout
        LOG.debug("Waiting for response using timeout {} millis.", timeout);
        boolean done = latch.await(timeout, TimeUnit.MILLISECONDS);
        if (!done) {
            throw new ExchangeTimedOutException(exchange, timeout);
        }
        // did we get a response
        ResponseHandler handler = (ResponseHandler) session.getHandler();
        if (handler.getCause() != null) {
            throw new CamelExchangeException("Error occurred in ResponseHandler", exchange, handler.getCause());
        } else if (!handler.isMessageReceived()) {
            // no message received
            throw new CamelExchangeException("No response received from remote server: " + getEndpoint().getEndpointUri(), exchange);
        } else {
            // set the result on either IN or OUT on the original exchange depending on its pattern
            if (ExchangeHelper.isOutCapable(exchange)) {
                MinaPayloadHelper.setOut(exchange, handler.getMessage());
            } else {
                MinaPayloadHelper.setIn(exchange, handler.getMessage());
            }
        }
    }
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) CountDownLatch(java.util.concurrent.CountDownLatch) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException)

Example 20 with ExchangeTimedOutException

use of org.apache.camel.ExchangeTimedOutException 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)

Aggregations

ExchangeTimedOutException (org.apache.camel.ExchangeTimedOutException)23 Exchange (org.apache.camel.Exchange)11 CountDownLatch (java.util.concurrent.CountDownLatch)5 CamelExecutionException (org.apache.camel.CamelExecutionException)4 StopWatch (org.apache.camel.util.StopWatch)4 Test (org.junit.Test)4 TimeoutException (java.util.concurrent.TimeoutException)3 AsyncCallback (org.apache.camel.AsyncCallback)3 Processor (org.apache.camel.Processor)3 WaitForTaskToComplete (org.apache.camel.WaitForTaskToComplete)3 SynchronizationAdapter (org.apache.camel.support.SynchronizationAdapter)3 CamelExchangeException (org.apache.camel.CamelExchangeException)2 Endpoint (org.apache.camel.Endpoint)2 Producer (org.apache.camel.Producer)2 CompletableFuture (java.util.concurrent.CompletableFuture)1 JMSException (javax.jms.JMSException)1 Message (javax.jms.Message)1 Session (javax.jms.Session)1 EtcdKeyDeleteRequest (mousio.etcd4j.requests.EtcdKeyDeleteRequest)1 EtcdKeyGetRequest (mousio.etcd4j.requests.EtcdKeyGetRequest)1