org.apache.camel.AsyncCallback Java Examples

The following examples show how to use org.apache.camel.AsyncCallback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KnativeHttpSupport.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Remap camel headers to cloud event http headers.
 */
public static Processor remapCloudEventHeaders(Processor delegate, CloudEvent ce) {
    return new DelegateAsyncProcessor(delegate) {
        @Override
        public boolean process(Exchange exchange, AsyncCallback callback) {
            return processor.process(exchange, doneSync -> {
                final Message message = exchange.getMessage();

                // remap CloudEvent camel --> http
                for (CloudEvent.Attribute attr : ce.attributes()) {
                    Object value = message.getHeader(attr.id());
                    if (value != null) {
                        message.setHeader(attr.http(), value);
                    }
                }

                callback.done(doneSync);
            });
        }
    };
}
 
Example #2
Source File: HeaderDrivenSlowOperationProcessor.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(final Exchange exchange,
                       final AsyncCallback asyncCallback) {
    final Message in = exchange.getIn();
    if (in.getHeader("processAsync", Boolean.class)) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                in.setBody("Processed async: " + in.getBody(String.class));
                asyncCallback.done(false);
            }
        });
        return false;
    } else {
        in.setBody("Processed sync: " + in.getBody(String.class));
        asyncCallback.done(true);
        return true;
    }
}
 
Example #3
Source File: SlowOperationProcessor.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(final Exchange exchange, final AsyncCallback asyncCallback) {
    final boolean completedSynchronously = false;

    backgroundExecutor.submit(new Runnable() {
        @Override
        public void run() {
            log.info("Running operation asynchronously");
            try {
                log.info("Doing something slowly");
                Thread.sleep(200); // this runs slowly
                log.info("...done");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            // the current thread will continue to process the exchange
            // through the remainder of the route
            asyncCallback.done(completedSynchronously);
        }
    });

    return completedSynchronously;
}
 
Example #4
Source File: TracingInterceptStrategy.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("try")
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    final Message in = exchange.getIn();
    final Span activitySpan = exchange.getProperty(IntegrationLoggingConstants.ACTIVITY_SPAN, Span.class);
    try (Scope activityScope = tracer.scopeManager().activate(activitySpan)) {
        Span span = tracer.buildSpan(stepId).withTag(Tags.SPAN_KIND.getKey(), "step").start();
        in.setHeader(IntegrationLoggingConstants.STEP_SPAN, span);
        return super.process(exchange, doneSync -> {
            String failure = failure(exchange);
            if (failure != null) {
                span.setTag(Tags.ERROR.getKey(), true);
                span.log(failure);
            }
            span.finish();
            callback.done(doneSync);
        });
    }
}
 
Example #5
Source File: ActivityTrackingInterceptStrategy.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    final String trackerId = KeyGenerator.createKey();
    final long createdAt = System.nanoTime();
    final Message in = exchange.getIn();
    in.setHeader(IntegrationLoggingConstants.STEP_TRACKER_ID, trackerId);

    return super.process(exchange, doneSync -> {
        final String activityId =  ActivityTracker.getActivityId(exchange);

        if (activityId != null) {
            tracker.track(
                "exchange", activityId,
                "step", stepId,
                "id", trackerId,
                "duration", System.nanoTime() - createdAt,
                "failure", failure(exchange)
            );
        }

        callback.done(doneSync);
    });
}
 
Example #6
Source File: KnativeHttpSupport.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Removes cloud event headers at the end of the processing.
 */
public static Processor withoutCloudEventHeaders(Processor delegate, CloudEvent ce) {
    return new DelegateAsyncProcessor(delegate) {
        @Override
        public boolean process(Exchange exchange, AsyncCallback callback) {
            return processor.process(exchange, doneSync -> {
                final Message message = exchange.getMessage();

                // remove CloudEvent headers
                for (CloudEvent.Attribute attr : ce.attributes()) {
                    message.removeHeader(attr.http());
                }

                callback.done(doneSync);
            });
        }
    };
}
 
Example #7
Source File: patched.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public boolean process(Exchange exchange, AsyncCallback callback) {
    final AtomicExchange result = new AtomicExchange();
    Iterable<ProcessorExchangePair> pairs = null;

    try {
        boolean sync = true;

        pairs = createProcessorExchangePairs(exchange);

        if (isParallelProcessing()) {
            // ensure an executor is set when running in parallel
            ObjectHelper.notNull(executorService, "executorService", this);
            doProcessParallel(exchange, result, pairs, isStreaming(), callback);
        } else {
            sync = doProcessSequential(exchange, result, pairs, callback);
        }

        if (!sync) {
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }
    } catch (Throwable e) {
        exchange.setException(e);
        // unexpected exception was thrown, maybe from iterator etc. so do not regard as exhausted
        // and do the done work
        doDone(exchange, null, pairs, callback, true, false);
        return true;
    }

    // multicasting was processed successfully
    // and do the done work
    Exchange subExchange = result.get() != null ? result.get() : null;
    doDone(exchange, subExchange, pairs, callback, true, true);
    return true;
}
 
Example #8
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
protected boolean doProcessSequential(Exchange original, AtomicExchange result, Iterable<ProcessorExchangePair> pairs, AsyncCallback callback) throws Exception {
    AtomicInteger total = new AtomicInteger();
    Iterator<ProcessorExchangePair> it = pairs.iterator();

    while (it.hasNext()) {
        ProcessorExchangePair pair = it.next();
        Exchange subExchange = pair.getExchange();
        updateNewExchange(subExchange, total.get(), pairs, it);

        boolean sync = doProcessSequential(original, result, pairs, it, pair, callback, total);
        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", pair.getExchange().getExchangeId());
            }
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: {} is continued being processed synchronously", pair.getExchange().getExchangeId());
        }

        // Decide whether to continue with the multicast or not; similar logic to the Pipeline
        // remember to test for stop on exception and aggregate before copying back results
        boolean continueProcessing = PipelineHelper.continueProcessing(subExchange, "Sequential processing failed for number " + total.get(), LOG);
        if (stopOnException && !continueProcessing) {
            if (subExchange.getException() != null) {
                // wrap in exception to explain where it failed
                CamelExchangeException cause = new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException());
                subExchange.setException(cause);
            }
            // we want to stop on exception, and the exception was handled by the error handler
            // this is similar to what the pipeline does, so we should do the same to not surprise end users
            // so we should set the failed exchange as the result and be done
            result.set(subExchange);
            return true;
        }

        LOG.trace("Sequential processing complete for number {} exchange: {}", total, subExchange);

        if (parallelAggregate) {
            doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
        } else {
            doAggregate(getAggregationStrategy(subExchange), result, subExchange);
        }

        total.incrementAndGet();
    }

    LOG.debug("Done sequential processing {} exchanges", total);

    return true;
}
 
Example #9
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public boolean process(Exchange exchange, AsyncCallback callback) {
    final AtomicExchange result = new AtomicExchange();
    Iterable<ProcessorExchangePair> pairs = null;

    try {
        boolean sync = true;

        pairs = createProcessorExchangePairs(exchange);

        if (isParallelProcessing()) {
            // ensure an executor is set when running in parallel
            ObjectHelper.notNull(executorService, "executorService", this);
            doProcessParallel(exchange, result, pairs, isStreaming(), callback);
        } else {
            sync = doProcessSequential(exchange, result, pairs, callback);
        }

        if (!sync) {
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }
    } catch (Throwable e) {
        exchange.setException(e);
        // unexpected exception was thrown, maybe from iterator etc. so do not regard as exhausted
        // and do the done work
        doDone(exchange, null, pairs, callback, true, false);
        return true;
    }

    // multicasting was processed successfully
    // and do the done work
    Exchange subExchange = result.get() != null ? result.get() : null;
    doDone(exchange, subExchange, pairs, callback, true, true);
    return true;
}
 
Example #10
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
protected boolean doProcessSequential(Exchange original, AtomicExchange result, Iterable<ProcessorExchangePair> pairs, AsyncCallback callback) throws Exception {
    AtomicInteger total = new AtomicInteger();
    Iterator<ProcessorExchangePair> it = pairs.iterator();

    while (it.hasNext()) {
        ProcessorExchangePair pair = it.next();
        Exchange subExchange = pair.getExchange();
        updateNewExchange(subExchange, total.get(), pairs, it);

        boolean sync = doProcessSequential(original, result, pairs, it, pair, callback, total);
        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", pair.getExchange().getExchangeId());
            }
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: {} is continued being processed synchronously", pair.getExchange().getExchangeId());
        }

        // Decide whether to continue with the multicast or not; similar logic to the Pipeline
        // remember to test for stop on exception and aggregate before copying back results
        boolean continueProcessing = PipelineHelper.continueProcessing(subExchange, "Sequential processing failed for number " + total.get(), LOG);
        if (stopOnException && !continueProcessing) {
            if (subExchange.getException() != null) {
                // wrap in exception to explain where it failed
                CamelExchangeException cause = new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException());
                subExchange.setException(cause);
            }
            // we want to stop on exception, and the exception was handled by the error handler
            // this is similar to what the pipeline does, so we should do the same to not surprise end users
            // so we should set the failed exchange as the result and be done
            result.set(subExchange);
            return true;
        }

        LOG.trace("Sequential processing complete for number {} exchange: {}", total, subExchange);

        if (parallelAggregate) {
            doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
        } else {
            doAggregate(getAggregationStrategy(subExchange), result, subExchange);
        }

        total.incrementAndGet();
    }

    LOG.debug("Done sequential processing {} exchanges", total);

    return true;
}
 
Example #11
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public boolean process(Exchange exchange, AsyncCallback callback) {
    final AtomicExchange result = new AtomicExchange();
    Iterable<ProcessorExchangePair> pairs = null;

    try {
        boolean sync = true;

        pairs = createProcessorExchangePairs(exchange);

        if (isParallelProcessing()) {
            // ensure an executor is set when running in parallel
            ObjectHelper.notNull(executorService, "executorService", this);
            doProcessParallel(exchange, result, pairs, isStreaming(), callback);
        } else {
            sync = doProcessSequential(exchange, result, pairs, callback);
        }

        if (!sync) {
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }
    } catch (Throwable e) {
        exchange.setException(e);
        // unexpected exception was thrown, maybe from iterator etc. so do not regard as exhausted
        // and do the done work
        doDone(exchange, null, pairs, callback, true, false);
        return true;
    }

    // multicasting was processed successfully
    // and do the done work
    Exchange subExchange = result.get() != null ? result.get() : null;
    doDone(exchange, subExchange, pairs, callback, true, true);
    return true;
}
 
Example #12
Source File: original.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
protected boolean doProcessSequential(Exchange original, AtomicExchange result, Iterable<ProcessorExchangePair> pairs, AsyncCallback callback) throws Exception {
    AtomicInteger total = new AtomicInteger();
    Iterator<ProcessorExchangePair> it = pairs.iterator();

    while (it.hasNext()) {
        ProcessorExchangePair pair = it.next();
        Exchange subExchange = pair.getExchange();
        updateNewExchange(subExchange, total.get(), pairs, it);

        boolean sync = doProcessSequential(original, result, pairs, it, pair, callback, total);
        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", pair.getExchange().getExchangeId());
            }
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: {} is continued being processed synchronously", pair.getExchange().getExchangeId());
        }

        // Decide whether to continue with the multicast or not; similar logic to the Pipeline
        // remember to test for stop on exception and aggregate before copying back results
        boolean continueProcessing = PipelineHelper.continueProcessing(subExchange, "Sequential processing failed for number " + total.get(), LOG);
        if (stopOnException && !continueProcessing) {
            if (subExchange.getException() != null) {
                // wrap in exception to explain where it failed
                CamelExchangeException cause = new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException());
                subExchange.setException(cause);
            }
            // we want to stop on exception, and the exception was handled by the error handler
            // this is similar to what the pipeline does, so we should do the same to not surprise end users
            // so we should set the failed exchange as the result and be done
            result.set(subExchange);
            return true;
        }

        LOG.trace("Sequential processing complete for number {} exchange: {}", total, subExchange);

        if (parallelAggregate) {
            doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
        } else {
            doAggregate(getAggregationStrategy(subExchange), result, subExchange);
        }

        total.incrementAndGet();
    }

    LOG.debug("Done sequential processing {} exchanges", total);

    return true;
}
 
Example #13
Source File: original.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public boolean process(Exchange exchange, AsyncCallback callback) {
    final AtomicExchange result = new AtomicExchange();
    Iterable<ProcessorExchangePair> pairs = null;

    try {
        boolean sync = true;

        pairs = createProcessorExchangePairs(exchange);

        if (isParallelProcessing()) {
            // ensure an executor is set when running in parallel
            ObjectHelper.notNull(executorService, "executorService", this);
            doProcessParallel(exchange, result, pairs, isStreaming(), callback);
        } else {
            sync = doProcessSequential(exchange, result, pairs, callback);
        }

        if (!sync) {
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }
    } catch (Throwable e) {
        exchange.setException(e);
        // unexpected exception was thrown, maybe from iterator etc. so do not regard as exhausted
        // and do the done work
        doDone(exchange, null, pairs, callback, true, false);
        return true;
    }

    // multicasting was processed successfully
    // and do the done work
    Exchange subExchange = result.get() != null ? result.get() : null;
    doDone(exchange, subExchange, pairs, callback, true, true);
    return true;
}
 
Example #14
Source File: patched.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
protected boolean doProcessSequential(Exchange original, AtomicExchange result, Iterable<ProcessorExchangePair> pairs, AsyncCallback callback) throws Exception {
    AtomicInteger total = new AtomicInteger();
    Iterator<ProcessorExchangePair> it = pairs.iterator();

    while (it.hasNext()) {
        ProcessorExchangePair pair = it.next();
        Exchange subExchange = pair.getExchange();
        updateNewExchange(subExchange, total.get(), pairs, it);

        boolean sync = doProcessSequential(original, result, pairs, it, pair, callback, total);
        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", pair.getExchange().getExchangeId());
            }
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: {} is continued being processed synchronously", pair.getExchange().getExchangeId());
        }

        // Decide whether to continue with the multicast or not; similar logic to the Pipeline
        // remember to test for stop on exception and aggregate before copying back results
        boolean continueProcessing = PipelineHelper.continueProcessing(subExchange, "Sequential processing failed for number " + total.get(), LOG);
        if (stopOnException && !continueProcessing) {
            if (subExchange.getException() != null) {
                // wrap in exception to explain where it failed
                CamelExchangeException cause = new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException());
                subExchange.setException(cause);
            }
            // we want to stop on exception, and the exception was handled by the error handler
            // this is similar to what the pipeline does, so we should do the same to not surprise end users
            // so we should set the failed exchange as the result and be done
            result.set(subExchange);
            return true;
        }

        LOG.trace("Sequential processing complete for number {} exchange: {}", total, subExchange);

        if (parallelAggregate) {
            doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
        } else {
            doAggregate(getAggregationStrategy(subExchange), result, subExchange);
        }

        total.incrementAndGet();
    }

    LOG.debug("Done sequential processing {} exchanges", total);

    return true;
}
 
Example #15
Source File: ActivityTrackingInterceptStrategy.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Exchange exchange, final AsyncCallback callback) {
    final String activityId =  ActivityTracker.getActivityId(exchange);
    if (activityId != null) {
        tracker.track(
            "exchange", activityId,
            "step", stepId,
            "id", KeyGenerator.createKey(),
            "duration", 0L,
            "failure", null
        );
    }

    return super.process(exchange, callback::done);
}
 
Example #16
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
protected boolean doProcessSequential(Exchange original, AtomicExchange result, Iterable<ProcessorExchangePair> pairs, AsyncCallback callback) throws Exception {
    AtomicInteger total = new AtomicInteger();
    Iterator<ProcessorExchangePair> it = pairs.iterator();

    while (it.hasNext()) {
        ProcessorExchangePair pair = it.next();
        Exchange subExchange = pair.getExchange();
        updateNewExchange(subExchange, total.get(), pairs, it);

        boolean sync = doProcessSequential(original, result, pairs, it, pair, callback, total);
        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", pair.getExchange().getExchangeId());
            }
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: {} is continued being processed synchronously", pair.getExchange().getExchangeId());
        }

        // Decide whether to continue with the multicast or not; similar logic to the Pipeline
        // remember to test for stop on exception and aggregate before copying back results
        boolean continueProcessing = PipelineHelper.continueProcessing(subExchange, "Sequential processing failed for number " + total.get(), LOG);
        if (stopOnException && !continueProcessing) {
            if (subExchange.getException() != null) {
                // wrap in exception to explain where it failed
                CamelExchangeException cause = new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException());
                subExchange.setException(cause);
            }
            // we want to stop on exception, and the exception was handled by the error handler
            // this is similar to what the pipeline does, so we should do the same to not surprise end users
            // so we should set the failed exchange as the result and be done
            result.set(subExchange);
            return true;
        }

        LOG.trace("Sequential processing complete for number {} exchange: {}", total, subExchange);

        if (parallelAggregate) {
            doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
        } else {
            doAggregate(getAggregationStrategy(subExchange), result, subExchange);
        }

        total.incrementAndGet();
    }

    LOG.debug("Done sequential processing {} exchanges", total);

    return true;
}
 
Example #17
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public boolean process(Exchange exchange, AsyncCallback callback) {
    final AtomicExchange result = new AtomicExchange();
    Iterable<ProcessorExchangePair> pairs = null;

    try {
        boolean sync = true;

        pairs = createProcessorExchangePairs(exchange);

        if (isParallelProcessing()) {
            // ensure an executor is set when running in parallel
            ObjectHelper.notNull(executorService, "executorService", this);
            doProcessParallel(exchange, result, pairs, isStreaming(), callback);
        } else {
            sync = doProcessSequential(exchange, result, pairs, callback);
        }

        if (!sync) {
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }
    } catch (Throwable e) {
        exchange.setException(e);
        // unexpected exception was thrown, maybe from iterator etc. so do not regard as exhausted
        // and do the done work
        doDone(exchange, null, pairs, callback, true, false);
        return true;
    }

    // multicasting was processed successfully
    // and do the done work
    Exchange subExchange = result.get() != null ? result.get() : null;
    doDone(exchange, subExchange, pairs, callback, true, true);
    return true;
}
 
Example #18
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
protected boolean doProcessSequential(Exchange original, AtomicExchange result, Iterable<ProcessorExchangePair> pairs, AsyncCallback callback) throws Exception {
    AtomicInteger total = new AtomicInteger();
    Iterator<ProcessorExchangePair> it = pairs.iterator();

    while (it.hasNext()) {
        ProcessorExchangePair pair = it.next();
        Exchange subExchange = pair.getExchange();
        updateNewExchange(subExchange, total.get(), pairs, it);

        boolean sync = doProcessSequential(original, result, pairs, it, pair, callback, total);
        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", pair.getExchange().getExchangeId());
            }
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: {} is continued being processed synchronously", pair.getExchange().getExchangeId());
        }

        // Decide whether to continue with the multicast or not; similar logic to the Pipeline
        // remember to test for stop on exception and aggregate before copying back results
        boolean continueProcessing = PipelineHelper.continueProcessing(subExchange, "Sequential processing failed for number " + total.get(), LOG);
        if (stopOnException && !continueProcessing) {
            if (subExchange.getException() != null) {
                // wrap in exception to explain where it failed
                CamelExchangeException cause = new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException());
                subExchange.setException(cause);
            }
            // we want to stop on exception, and the exception was handled by the error handler
            // this is similar to what the pipeline does, so we should do the same to not surprise end users
            // so we should set the failed exchange as the result and be done
            result.set(subExchange);
            return true;
        }

        LOG.trace("Sequential processing complete for number {} exchange: {}", total, subExchange);

        if (parallelAggregate) {
            doAggregateInternal(getAggregationStrategy(subExchange), result, subExchange);
        } else {
            doAggregate(getAggregationStrategy(subExchange), result, subExchange);
        }

        total.incrementAndGet();
    }

    LOG.debug("Done sequential processing {} exchanges", total);

    return true;
}
 
Example #19
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public boolean process(Exchange exchange, AsyncCallback callback) {
    final AtomicExchange result = new AtomicExchange();
    Iterable<ProcessorExchangePair> pairs = null;

    try {
        boolean sync = true;

        pairs = createProcessorExchangePairs(exchange);

        if (isParallelProcessing()) {
            // ensure an executor is set when running in parallel
            ObjectHelper.notNull(executorService, "executorService", this);
            doProcessParallel(exchange, result, pairs, isStreaming(), callback);
        } else {
            sync = doProcessSequential(exchange, result, pairs, callback);
        }

        if (!sync) {
            // the remainder of the multicast will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }
    } catch (Throwable e) {
        exchange.setException(e);
        // unexpected exception was thrown, maybe from iterator etc. so do not regard as exhausted
        // and do the done work
        doDone(exchange, null, pairs, callback, true, false);
        return true;
    }

    // multicasting was processed successfully
    // and do the done work
    Exchange subExchange = result.get() != null ? result.get() : null;
    doDone(exchange, subExchange, pairs, callback, true, true);
    return true;
}
 
Example #20
Source File: ErpProducer.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    // simulate async communication using a thread pool in which will return a reply in 5 seconds.
    executor.submit(new ERPTask(exchange, callback));

    // return false to tell Camel that we process asynchronously
    // which enables the Camel routing engine to know this and act accordingly
    // notice the ERPTask must invoke the callback.done(false) because what
    // we return here must match the boolean in the callback.done method.
    log.info("Returning false (processing will continue asynchronously)");
    return false;
}
 
Example #21
Source File: ErpProducer.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    // simulate async communication using a thread pool in which will return a reply in 5 seconds.
    executor.submit(new ERPTask(exchange, callback));

    // return false to tell Camel that we process asynchronously
    // which enables the Camel routing engine to know this and act accordingly
    // notice the ERPTask must invoke the callback.done(false) because what
    // we return here must match the boolean in the callback.done method.
    log.info("Returning false (processing will continue asynchronously)");
    return false;
}
 
Example #22
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #23
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #24
Source File: patched.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #25
Source File: ErpProducer.java    From camelinaction with Apache License 2.0 4 votes vote down vote up
private ERPTask(Exchange exchange, AsyncCallback callback) {
    this.exchange = exchange;
    this.callback = callback;
}
 
Example #26
Source File: original.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #27
Source File: ErpProducer.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
private ERPTask(Exchange exchange, AsyncCallback callback) {
    this.exchange = exchange;
    this.callback = callback;
}
 
Example #28
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #29
Source File: CamelToVertxProcessor.java    From vertx-camel-bridge with Apache License 2.0 4 votes vote down vote up
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
  Message in = exchange.getIn();

  Object body = CamelHelper.convert(inbound, in);

  DeliveryOptions delivery = CamelHelper.getDeliveryOptions(in, inbound.isHeadersCopy());
  if (inbound.getTimeout() > 0) {
    delivery.setSendTimeout(inbound.getTimeout());
  }

  try {
    if (inbound.isPublish()) {
      vertx.eventBus().publish(inbound.getAddress(), body, delivery);
    } else {
      if (ExchangeHelper.isOutCapable(exchange)) {
        vertx.eventBus().request(inbound.getAddress(), body, delivery, reply -> {
          Message out = exchange.getOut();
          if (reply.succeeded()) {
            out.setBody(reply.result().body());
            MultiMapHelper.toMap(reply.result().headers(), out.getHeaders());
          } else {
            exchange.setException(reply.cause());
          }
          // continue callback
          callback.done(false);
        });
        // being routed async so return false
        return false;
      } else {
        // No reply expected.
        vertx.eventBus().send(inbound.getAddress(), body, delivery);
      }
    }
  } catch (Throwable e) {
    // Mark the exchange as "failed".
    exchange.setException(e);
  }

  callback.done(true);
  return true;
}
 
Example #30
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}