Search in sources :

Example 6 with Synchronization

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

the class S3Consumer method processBatch.

public int processBatch(Queue<Object> exchanges) throws Exception {
    int total = exchanges.size();
    for (int index = 0; index < total && isBatchAllowed(); index++) {
        // only loop if we are started (allowed to run)
        final Exchange exchange = ObjectHelper.cast(Exchange.class, exchanges.poll());
        // add current index and total as properties
        exchange.setProperty(Exchange.BATCH_INDEX, index);
        exchange.setProperty(Exchange.BATCH_SIZE, total);
        exchange.setProperty(Exchange.BATCH_COMPLETE, index == total - 1);
        // update pending number of exchanges
        pendingExchanges = total - index - 1;
        // add on completion to handle after work when the exchange is done
        exchange.addOnCompletion(new Synchronization() {

            public void onComplete(Exchange exchange) {
                processCommit(exchange);
            }

            public void onFailure(Exchange exchange) {
                processRollback(exchange);
            }

            @Override
            public String toString() {
                return "S3ConsumerOnCompletion";
            }
        });
        LOG.trace("Processing exchange [{}]...", exchange);
        getAsyncProcessor().process(exchange, new AsyncCallback() {

            @Override
            public void done(boolean doneSync) {
                LOG.trace("Processing exchange [{}] done.", exchange);
            }
        });
    }
    return total;
}
Also used : Exchange(org.apache.camel.Exchange) AsyncCallback(org.apache.camel.AsyncCallback) Synchronization(org.apache.camel.spi.Synchronization)

Example 7 with Synchronization

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

the class DefaultExchange method setUnitOfWork.

public void setUnitOfWork(UnitOfWork unitOfWork) {
    this.unitOfWork = unitOfWork;
    if (unitOfWork != null && onCompletions != null) {
        // we might have registered already
        for (Synchronization onCompletion : onCompletions) {
            unitOfWork.addSynchronization(onCompletion);
        }
        // cleanup the temporary on completion list as they now have been registered
        // on the unit of work
        onCompletions.clear();
        onCompletions = null;
    }
}
Also used : Synchronization(org.apache.camel.spi.Synchronization)

Example 8 with Synchronization

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

the class IdempotentConsumer method process.

public boolean process(final Exchange exchange, final AsyncCallback callback) {
    final AsyncCallback target;
    final String messageId;
    try {
        messageId = messageIdExpression.evaluate(exchange, String.class);
        if (messageId == null) {
            exchange.setException(new NoMessageIdException(exchange, messageIdExpression));
            callback.done(true);
            return true;
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    try {
        boolean newKey;
        if (eager) {
            // add the key to the repository
            if (idempotentRepository instanceof ExchangeIdempotentRepository) {
                newKey = ((ExchangeIdempotentRepository<String>) idempotentRepository).add(exchange, messageId);
            } else {
                newKey = idempotentRepository.add(messageId);
            }
        } else {
            // check if we already have the key
            if (idempotentRepository instanceof ExchangeIdempotentRepository) {
                newKey = !((ExchangeIdempotentRepository<String>) idempotentRepository).contains(exchange, messageId);
            } else {
                newKey = !idempotentRepository.contains(messageId);
            }
        }
        if (!newKey) {
            // mark the exchange as duplicate
            exchange.setProperty(Exchange.DUPLICATE_MESSAGE, Boolean.TRUE);
            // we already have this key so its a duplicate message
            onDuplicate(exchange, messageId);
            if (skipDuplicate) {
                // if we should skip duplicate then we are done
                LOG.debug("Ignoring duplicate message with id: {} for exchange: {}", messageId, exchange);
                callback.done(true);
                return true;
            }
        }
        final Synchronization onCompletion = new IdempotentOnCompletion(idempotentRepository, messageId, eager, removeOnFailure);
        target = new IdempotentConsumerCallback(exchange, onCompletion, callback, completionEager);
        if (!completionEager) {
            // the scope is to do the idempotent completion work as an unit of work on the exchange when its done being routed
            exchange.addOnCompletion(onCompletion);
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // process the exchange
    return processor.process(exchange, target);
}
Also used : AsyncCallback(org.apache.camel.AsyncCallback) Synchronization(org.apache.camel.spi.Synchronization) ExchangeIdempotentRepository(org.apache.camel.spi.ExchangeIdempotentRepository)

Example 9 with Synchronization

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

the class UnitOfWorkHelper method afterRouteSynchronizations.

public static void afterRouteSynchronizations(Route route, Exchange exchange, List<Synchronization> synchronizations, Logger log) {
    if (synchronizations != null && !synchronizations.isEmpty()) {
        // work on a copy of the list to avoid any modification which may cause ConcurrentModificationException
        List<Synchronization> copy = new ArrayList<Synchronization>(synchronizations);
        // reverse so we invoke it FILO style instead of FIFO
        Collections.reverse(copy);
        // and honor if any was ordered by sorting it accordingly
        copy.sort(new OrderedComparator());
        // invoke synchronization callbacks
        for (Synchronization synchronization : copy) {
            if (synchronization instanceof SynchronizationRouteAware) {
                try {
                    log.trace("Invoking synchronization.onAfterRoute: {} with {}", synchronization, exchange);
                    ((SynchronizationRouteAware) synchronization).onAfterRoute(route, exchange);
                } catch (Throwable e) {
                    // must catch exceptions to ensure all synchronizations have a chance to run
                    log.warn("Exception occurred during onAfterRoute. This exception will be ignored.", e);
                }
            }
        }
    }
}
Also used : SynchronizationRouteAware(org.apache.camel.spi.SynchronizationRouteAware) ArrayList(java.util.ArrayList) Synchronization(org.apache.camel.spi.Synchronization)

Example 10 with Synchronization

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

the class CamelReactiveStreamsServiceImpl method doRequest.

protected Publisher<Exchange> doRequest(String name, Exchange data) {
    ReactiveStreamsConsumer consumer = streamSubscriber(name).getConsumer();
    if (consumer == null) {
        throw new IllegalStateException("No consumers attached to the stream " + name);
    }
    DelayedMonoPublisher<Exchange> publisher = new DelayedMonoPublisher<>(this.workerPool);
    data.addOnCompletion(new Synchronization() {

        @Override
        public void onComplete(Exchange exchange) {
            publisher.setData(exchange);
        }

        @Override
        public void onFailure(Exchange exchange) {
            Throwable throwable = exchange.getException();
            if (throwable == null) {
                throwable = new IllegalStateException("Unknown Exception");
            }
            publisher.setException(throwable);
        }
    });
    consumer.process(data, doneSync -> {
    });
    return publisher;
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) ReactiveStreamsConsumer(org.apache.camel.component.reactive.streams.ReactiveStreamsConsumer) Synchronization(org.apache.camel.spi.Synchronization)

Aggregations

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