Java Code Examples for org.apache.camel.Exchange#getException()

The following examples show how to use org.apache.camel.Exchange#getException() . 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: CouchdbResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/get")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String get(CouchdbTestDocument document) {
    LOG.info("Invoking get");
    Exchange getExchange = producerTemplate.request(COUCHDB_ENDPOINT_URI, e -> {
        e.getMessage().setBody(document.toJsonObject());
        e.getMessage().setHeader(CouchDbConstants.HEADER_METHOD, CouchDbOperations.GET);
        e.getMessage().setHeader(CouchDbConstants.HEADER_DOC_ID, document.getId());
    });
    if (getExchange.getException(NoDocumentException.class) != null) {
        return null;
    } else {
        return getExchange.getMessage().getBody(String.class);
    }
}
 
Example 2
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) throws Exception {
    List<ProcessorExchangePair> result = new ArrayList<ProcessorExchangePair>(processors.size());

    int index = 0;
    for (Processor processor : processors) {
        // copy exchange, and do not share the unit of work
        Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false);

        // if we share unit of work, we need to prepare the child exchange
        if (isShareUnitOfWork()) {
            prepareSharedUnitOfWork(copy, exchange);
        }

        // and add the pair
        RouteContext routeContext = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
        result.add(createProcessorExchangePair(index++, processor, copy, routeContext));
    }

    if (exchange.getException() != null) {
        // force any exceptions occurred during creation of exchange paris to be thrown
        // before returning the answer;
        throw exchange.getException();
    }

    return result;
}
 
Example 3
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) throws Exception {
    List<ProcessorExchangePair> result = new ArrayList<ProcessorExchangePair>(processors.size());

    int index = 0;
    for (Processor processor : processors) {
        // copy exchange, and do not share the unit of work
        Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false);

        // if we share unit of work, we need to prepare the child exchange
        if (isShareUnitOfWork()) {
            prepareSharedUnitOfWork(copy, exchange);
        }

        // and add the pair
        RouteContext routeContext = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
        result.add(createProcessorExchangePair(index++, processor, copy, routeContext));
    }

    if (exchange.getException() != null) {
        // force any exceptions occurred during creation of exchange paris to be thrown
        // before returning the answer;
        throw exchange.getException();
    }

    return result;
}
 
Example 4
Source File: MyConsumer.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
@Override
// poll method will fire every 500 ms by default 
protected int poll() throws Exception {
    Exchange exchange = endpoint.createExchange();

    // create a message body
    Date now = new Date();
    exchange.getIn().setBody("Hello World! The time is " + now);

    try {
        // send message to next processor in the route
        getProcessor().process(exchange);
    } finally {
        // log exception if an exception occurred and was not handled
        if (exchange.getException() != null) {
            getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
        }
    }

    // we consumed 1 message
    return 1;
}
 
Example 5
Source File: MyIgnoreFailureAggregationStrategy.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
    // check if there was an exception thrown
    if (newExchange.getException() != null) {
        // yes there was, so we just handle it by ignoring it
        return oldExchange;
    }

    if (oldExchange == null) {
        // this is the first time so no existing aggregated exchange
        return newExchange;
    }

    // append the new word to the existing
    String body = newExchange.getIn().getBody(String.class);
    String existing = oldExchange.getIn().getBody(String.class);

    oldExchange.getIn().setBody(existing + "+" + body);
    return oldExchange;
}
 
Example 6
Source File: original.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) throws Exception {
    List<ProcessorExchangePair> result = new ArrayList<ProcessorExchangePair>(processors.size());

    int index = 0;
    for (Processor processor : processors) {
        // copy exchange, and do not share the unit of work
        Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false);

        // if we share unit of work, we need to prepare the child exchange
        if (isShareUnitOfWork()) {
            prepareSharedUnitOfWork(copy, exchange);
        }

        // and add the pair
        RouteContext routeContext = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
        result.add(createProcessorExchangePair(index++, processor, copy, routeContext));
    }

    if (exchange.getException() != null) {
        // force any exceptions occurred during creation of exchange paris to be thrown
        // before returning the answer;
        throw exchange.getException();
    }

    return result;
}
 
Example 7
Source File: patched.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) throws Exception {
    List<ProcessorExchangePair> result = new ArrayList<ProcessorExchangePair>(processors.size());

    int index = 0;
    for (Processor processor : processors) {
        // copy exchange, and do not share the unit of work
        Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false);

        // if we share unit of work, we need to prepare the child exchange
        if (isShareUnitOfWork()) {
            prepareSharedUnitOfWork(copy, exchange);
        }

        // and add the pair
        RouteContext routeContext = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
        result.add(createProcessorExchangePair(index++, processor, copy, routeContext));
    }

    if (exchange.getException() != null) {
        // force any exceptions occurred during creation of exchange paris to be thrown
        // before returning the answer;
        throw exchange.getException();
    }

    return result;
}
 
Example 8
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) throws Exception {
    List<ProcessorExchangePair> result = new ArrayList<ProcessorExchangePair>(processors.size());

    int index = 0;
    for (Processor processor : processors) {
        // copy exchange, and do not share the unit of work
        Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false);

        // if we share unit of work, we need to prepare the child exchange
        if (isShareUnitOfWork()) {
            prepareSharedUnitOfWork(copy, exchange);
        }

        // and add the pair
        RouteContext routeContext = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
        result.add(createProcessorExchangePair(index++, processor, copy, routeContext));
    }

    if (exchange.getException() != null) {
        // force any exceptions occurred during creation of exchange paris to be thrown
        // before returning the answer;
        throw exchange.getException();
    }

    return result;
}
 
Example 9
Source File: CamelSinkTask.java    From camel-kafka-connector with Apache License 2.0 6 votes vote down vote up
@Override
public void put(Collection<SinkRecord> sinkRecords) {
    for (SinkRecord record : sinkRecords) {
        TaskHelper.logRecordContent(LOG, record, config);
        Map<String, Object> headers = new HashMap<String, Object>();
        Exchange exchange = new DefaultExchange(producer.getCamelContext());
        headers.put(KAFKA_RECORD_KEY_HEADER, record.key());
        for (Iterator<Header> iterator = record.headers().iterator(); iterator.hasNext();) {
            Header header = (Header)iterator.next();
            if (header.key().startsWith(HEADER_CAMEL_PREFIX)) {
                addHeader(headers, header);
            } else if (header.key().startsWith(PROPERTY_CAMEL_PREFIX)) {
                addProperty(exchange, header);
            }
        }
        exchange.getMessage().setHeaders(headers);
        exchange.getMessage().setBody(record.value());

        LOG.debug("Sending exchange {} to {}", exchange.getExchangeId(), LOCAL_URL);
        producer.send(LOCAL_URL, exchange);

        if (exchange.isFailed()) {
            throw new ConnectException("Exchange delivery has failed!", exchange.getException());
        }
    }
}
 
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: DataVecConsumer.java    From DataVec with Apache License 2.0 5 votes vote down vote up
@Override
protected int poll() throws Exception {
    Exchange exchange = endpoint.createExchange();
    InputSplit split = inputFromExchange(exchange);
    RecordReader reader = inputFormat.createReader(split, configuration);
    int numMessagesPolled = 0;
    while (reader.hasNext()) {
        // create a message body
        while (reader.hasNext()) {
            exchange.getIn().setBody(reader.next());

            try {
                // send message to next processor in the route
                getProcessor().process(exchange);
                numMessagesPolled++; // number of messages polled
            } finally {
                // log exception if an exception occurred and was not handled
                if (exchange.getException() != null) {
                    getExceptionHandler().handleException("Error processing exchange", exchange,
                                    exchange.getException());
                }
            }
        }


    }

    return numMessagesPolled;
}
 
Example 12
Source File: CamelBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected boolean handleCamelException(Exchange exchange, DelegateExecution execution, boolean isV5Execution) {
    Exception camelException = exchange.getException();
    boolean notHandledByCamel = exchange.isFailed() && camelException != null;
    if (notHandledByCamel) {
        if (camelException instanceof BpmnError) {
            if (isV5Execution) {
                Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
                compatibilityHandler.propagateError((BpmnError) camelException, execution);
                return true;
            }
            ErrorPropagation.propagateError((BpmnError) camelException, execution);
            return true;
        } else {
            if (isV5Execution) {
                Flowable5CompatibilityHandler ompatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
                if (ompatibilityHandler.mapException(camelException, execution, mapExceptions)) {
                    return true;
                } else {
                    throw new FlowableException("Unhandled exception on camel route", camelException);
                }
            }

            if (ErrorPropagation.mapException(camelException, (ExecutionEntity) execution, mapExceptions)) {
                return true;
            } else {
                throw new FlowableException("Unhandled exception on camel route", camelException);
            }
        }
    }
    return false;
}
 
Example 13
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 14
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 15
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 16
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 17
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 18
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 19
Source File: QuarkusPlatformHttpConsumer.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
static Object toHttpResponse(HttpServerResponse response, Message message, HeaderFilterStrategy headerFilterStrategy) {
    final Exchange exchange = message.getExchange();

    final int code = determineResponseCode(exchange, message.getBody());
    response.setStatusCode(code);

    final TypeConverter tc = exchange.getContext().getTypeConverter();

    // copy headers from Message to Response
    if (headerFilterStrategy != null) {
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null);
            String firstValue = null;
            List<String> values = null;
            while (it.hasNext()) {
                final String headerValue = tc.convertTo(String.class, it.next());
                if (headerValue != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, exchange)) {
                    if (firstValue == null) {
                        firstValue = headerValue;
                    } else {
                        if (values == null) {
                            values = new ArrayList<String>();
                            values.add(firstValue);
                        }
                        values.add(headerValue);
                    }
                }
            }
            if (values != null) {
                response.putHeader(key, values);
            } else if (firstValue != null) {
                response.putHeader(key, firstValue);
            }
        }
    }

    Object body = message.getBody();
    final Exception exception = exchange.getException();

    if (exception != null) {
        // we failed due an exception so print it as plain text
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);

        // the body should then be the stacktrace
        body = ByteBuffer.wrap(sw.toString().getBytes(StandardCharsets.UTF_8));
        // force content type to be text/plain as that is what the stacktrace is
        message.setHeader(Exchange.CONTENT_TYPE, "text/plain; charset=utf-8");

        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(exchange);
    }

    // set the content-length if it can be determined, or chunked encoding
    final Integer length = determineContentLength(exchange, body);
    if (length != null) {
        response.putHeader("Content-Length", String.valueOf(length));
    } else {
        response.setChunked(true);
    }

    // set the content type in the response.
    final String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.putHeader("Content-Type", contentType);
    }
    return body;
}
 
Example 20
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);
}