Search in sources :

Example 1 with ListenableFutureCallback

use of org.springframework.util.concurrent.ListenableFutureCallback in project spring-integration-samples by spring-projects.

the class ListenableFutureTest method testAsyncGateway.

@Test
public void testAsyncGateway() throws Exception {
    Random random = new Random();
    int[] numbers = new int[100];
    int expectedResults = 0;
    for (int i = 0; i < 100; i++) {
        numbers[i] = random.nextInt(200);
        if (numbers[i] > 100) {
            expectedResults++;
        }
    }
    final CountDownLatch latch = new CountDownLatch(expectedResults);
    final AtomicInteger failures = new AtomicInteger();
    for (int i = 0; i < 100; i++) {
        final int number = numbers[i];
        ListenableFuture<Integer> result = gateway.multiplyByTwo(number);
        ListenableFutureCallback<Integer> callback = new ListenableFutureCallback<Integer>() {

            @Override
            public void onSuccess(Integer result) {
                logger.info("Result of multiplication of " + number + " by 2 is " + result);
                latch.countDown();
            }

            @Override
            public void onFailure(Throwable t) {
                failures.incrementAndGet();
                logger.error("Unexpected exception for " + number, t);
                latch.countDown();
            }
        };
        result.addCallback(callback);
    }
    assertTrue(latch.await(60, TimeUnit.SECONDS));
    assertEquals(0, failures.get());
    logger.info("Finished");
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ListenableFutureCallback(org.springframework.util.concurrent.ListenableFutureCallback) CountDownLatch(java.util.concurrent.CountDownLatch) MessageEndpoint(org.springframework.integration.annotation.MessageEndpoint) Test(org.junit.Test)

Example 2 with ListenableFutureCallback

use of org.springframework.util.concurrent.ListenableFutureCallback in project dhis2-core by dhis2.

the class FileResourceUploadCallback method newInstance.

public ListenableFutureCallback<String> newInstance(String fileResourceUid) {
    return new ListenableFutureCallback<String>() {

        DateTime startTime = DateTime.now();

        @Override
        public void onFailure(Throwable ex) {
            log.error("Saving content for file resource '" + fileResourceUid + "' failed", ex);
            FileResource fileResource = idObjectManager.get(FileResource.class, fileResourceUid);
            if (fileResource != null) {
                log.info("File resource '" + fileResource.getUid() + "' storageStatus set to FAILED.");
                fileResource.setStorageStatus(FileResourceStorageStatus.FAILED);
                idObjectManager.update(fileResource);
            }
        }

        @Override
        public void onSuccess(String result) {
            Period timeDiff = new Period(startTime, DateTime.now());
            log.info("File stored with key: '" + result + "'. Upload finished in " + timeDiff.toString(PeriodFormat.getDefault()));
            FileResource fileResource = idObjectManager.get(FileResource.class, fileResourceUid);
            if (result != null && fileResource != null) {
                fileResource.setStorageStatus(FileResourceStorageStatus.STORED);
                idObjectManager.update(fileResource);
            } else {
                log.error("Conflict: content was stored but FileResource with uid '" + fileResourceUid + "' could not be found.");
            }
        }
    };
}
Also used : ListenableFutureCallback(org.springframework.util.concurrent.ListenableFutureCallback) Period(org.joda.time.Period) DateTime(org.joda.time.DateTime)

Example 3 with ListenableFutureCallback

use of org.springframework.util.concurrent.ListenableFutureCallback in project spring-integration by spring-projects.

the class AbstractMessageProducingHandler method produceOutput.

protected void produceOutput(Object reply, final Message<?> requestMessage) {
    final MessageHeaders requestHeaders = requestMessage.getHeaders();
    Object replyChannel = null;
    if (getOutputChannel() == null) {
        Map<?, ?> routingSlipHeader = requestHeaders.get(IntegrationMessageHeaderAccessor.ROUTING_SLIP, Map.class);
        if (routingSlipHeader != null) {
            Assert.isTrue(routingSlipHeader.size() == 1, "The RoutingSlip header value must be a SingletonMap");
            Object key = routingSlipHeader.keySet().iterator().next();
            Object value = routingSlipHeader.values().iterator().next();
            Assert.isInstanceOf(List.class, key, "The RoutingSlip key must be List");
            Assert.isInstanceOf(Integer.class, value, "The RoutingSlip value must be Integer");
            List<?> routingSlip = (List<?>) key;
            AtomicInteger routingSlipIndex = new AtomicInteger((Integer) value);
            replyChannel = getOutputChannelFromRoutingSlip(reply, requestMessage, routingSlip, routingSlipIndex);
            if (replyChannel != null) {
                // TODO Migrate to the SF MessageBuilder
                AbstractIntegrationMessageBuilder<?> builder = null;
                if (reply instanceof Message) {
                    builder = this.getMessageBuilderFactory().fromMessage((Message<?>) reply);
                } else if (reply instanceof AbstractIntegrationMessageBuilder) {
                    builder = (AbstractIntegrationMessageBuilder<?>) reply;
                } else {
                    builder = this.getMessageBuilderFactory().withPayload(reply);
                }
                builder.setHeader(IntegrationMessageHeaderAccessor.ROUTING_SLIP, Collections.singletonMap(routingSlip, routingSlipIndex.get()));
                reply = builder;
            }
        }
        if (replyChannel == null) {
            replyChannel = requestHeaders.getReplyChannel();
            if (replyChannel == null && reply instanceof Message) {
                replyChannel = ((Message<?>) reply).getHeaders().getReplyChannel();
            }
        }
    }
    if (this.async && (reply instanceof ListenableFuture<?> || reply instanceof Publisher<?>)) {
        if (reply instanceof ListenableFuture<?> || !(getOutputChannel() instanceof ReactiveStreamsSubscribableChannel)) {
            ListenableFuture<?> future;
            if (reply instanceof ListenableFuture<?>) {
                future = (ListenableFuture<?>) reply;
            } else {
                SettableListenableFuture<Object> settableListenableFuture = new SettableListenableFuture<>();
                Mono.from((Publisher<?>) reply).subscribe(settableListenableFuture::set, settableListenableFuture::setException);
                future = settableListenableFuture;
            }
            Object theReplyChannel = replyChannel;
            future.addCallback(new ListenableFutureCallback<Object>() {

                @Override
                public void onSuccess(Object result) {
                    Message<?> replyMessage = null;
                    try {
                        replyMessage = createOutputMessage(result, requestHeaders);
                        sendOutput(replyMessage, theReplyChannel, false);
                    } catch (Exception e) {
                        Exception exceptionToLogAndSend = e;
                        if (!(e instanceof MessagingException)) {
                            exceptionToLogAndSend = new MessageHandlingException(requestMessage, e);
                            if (replyMessage != null) {
                                exceptionToLogAndSend = new MessagingException(replyMessage, exceptionToLogAndSend);
                            }
                        }
                        logger.error("Failed to send async reply: " + result.toString(), exceptionToLogAndSend);
                        onFailure(exceptionToLogAndSend);
                    }
                }

                @Override
                public void onFailure(Throwable ex) {
                    sendErrorMessage(requestMessage, ex);
                }
            });
        } else {
            ((ReactiveStreamsSubscribableChannel) getOutputChannel()).subscribeTo(Flux.from((Publisher<?>) reply).map(result -> createOutputMessage(result, requestHeaders)));
        }
    } else {
        sendOutput(createOutputMessage(reply, requestHeaders), replyChannel, false);
    }
}
Also used : MessagingException(org.springframework.messaging.MessagingException) Arrays(java.util.Arrays) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) HashMap(java.util.HashMap) ErrorMessage(org.springframework.messaging.support.ErrorMessage) ListenableFutureCallback(org.springframework.util.concurrent.ListenableFutureCallback) MessagingTemplate(org.springframework.integration.core.MessagingTemplate) HashSet(java.util.HashSet) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Map(java.util.Map) IntegrationMessageHeaderAccessor(org.springframework.integration.IntegrationMessageHeaderAccessor) RoutingSlipRouteStrategy(org.springframework.integration.routingslip.RoutingSlipRouteStrategy) Message(org.springframework.messaging.Message) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) Collection(java.util.Collection) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) PatternMatchUtils(org.springframework.util.PatternMatchUtils) Set(java.util.Set) Mono(reactor.core.publisher.Mono) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) DestinationResolutionException(org.springframework.messaging.core.DestinationResolutionException) MessageProducer(org.springframework.integration.core.MessageProducer) MessageChannel(org.springframework.messaging.MessageChannel) MessageHeaders(org.springframework.messaging.MessageHeaders) Flux(reactor.core.publisher.Flux) List(java.util.List) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) MessagingException(org.springframework.messaging.MessagingException) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) Publisher(org.reactivestreams.Publisher) MessagingException(org.springframework.messaging.MessagingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) DestinationResolutionException(org.springframework.messaging.core.DestinationResolutionException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) List(java.util.List) MessageHeaders(org.springframework.messaging.MessageHeaders)

Aggregations

ListenableFutureCallback (org.springframework.util.concurrent.ListenableFutureCallback)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Random (java.util.Random)1 Set (java.util.Set)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 DateTime (org.joda.time.DateTime)1 Period (org.joda.time.Period)1 Test (org.junit.Test)1 Publisher (org.reactivestreams.Publisher)1 IntegrationMessageHeaderAccessor (org.springframework.integration.IntegrationMessageHeaderAccessor)1 MessageEndpoint (org.springframework.integration.annotation.MessageEndpoint)1 ReactiveStreamsSubscribableChannel (org.springframework.integration.channel.ReactiveStreamsSubscribableChannel)1 MessageProducer (org.springframework.integration.core.MessageProducer)1