Search in sources :

Example 16 with Synchronization

use of org.apache.camel.spi.Synchronization in project camel by apache.

the class SedaConsumer method sendToConsumers.

/**
     * Send the given {@link Exchange} to the consumer(s).
     * <p/>
     * If multiple consumers then they will each receive a copy of the Exchange.
     * A multicast processor will send the exchange in parallel to the multiple consumers.
     * <p/>
     * If there is only a single consumer then its dispatched directly to it using same thread.
     * 
     * @param exchange the exchange
     * @throws Exception can be thrown if processing of the exchange failed
     */
protected void sendToConsumers(final Exchange exchange) throws Exception {
    // validate multiple consumers has been enabled
    int size = endpoint.getConsumers().size();
    if (size > 1 && !endpoint.isMultipleConsumersSupported()) {
        throw new IllegalStateException("Multiple consumers for the same endpoint is not allowed: " + endpoint);
    }
    // if there are multiple consumers then multicast to them
    if (endpoint.isMultipleConsumersSupported()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Multicasting to {} consumers for Exchange: {}", size, exchange);
        }
        // handover completions, as we need to done this when the multicast is done
        final List<Synchronization> completions = exchange.handoverCompletions();
        // use a multicast processor to process it
        MulticastProcessor mp = endpoint.getConsumerMulticastProcessor();
        ObjectHelper.notNull(mp, "ConsumerMulticastProcessor", this);
        // and use the asynchronous routing engine to support it
        mp.process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
                // done the uow on the completions
                UnitOfWorkHelper.doneSynchronizations(exchange, completions, LOG);
            }
        });
    } else {
        // use the regular processor and use the asynchronous routing engine to support it
        processor.process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
            // noop
            }
        });
    }
}
Also used : AsyncCallback(org.apache.camel.AsyncCallback) MulticastProcessor(org.apache.camel.processor.MulticastProcessor) Synchronization(org.apache.camel.spi.Synchronization) Endpoint(org.apache.camel.Endpoint)

Example 17 with Synchronization

use of org.apache.camel.spi.Synchronization in project camel by apache.

the class DefaultExchange method handoverCompletions.

public void handoverCompletions(Exchange target) {
    if (onCompletions != null) {
        for (Synchronization onCompletion : onCompletions) {
            target.addOnCompletion(onCompletion);
        }
        // cleanup the temporary on completion list as they have been handed over
        onCompletions.clear();
        onCompletions = null;
    } else if (unitOfWork != null) {
        // let unit of work handover
        unitOfWork.handoverSynchronization(target);
    }
}
Also used : Synchronization(org.apache.camel.spi.Synchronization)

Example 18 with Synchronization

use of org.apache.camel.spi.Synchronization in project camel by apache.

the class SjmsConsumer method createMessageHandler.

/**
     * Helper factory method used to create a MessageListener based on the MEP
     *
     * @param session a session is only required if we are a transacted consumer
     * @return the listener
     */
protected MessageListener createMessageHandler(Session session) {
    TransactionCommitStrategy commitStrategy;
    if (getTransactionCommitStrategy() != null) {
        commitStrategy = getTransactionCommitStrategy();
    } else if (getTransactionBatchCount() > 0) {
        commitStrategy = new BatchTransactionCommitStrategy(getTransactionBatchCount());
    } else {
        commitStrategy = new DefaultTransactionCommitStrategy();
    }
    Synchronization synchronization;
    if (commitStrategy instanceof BatchTransactionCommitStrategy) {
        TimedTaskManager timedTaskManager = getEndpoint().getComponent().getTimedTaskManager();
        synchronization = new SessionBatchTransactionSynchronization(timedTaskManager, session, commitStrategy, getTransactionBatchTimeout());
    } else {
        synchronization = new SessionTransactionSynchronization(session, commitStrategy);
    }
    AbstractMessageHandler messageHandler;
    if (getEndpoint().getExchangePattern().equals(ExchangePattern.InOnly)) {
        if (isTransacted()) {
            messageHandler = new InOnlyMessageHandler(getEndpoint(), executor, synchronization);
        } else {
            messageHandler = new InOnlyMessageHandler(getEndpoint(), executor);
        }
    } else {
        if (isTransacted()) {
            messageHandler = new InOutMessageHandler(getEndpoint(), executor, synchronization);
        } else {
            messageHandler = new InOutMessageHandler(getEndpoint(), executor);
        }
    }
    messageHandler.setSession(session);
    messageHandler.setProcessor(getAsyncProcessor());
    messageHandler.setSynchronous(isSynchronous());
    messageHandler.setTransacted(isTransacted());
    messageHandler.setSharedJMSSession(isSharedJMSSession());
    messageHandler.setTopic(isTopic());
    return messageHandler;
}
Also used : InOnlyMessageHandler(org.apache.camel.component.sjms.consumer.InOnlyMessageHandler) SessionTransactionSynchronization(org.apache.camel.component.sjms.tx.SessionTransactionSynchronization) InOutMessageHandler(org.apache.camel.component.sjms.consumer.InOutMessageHandler) BatchTransactionCommitStrategy(org.apache.camel.component.sjms.tx.BatchTransactionCommitStrategy) DefaultTransactionCommitStrategy(org.apache.camel.component.sjms.tx.DefaultTransactionCommitStrategy) DefaultTransactionCommitStrategy(org.apache.camel.component.sjms.tx.DefaultTransactionCommitStrategy) BatchTransactionCommitStrategy(org.apache.camel.component.sjms.tx.BatchTransactionCommitStrategy) SessionBatchTransactionSynchronization(org.apache.camel.component.sjms.tx.SessionBatchTransactionSynchronization) SessionTransactionSynchronization(org.apache.camel.component.sjms.tx.SessionTransactionSynchronization) Synchronization(org.apache.camel.spi.Synchronization) TimedTaskManager(org.apache.camel.component.sjms.taskmanager.TimedTaskManager) SessionBatchTransactionSynchronization(org.apache.camel.component.sjms.tx.SessionBatchTransactionSynchronization) AbstractMessageHandler(org.apache.camel.component.sjms.consumer.AbstractMessageHandler)

Example 19 with Synchronization

use of org.apache.camel.spi.Synchronization in project opennms by OpenNMS.

the class CamelRpcClientFactory method getClient.

@Override
public <S extends RpcRequest, T extends RpcResponse> RpcClient<S, T> getClient(RpcModule<S, T> module) {
    return new RpcClient<S, T>() {

        @Override
        public CompletableFuture<T> execute(S request) {
            if (request.getLocation() == null || request.getLocation().equals(location)) {
                // The request is for the current location, invoke it directly
                return module.execute(request);
            }
            // Save the context map and restore it on callback
            final Map<String, String> clientContextMap = Logging.getCopyOfContextMap();
            // Wrap the request in a CamelRpcRequest and forward it to the Camel route
            final CompletableFuture<T> future = new CompletableFuture<>();
            try {
                template.asyncCallbackSendBody(endpoint, new CamelRpcRequest<>(module, request), new Synchronization() {

                    @Override
                    public void onComplete(Exchange exchange) {
                        try (MDCCloseable mdc = Logging.withContextMapCloseable(clientContextMap)) {
                            final T response = module.unmarshalResponse(exchange.getOut().getBody(String.class));
                            if (response.getErrorMessage() != null) {
                                future.completeExceptionally(new RemoteExecutionException(response.getErrorMessage()));
                            } else {
                                future.complete(response);
                            }
                        } catch (Throwable ex) {
                            LOG.error("Unmarshalling a response in RPC module {} failed.", module, ex);
                            future.completeExceptionally(ex);
                        }
                        // Ensure that future log statements on this thread are routed properly
                        Logging.putPrefix(RpcClientFactory.LOG_PREFIX);
                    }

                    @Override
                    public void onFailure(Exchange exchange) {
                        try (MDCCloseable mdc = Logging.withContextMapCloseable(clientContextMap)) {
                            final ExchangeTimedOutException timeoutException = exchange.getException(ExchangeTimedOutException.class);
                            final DirectConsumerNotAvailableException directConsumerNotAvailableException = exchange.getException(DirectConsumerNotAvailableException.class);
                            if (timeoutException != null) {
                                // Wrap timeout exceptions within a RequestTimedOutException
                                future.completeExceptionally(new RequestTimedOutException(exchange.getException()));
                            } else if (directConsumerNotAvailableException != null) {
                                // Wrap consumer not available exceptions with a RequestRejectedException
                                future.completeExceptionally(new RequestRejectedException(exchange.getException()));
                            } else {
                                future.completeExceptionally(exchange.getException());
                            }
                        }
                        // Ensure that future log statements on this thread are routed properly
                        Logging.putPrefix(RpcClientFactory.LOG_PREFIX);
                    }
                });
            } catch (IllegalStateException e) {
                try (MDCCloseable mdc = Logging.withContextMapCloseable(clientContextMap)) {
                    // Wrap ProducerTemplate exceptions with a RequestRejectedException
                    future.completeExceptionally(new RequestRejectedException(e));
                }
                // Ensure that future log statements on this thread are routed properly
                Logging.putPrefix(RpcClientFactory.LOG_PREFIX);
            }
            return future;
        }
    };
}
Also used : DirectConsumerNotAvailableException(org.apache.camel.component.direct.DirectConsumerNotAvailableException) RequestTimedOutException(org.opennms.core.rpc.api.RequestTimedOutException) RequestRejectedException(org.opennms.core.rpc.api.RequestRejectedException) Synchronization(org.apache.camel.spi.Synchronization) Exchange(org.apache.camel.Exchange) RemoteExecutionException(org.opennms.core.rpc.api.RemoteExecutionException) CompletableFuture(java.util.concurrent.CompletableFuture) MDCCloseable(org.opennms.core.logging.Logging.MDCCloseable) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) RpcClient(org.opennms.core.rpc.api.RpcClient)

Example 20 with Synchronization

use of org.apache.camel.spi.Synchronization in project vertx-camel-bridge by vert-x3.

the class InboundEndpointTest method testReplyTimeout.

/**
 * Reproducer for https://github.com/vert-x3/vertx-camel-bridge/issues/27
 */
@Test
public void testReplyTimeout(TestContext tc) throws Exception {
    Async async = tc.async();
    Endpoint endpoint = camel.getEndpoint("direct:foo");
    bridge = CamelBridge.create(vertx, new CamelBridgeOptions(camel).addInboundMapping(fromCamel(endpoint).toVertx("test").setTimeout(5000)));
    camel.start();
    BridgeHelper.startBlocking(bridge);
    vertx.eventBus().consumer("test", message -> {
    // Simulate a timeout, so do not reply.
    });
    ProducerTemplate producer = camel.createProducerTemplate();
    long begin = System.currentTimeMillis();
    producer.asyncCallbackRequestBody(endpoint, "ping", new Synchronization() {

        @Override
        public void onComplete(Exchange exchange) {
            tc.fail("The interaction should fail");
        }

        @Override
        public void onFailure(Exchange exchange) {
            tc.assertTrue(exchange.getException().getMessage().contains("Timed out"));
            tc.assertTrue(exchange.getException().getMessage().contains("5000"));
            long end = System.currentTimeMillis();
            tc.assertTrue((end - begin) < 20000);
            async.complete();
        }
    });
}
Also used : Exchange(org.apache.camel.Exchange) ProducerTemplate(org.apache.camel.ProducerTemplate) Endpoint(org.apache.camel.Endpoint) Async(io.vertx.ext.unit.Async) Synchronization(org.apache.camel.spi.Synchronization) Test(org.junit.Test)

Aggregations

Synchronization (org.apache.camel.spi.Synchronization)22 Exchange (org.apache.camel.Exchange)12 AsyncCallback (org.apache.camel.AsyncCallback)4 Endpoint (org.apache.camel.Endpoint)4 ArrayList (java.util.ArrayList)3 Async (io.vertx.ext.unit.Async)2 ProducerTemplate (org.apache.camel.ProducerTemplate)2 DefaultExchange (org.apache.camel.impl.DefaultExchange)2 SynchronizationRouteAware (org.apache.camel.spi.SynchronizationRouteAware)2 Test (org.junit.Test)2 File (java.io.File)1 URL (java.net.URL)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExchangeTimedOutException (org.apache.camel.ExchangeTimedOutException)1 InvalidPayloadException (org.apache.camel.InvalidPayloadException)1 DirectConsumerNotAvailableException (org.apache.camel.component.direct.DirectConsumerNotAvailableException)1 ReactiveStreamsConsumer (org.apache.camel.component.reactive.streams.ReactiveStreamsConsumer)1 AbstractMessageHandler (org.apache.camel.component.sjms.consumer.AbstractMessageHandler)1 InOnlyMessageHandler (org.apache.camel.component.sjms.consumer.InOnlyMessageHandler)1 InOutMessageHandler (org.apache.camel.component.sjms.consumer.InOutMessageHandler)1