Search in sources :

Example 11 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-cloud-gcp by spring-cloud.

the class PubSubSubscriberTemplate method doBatchedAsyncOperation.

/**
 * Perform Pub/Sub operations (ack/nack/modifyAckDeadline) in per-subscription batches.
 * <p>The returned {@link ListenableFuture} will complete when either all batches completes successfully or when at
 * least one fails.</p>
 * <p>
 * In case of multiple batch failures, which exception will be in the final {@link ListenableFuture} is
 * non-deterministic.
 * </p>
 * @param acknowledgeablePubsubMessages messages, could be from different subscriptions.
 * @param asyncOperation specific Pub/Sub operation to perform.
 * @return {@link ListenableFuture} indicating overall success or failure.
 */
private ListenableFuture<Void> doBatchedAsyncOperation(Collection<? extends AcknowledgeablePubsubMessage> acknowledgeablePubsubMessages, BiFunction<String, List<String>, ApiFuture<Empty>> asyncOperation) {
    Map<ProjectSubscriptionName, List<String>> groupedMessages = acknowledgeablePubsubMessages.stream().collect(Collectors.groupingBy(AcknowledgeablePubsubMessage::getProjectSubscriptionName, Collectors.mapping(AcknowledgeablePubsubMessage::getAckId, Collectors.toList())));
    Assert.state(groupedMessages.keySet().stream().map(ProjectSubscriptionName::getProject).distinct().count() == 1, "The project id of all messages must match.");
    SettableListenableFuture<Void> settableListenableFuture = new SettableListenableFuture<>();
    int numExpectedFutures = groupedMessages.size();
    AtomicInteger numCompletedFutures = new AtomicInteger();
    groupedMessages.forEach((ProjectSubscriptionName psName, List<String> ackIds) -> {
        ApiFuture<Empty> ackApiFuture = asyncOperation.apply(psName.toString(), ackIds);
        ApiFutures.addCallback(ackApiFuture, new ApiFutureCallback<Empty>() {

            @Override
            public void onFailure(Throwable throwable) {
                processResult(throwable);
            }

            @Override
            public void onSuccess(Empty empty) {
                processResult(null);
            }

            private void processResult(Throwable throwable) {
                if (throwable != null) {
                    settableListenableFuture.setException(throwable);
                } else if (numCompletedFutures.incrementAndGet() == numExpectedFutures) {
                    settableListenableFuture.set(null);
                }
            }
        }, this.ackExecutor);
    });
    return settableListenableFuture;
}
Also used : ProjectSubscriptionName(com.google.pubsub.v1.ProjectSubscriptionName) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) BasicAcknowledgeablePubsubMessage(org.springframework.cloud.gcp.pubsub.support.BasicAcknowledgeablePubsubMessage) ConvertedAcknowledgeablePubsubMessage(org.springframework.cloud.gcp.pubsub.support.converter.ConvertedAcknowledgeablePubsubMessage) AcknowledgeablePubsubMessage(org.springframework.cloud.gcp.pubsub.support.AcknowledgeablePubsubMessage) ConvertedBasicAcknowledgeablePubsubMessage(org.springframework.cloud.gcp.pubsub.support.converter.ConvertedBasicAcknowledgeablePubsubMessage) Empty(com.google.protobuf.Empty) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) List(java.util.List)

Example 12 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-cloud-gcp by spring-cloud.

the class PubSubSubscriberTemplate method pullAndAckAsync.

@Override
public ListenableFuture<List<PubsubMessage>> pullAndAckAsync(String subscription, Integer maxMessages, Boolean returnImmediately) {
    PullRequest pullRequest = this.subscriberFactory.createPullRequest(subscription, maxMessages, returnImmediately);
    final SettableListenableFuture<List<PubsubMessage>> settableFuture = new SettableListenableFuture<>();
    this.pullAsync(pullRequest).addCallback(ackableMessages -> {
        if (!ackableMessages.isEmpty()) {
            ack(ackableMessages);
        }
        List<PubsubMessage> messages = ackableMessages.stream().map(AcknowledgeablePubsubMessage::getPubsubMessage).collect(Collectors.toList());
        settableFuture.set(messages);
    }, settableFuture::setException);
    return settableFuture;
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) PullRequest(com.google.pubsub.v1.PullRequest) List(java.util.List) BasicAcknowledgeablePubsubMessage(org.springframework.cloud.gcp.pubsub.support.BasicAcknowledgeablePubsubMessage) PubsubMessage(com.google.pubsub.v1.PubsubMessage) ConvertedAcknowledgeablePubsubMessage(org.springframework.cloud.gcp.pubsub.support.converter.ConvertedAcknowledgeablePubsubMessage) AcknowledgeablePubsubMessage(org.springframework.cloud.gcp.pubsub.support.AcknowledgeablePubsubMessage) ConvertedBasicAcknowledgeablePubsubMessage(org.springframework.cloud.gcp.pubsub.support.converter.ConvertedBasicAcknowledgeablePubsubMessage)

Example 13 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-boot-admin by codecentric.

the class StatusUpdateApplicationListenerTest method test_newApplication.

@Test
public void test_newApplication() throws Exception {
    StatusUpdater statusUpdater = mock(StatusUpdater.class);
    ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class);
    when(scheduler.submit(any(Runnable.class))).then(new Answer<Future<?>>() {

        @Override
        public Future<?> answer(InvocationOnMock invocation) throws Throwable {
            invocation.getArgumentAt(0, Runnable.class).run();
            SettableListenableFuture<?> future = new SettableListenableFuture<Void>();
            future.set(null);
            return future;
        }
    });
    StatusUpdateApplicationListener listener = new StatusUpdateApplicationListener(statusUpdater, scheduler);
    Application application = Application.create("test").withHealthUrl("http://example.com").build();
    listener.onClientApplicationRegistered(new ClientApplicationRegisteredEvent(application));
    verify(statusUpdater).updateStatus(eq(application));
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) ClientApplicationRegisteredEvent(de.codecentric.boot.admin.event.ClientApplicationRegisteredEvent) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ScheduledFuture(java.util.concurrent.ScheduledFuture) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) Future(java.util.concurrent.Future) SpringApplication(org.springframework.boot.SpringApplication) Application(de.codecentric.boot.admin.model.Application) Test(org.junit.Test)

Example 14 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-framework by spring-projects.

the class ReactorNettyTcpClient method shutdown.

@Override
public ListenableFuture<Void> shutdown() {
    if (this.stopping) {
        SettableListenableFuture<Void> future = new SettableListenableFuture<>();
        future.set(null);
        return future;
    }
    this.stopping = true;
    ChannelGroupFuture close = this.channelGroup.close();
    Mono<Void> completion = FutureMono.from(close).doAfterTerminate((x, e) -> {
        // TODO: https://github.com/reactor/reactor-netty/issues/24
        shutdownGlobalResources();
        this.loopResources.dispose();
        this.poolResources.dispose();
        // TODO: https://github.com/reactor/reactor-netty/issues/25
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        // Scheduler after loop resources...
        this.scheduler.dispose();
    });
    return new MonoToListenableFutureAdapter<>(completion);
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture)

Example 15 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-framework by spring-projects.

the class Netty4ClientHttpRequest method executeInternal.

@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(final HttpHeaders headers) throws IOException {
    final SettableListenableFuture<ClientHttpResponse> responseFuture = new SettableListenableFuture<>();
    ChannelFutureListener connectionListener = new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                Channel channel = future.channel();
                channel.pipeline().addLast(new RequestExecuteHandler(responseFuture));
                FullHttpRequest nettyRequest = createFullHttpRequest(headers);
                channel.writeAndFlush(nettyRequest);
            } else {
                responseFuture.setException(future.cause());
            }
        }
    };
    this.bootstrap.connect(this.uri.getHost(), getPort(this.uri)).addListener(connectionListener);
    return responseFuture;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Channel(io.netty.channel.Channel) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Aggregations

SettableListenableFuture (org.springframework.util.concurrent.SettableListenableFuture)24 Test (org.junit.Test)8 List (java.util.List)3 BeanFactory (org.springframework.beans.factory.BeanFactory)3 MessagingException (org.springframework.messaging.MessagingException)3 PubsubMessage (com.google.pubsub.v1.PubsubMessage)2 URI (java.net.URI)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Transformer (javax.xml.transform.Transformer)2 TransformerFactory (javax.xml.transform.TransformerFactory)2 Log (org.apache.commons.logging.Log)2 AcknowledgeablePubsubMessage (org.springframework.cloud.gcp.pubsub.support.AcknowledgeablePubsubMessage)2 BasicAcknowledgeablePubsubMessage (org.springframework.cloud.gcp.pubsub.support.BasicAcknowledgeablePubsubMessage)2 ConvertedAcknowledgeablePubsubMessage (org.springframework.cloud.gcp.pubsub.support.converter.ConvertedAcknowledgeablePubsubMessage)2 ConvertedBasicAcknowledgeablePubsubMessage (org.springframework.cloud.gcp.pubsub.support.converter.ConvertedBasicAcknowledgeablePubsubMessage)2 MethodParameter (org.springframework.core.MethodParameter)2 Message (org.springframework.messaging.Message)2 MessageHandlingException (org.springframework.messaging.MessageHandlingException)2 ErrorMessage (org.springframework.messaging.support.ErrorMessage)2