use of org.apache.camel.ExchangePattern in project camel by apache.
the class DefaultCxfBinding method populateExchangeFromCxfRequest.
/**
* This method is called by {@link CxfConsumer}.
*/
public void populateExchangeFromCxfRequest(org.apache.cxf.message.Exchange cxfExchange, Exchange camelExchange) {
Method method = null;
QName operationName = null;
ExchangePattern mep = ExchangePattern.InOut;
// extract binding operation information
BindingOperationInfo boi = camelExchange.getProperty(BindingOperationInfo.class.getName(), BindingOperationInfo.class);
if (boi != null) {
Service service = cxfExchange.get(Service.class);
if (service != null) {
MethodDispatcher md = (MethodDispatcher) service.get(MethodDispatcher.class.getName());
if (md != null) {
method = md.getMethod(boi);
}
}
if (boi.getOperationInfo().isOneWay()) {
mep = ExchangePattern.InOnly;
}
operationName = boi.getName();
}
// set operation name in header
if (operationName != null) {
camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, boi.getName().getNamespaceURI());
camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, boi.getName().getLocalPart());
if (LOG.isTraceEnabled()) {
LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAMESPACE, boi.getName().getNamespaceURI());
LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAME, boi.getName().getLocalPart());
}
} else if (method != null) {
camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, method.getName());
if (LOG.isTraceEnabled()) {
LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAME, method.getName());
}
}
// set message exchange pattern
camelExchange.setPattern(mep);
LOG.trace("Set exchange MEP: {}", mep);
// propagate headers
Message cxfMessage = cxfExchange.getInMessage();
propagateHeadersFromCxfToCamel(cxfMessage, camelExchange.getIn(), camelExchange);
// propagate the security subject from CXF security context
SecurityContext securityContext = cxfMessage.get(SecurityContext.class);
if (securityContext instanceof LoginSecurityContext && ((LoginSecurityContext) securityContext).getSubject() != null) {
camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, ((LoginSecurityContext) securityContext).getSubject());
} else if (securityContext != null) {
Principal user = securityContext.getUserPrincipal();
if (user != null) {
Subject subject = new Subject();
subject.getPrincipals().add(user);
camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, subject);
}
}
// Propagating properties from CXF Exchange to Camel Exchange has an
// side effect of copying reply side stuff when the producer is retried.
// So, we do not want to do this.
//camelExchange.getProperties().putAll(cxfExchange);
// propagate request context
Object value = cxfMessage.get(Client.REQUEST_CONTEXT);
if (value != null && !headerFilterStrategy.applyFilterToExternalHeaders(Client.REQUEST_CONTEXT, value, camelExchange)) {
camelExchange.getIn().setHeader(Client.REQUEST_CONTEXT, value);
LOG.trace("Populate context from CXF message {} value={}", Client.REQUEST_CONTEXT, value);
}
// setup the charset from content-type header
setCharsetWithContentType(camelExchange);
// set body
String encoding = (String) camelExchange.getProperty(Exchange.CHARSET_NAME);
Object body = DefaultCxfBinding.getContentFromCxf(cxfMessage, camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class), encoding);
if (body != null) {
camelExchange.getIn().setBody(body);
}
// propagate attachments if the data format is not POJO
if (cxfMessage.getAttachments() != null && !camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class).equals(DataFormat.POJO)) {
for (Attachment attachment : cxfMessage.getAttachments()) {
camelExchange.getIn().addAttachmentObject(attachment.getId(), createCamelAttachment(attachment));
}
}
}
use of org.apache.camel.ExchangePattern in project camel by apache.
the class InterceptSendToEndpoint method createProducer.
public Producer createProducer() throws Exception {
producer = delegate.createProducer();
return new DefaultAsyncProducer(delegate) {
public Endpoint getEndpoint() {
return producer.getEndpoint();
}
public Exchange createExchange() {
return producer.createExchange();
}
public Exchange createExchange(ExchangePattern pattern) {
return producer.createExchange(pattern);
}
@Deprecated
public Exchange createExchange(Exchange exchange) {
return producer.createExchange(exchange);
}
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
// process the detour so we do the detour routing
if (LOG.isDebugEnabled()) {
LOG.debug("Sending to endpoint: {} is intercepted and detoured to: {} for exchange: {}", new Object[] { getEndpoint(), detour, exchange });
}
// add header with the real endpoint uri
exchange.getIn().setHeader(Exchange.INTERCEPTED_ENDPOINT, delegate.getEndpointUri());
// detour the exchange using synchronous processing
try {
detour.process(exchange);
} catch (Exception e) {
exchange.setException(e);
}
// check for error if so we should break out
if (!continueProcessing(exchange, "skip sending to original intended destination: " + getEndpoint(), LOG)) {
callback.done(true);
return true;
}
// determine if we should skip or not
boolean shouldSkip = skip;
// if then interceptor had a when predicate, then we should only skip if it matched
Boolean whenMatches = (Boolean) exchange.removeProperty(Exchange.INTERCEPT_SEND_TO_ENDPOINT_WHEN_MATCHED);
if (whenMatches != null) {
shouldSkip = skip && whenMatches;
}
if (!shouldSkip) {
if (exchange.hasOut()) {
// replace OUT with IN as detour changed something
exchange.setIn(exchange.getOut());
exchange.setOut(null);
}
// route to original destination leveraging the asynchronous routing engine if possible
if (producer instanceof AsyncProcessor) {
AsyncProcessor async = (AsyncProcessor) producer;
return async.process(exchange, callback);
} else {
try {
producer.process(exchange);
} catch (Exception e) {
exchange.setException(e);
}
callback.done(true);
return true;
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Stop() means skip sending exchange to original intended destination: {} for exchange: {}", getEndpoint(), exchange);
}
callback.done(true);
return true;
}
}
public boolean isSingleton() {
return producer.isSingleton();
}
public void start() throws Exception {
ServiceHelper.startService(detour);
// here we also need to start the producer
ServiceHelper.startService(producer);
}
public void stop() throws Exception {
// do not stop detour as it should only be stopped when the interceptor stops
// we should stop the producer here
ServiceHelper.stopService(producer);
}
};
}
use of org.apache.camel.ExchangePattern in project camel by apache.
the class RecipientListProcessor method createProcessorExchangePairs.
@Override
protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) throws Exception {
// here we iterate the recipient lists and create the exchange pair for each of those
List<ProcessorExchangePair> result = new ArrayList<ProcessorExchangePair>();
// at first we must lookup the endpoint and acquire the producer which can send to the endpoint
int index = 0;
while (iter.hasNext()) {
Object recipient = iter.next();
Endpoint endpoint;
Producer producer;
ExchangePattern pattern;
try {
endpoint = resolveEndpoint(exchange, recipient);
pattern = resolveExchangePattern(recipient);
producer = producerCache.acquireProducer(endpoint);
} catch (Exception e) {
if (isIgnoreInvalidEndpoints()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Endpoint uri is invalid: " + recipient + ". This exception will be ignored.", e);
}
continue;
} else {
// failure so break out
throw e;
}
}
// then create the exchange pair
result.add(createProcessorExchangePair(index++, endpoint, producer, exchange, pattern));
}
return result;
}
use of org.apache.camel.ExchangePattern in project camel by apache.
the class RoutingSlip method processExchange.
protected boolean processExchange(final Endpoint endpoint, final Exchange exchange, final Exchange original, final AsyncCallback callback, final RoutingSlipIterator iter) {
// this does the actual processing so log at trace level
log.trace("Processing exchangeId: {} >>> {}", exchange.getExchangeId(), exchange);
boolean sync = producerCache.doInAsyncProducer(endpoint, exchange, null, callback, new AsyncProducerCallback() {
public boolean doInAsyncProducer(Producer producer, AsyncProcessor asyncProducer, final Exchange exchange, ExchangePattern exchangePattern, final AsyncCallback callback) {
// rework error handling to support fine grained error handling
RouteContext routeContext = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
AsyncProcessor target = createErrorHandler(routeContext, exchange, asyncProducer, endpoint);
// set property which endpoint we send to
exchange.setProperty(Exchange.TO_ENDPOINT, endpoint.getEndpointUri());
exchange.setProperty(Exchange.SLIP_ENDPOINT, endpoint.getEndpointUri());
boolean answer = target.process(exchange, new AsyncCallback() {
public void done(boolean doneSync) {
// we only have to handle async completion of the routing slip
if (doneSync) {
callback.done(doneSync);
return;
}
// continue processing the routing slip asynchronously
Exchange current = prepareExchangeForRoutingSlip(exchange, endpoint);
while (iter.hasNext(current)) {
// we ignore some kind of exceptions and allow us to continue
if (isIgnoreInvalidEndpoints()) {
FailedToCreateProducerException e = current.getException(FailedToCreateProducerException.class);
if (e != null) {
if (log.isDebugEnabled()) {
log.debug("Endpoint uri is invalid: " + endpoint + ". This exception will be ignored.", e);
}
current.setException(null);
}
}
// check for error if so we should break out
if (!continueProcessing(current, "so breaking out of the routing slip", log)) {
break;
}
Endpoint endpoint;
try {
endpoint = resolveEndpoint(iter, exchange);
// if no endpoint was resolved then try the next
if (endpoint == null) {
continue;
}
} catch (Exception e) {
// error resolving endpoint so we should break out
exchange.setException(e);
break;
}
// prepare and process the routing slip
boolean sync = processExchange(endpoint, current, original, callback, iter);
current = prepareExchangeForRoutingSlip(current, endpoint);
if (!sync) {
log.trace("Processing exchangeId: {} is continued being processed asynchronously", original.getExchangeId());
return;
}
}
// logging nextExchange as it contains the exchange that might have altered the payload and since
// we are logging the completion if will be confusing if we log the original instead
// we could also consider logging the original and the nextExchange then we have *before* and *after* snapshots
log.trace("Processing complete for exchangeId: {} >>> {}", original.getExchangeId(), current);
// copy results back to the original exchange
ExchangeHelper.copyResults(original, current);
if (target instanceof DeadLetterChannel) {
Processor deadLetter = ((DeadLetterChannel) target).getDeadLetter();
try {
ServiceHelper.stopService(deadLetter);
} catch (Exception e) {
log.warn("Error stopping DeadLetterChannel error handler on routing slip. This exception is ignored.", e);
}
}
callback.done(false);
}
});
// stop error handler if we completed synchronously
if (answer) {
if (target instanceof DeadLetterChannel) {
Processor deadLetter = ((DeadLetterChannel) target).getDeadLetter();
try {
ServiceHelper.stopService(deadLetter);
} catch (Exception e) {
log.warn("Error stopping DeadLetterChannel error handler on routing slip. This exception is ignored.", e);
}
}
}
return answer;
}
});
return sync;
}
use of org.apache.camel.ExchangePattern in project camel by apache.
the class SendProcessor method process.
public boolean process(Exchange exchange, final AsyncCallback callback) {
if (!isStarted()) {
exchange.setException(new IllegalStateException("SendProcessor has not been started: " + this));
callback.done(true);
return true;
}
// we should preserve existing MEP so remember old MEP
// if you want to permanently to change the MEP then use .setExchangePattern in the DSL
final ExchangePattern existingPattern = exchange.getPattern();
counter++;
// if we have a producer then use that as its optimized
if (producer != null) {
// record timing for sending the exchange using the producer
final StopWatch watch = new StopWatch();
final Exchange target = configureExchange(exchange, pattern);
EventHelper.notifyExchangeSending(exchange.getContext(), target, destination);
LOG.debug(">>>> {} {}", destination, exchange);
boolean sync = true;
try {
sync = producer.process(exchange, new AsyncCallback() {
@Override
public void done(boolean doneSync) {
try {
// restore previous MEP
target.setPattern(existingPattern);
// emit event that the exchange was sent to the endpoint
long timeTaken = watch.stop();
EventHelper.notifyExchangeSent(target.getContext(), target, destination, timeTaken);
} finally {
callback.done(doneSync);
}
}
});
} catch (Throwable throwable) {
exchange.setException(throwable);
callback.done(sync);
}
return sync;
}
// send the exchange to the destination using the producer cache for the non optimized producers
return producerCache.doInAsyncProducer(destination, exchange, pattern, callback, new AsyncProducerCallback() {
public boolean doInAsyncProducer(Producer producer, AsyncProcessor asyncProducer, final Exchange exchange, ExchangePattern pattern, final AsyncCallback callback) {
final Exchange target = configureExchange(exchange, pattern);
LOG.debug(">>>> {} {}", destination, exchange);
return asyncProducer.process(target, new AsyncCallback() {
public void done(boolean doneSync) {
// restore previous MEP
target.setPattern(existingPattern);
// signal we are done
callback.done(doneSync);
}
});
}
});
}
Aggregations