Search in sources :

Example 11 with Synchronization

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

the class DefaultUnitOfWork method handoverSynchronization.

@Override
public void handoverSynchronization(Exchange target, Predicate<Synchronization> filter) {
    if (synchronizations == null || synchronizations.isEmpty()) {
        return;
    }
    Iterator<Synchronization> it = synchronizations.iterator();
    while (it.hasNext()) {
        Synchronization synchronization = it.next();
        boolean handover = true;
        if (synchronization instanceof SynchronizationVetoable) {
            SynchronizationVetoable veto = (SynchronizationVetoable) synchronization;
            handover = veto.allowHandover();
        }
        if (handover && (filter == null || filter.test(synchronization))) {
            log.trace("Handover synchronization {} to: {}", synchronization, target);
            target.addOnCompletion(synchronization);
            // remove it if its handed over
            it.remove();
        } else {
            log.trace("Handover not allow for synchronization {}", synchronization);
        }
    }
}
Also used : SynchronizationVetoable(org.apache.camel.spi.SynchronizationVetoable) Synchronization(org.apache.camel.spi.Synchronization)

Example 12 with Synchronization

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

the class UnitOfWorkHelper method beforeRouteSynchronizations.

public static void beforeRouteSynchronizations(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.onBeforeRoute: {} with {}", synchronization, exchange);
                    ((SynchronizationRouteAware) synchronization).onBeforeRoute(route, exchange);
                } catch (Throwable e) {
                    // must catch exceptions to ensure all synchronizations have a chance to run
                    log.warn("Exception occurred during onBeforeRoute. 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 13 with Synchronization

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

the class UnitOfWorkHelper method doneSynchronizations.

public static void doneSynchronizations(Exchange exchange, List<Synchronization> synchronizations, Logger log) {
    boolean failed = exchange.isFailed();
    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) {
            try {
                if (failed) {
                    log.trace("Invoking synchronization.onFailure: {} with {}", synchronization, exchange);
                    synchronization.onFailure(exchange);
                } else {
                    log.trace("Invoking synchronization.onComplete: {} with {}", synchronization, exchange);
                    synchronization.onComplete(exchange);
                }
            } catch (Throwable e) {
                // must catch exceptions to ensure all synchronizations have a chance to run
                log.warn("Exception occurred during onCompletion. This exception will be ignored.", e);
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Synchronization(org.apache.camel.spi.Synchronization)

Example 14 with Synchronization

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

the class UnitOfWorkTest method setUp.

@Override
protected void setUp() throws Exception {
    synchronization = new Synchronization() {

        public void onComplete(Exchange exchange) {
            completed = exchange;
            foo = exchange.getIn().getHeader("foo");
            doneLatch.countDown();
        }

        public void onFailure(Exchange exchange) {
            failed = exchange;
            baz = exchange.getIn().getHeader("baz");
            doneLatch.countDown();
        }
    };
    super.setUp();
}
Also used : Exchange(org.apache.camel.Exchange) Synchronization(org.apache.camel.spi.Synchronization)

Example 15 with Synchronization

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

the class SqsConsumer 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;
        // schedule task to extend visibility if enabled
        Integer visibilityTimeout = getConfiguration().getVisibilityTimeout();
        if (this.scheduledExecutor != null && visibilityTimeout != null && (visibilityTimeout.intValue() / 2) > 0) {
            int delay = visibilityTimeout.intValue() / 2;
            int period = visibilityTimeout.intValue();
            int repeatSeconds = new Double(visibilityTimeout.doubleValue() * 1.5).intValue();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Scheduled TimeoutExtender task to start after {} delay, and run with {}/{} period/repeat (seconds), to extend exchangeId: {}", new Object[] { delay, period, repeatSeconds, exchange.getExchangeId() });
            }
            final ScheduledFuture<?> scheduledFuture = this.scheduledExecutor.scheduleAtFixedRate(new TimeoutExtender(exchange, repeatSeconds), delay, period, TimeUnit.SECONDS);
            exchange.addOnCompletion(new Synchronization() {

                @Override
                public void onComplete(Exchange exchange) {
                    cancelExtender(exchange);
                }

                @Override
                public void onFailure(Exchange exchange) {
                    cancelExtender(exchange);
                }

                private void cancelExtender(Exchange exchange) {
                    // cancel task as we are done
                    LOG.trace("Processing done so cancelling TimeoutExtender task for exchangeId: {}", exchange.getExchangeId());
                    scheduledFuture.cancel(true);
                }
            });
        }
        // 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 "SqsConsumerOnCompletion";
            }
        });
        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)

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