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
}
});
}
}
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);
}
}
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;
}
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;
}
};
}
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();
}
});
}
Aggregations