Search in sources :

Example 56 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project crate by crate.

the class TransportJobAction method nodeOperation.

@Override
public void nodeOperation(final JobRequest request, final ActionListener<JobResponse> actionListener) {
    JobExecutionContext.Builder contextBuilder = jobContextService.newBuilder(request.jobId(), request.coordinatorNodeId());
    SharedShardContexts sharedShardContexts = new SharedShardContexts(indicesService);
    List<CompletableFuture<Bucket>> directResponseFutures = contextPreparer.prepareOnRemote(request.nodeOperations(), contextBuilder, sharedShardContexts);
    try {
        JobExecutionContext context = jobContextService.createContext(contextBuilder);
        context.start();
    } catch (Throwable t) {
        actionListener.onFailure(t);
        return;
    }
    if (directResponseFutures.size() == 0) {
        actionListener.onResponse(new JobResponse());
    } else {
        CompletableFutures.allAsList(directResponseFutures).whenComplete((buckets, t) -> {
            if (t == null) {
                actionListener.onResponse(new JobResponse(buckets));
            } else {
                actionListener.onFailure(SQLExceptions.unwrap(t));
            }
        });
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) JobExecutionContext(io.crate.jobs.JobExecutionContext)

Example 57 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project PayFile by mikehearn.

the class ConnectServerController method maybeSettleLastServer.

/**
     * Possibly reconnect to the last paid server and ask it to give us back the money. Note that after 24 hours this
     * channel will expire anyway, so if the server is gone, it's not the end of the world, we'll still get the money
     * back. The returned future completes immediately if nothing needs to be done.
     */
private CompletableFuture<Void> maybeSettleLastServer(HostAndPort newServerName) {
    final HostAndPort lastPaidServer = Settings.getLastPaidServer();
    // If we didn't have a payment channel, or we did but it's with the same server we're connecting to, ignore.
    if (lastPaidServer == null || newServerName.equals(lastPaidServer))
        return CompletableFuture.completedFuture(null);
    BigInteger amountInLastServer = PayFileClient.getBalanceForServer(lastPaidServer.getHostText(), lastPaidServer.getPort(), Main.bitcoin.wallet());
    // If the last server we paid was already settled, ignore.
    if (amountInLastServer.compareTo(BigInteger.ZERO) == 0)
        return CompletableFuture.completedFuture(null);
    // Otherwise we have some money locked up with the last server. Ask for it back.
    final CompletableFuture<Void> future = new CompletableFuture<>();
    titleLabel.setText(String.format("Contacting %s to request early settlement ...", lastPaidServer));
    log.info("Connecting to {}", lastPaidServer);
    Main.connect(lastPaidServer, REFUND_CONNECT_TIMEOUT_MSEC).whenCompleteAsync((client, ex) -> {
        if (ex == null) {
            log.info("Connected. Requesting early settlement.");
            titleLabel.setText("Requesting early settlement ...");
            client.settlePaymentChannel().whenCompleteAsync((v, settleEx) -> {
                if (settleEx == null) {
                    log.info("Settled. Proceeding ...");
                    client.disconnect();
                    future.complete(null);
                } else {
                    crashAlert(settleEx);
                }
            }, Platform::runLater);
        } else {
            log.error("Failed to connect", ex);
            titleLabel.setText(defaultTitle);
            informUserTheyMustWait(lastPaidServer);
        }
    }, Platform::runLater);
    return future;
}
Also used : HostAndPort(com.google.common.net.HostAndPort) CompletableFuture(java.util.concurrent.CompletableFuture) Platform(javafx.application.Platform) BigInteger(java.math.BigInteger)

Example 58 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project failsafe by jhalterman.

the class Java8Example method main.

@SuppressWarnings("unused")
public static void main(String... args) {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    RetryPolicy retryPolicy = new RetryPolicy();
    // Create a retryable functional interface
    Function<String, String> bar = value -> Failsafe.with(retryPolicy).get(() -> value + "bar");
    // Create a retryable runnable Stream
    Failsafe.with(retryPolicy).run(() -> Stream.of("foo").map(value -> value + "bar").forEach(System.out::println));
    // Create a retryable callable Stream
    Failsafe.with(retryPolicy).get(() -> Stream.of("foo").map(value -> Failsafe.with(retryPolicy).get(() -> value + "bar")).collect(Collectors.toList()));
    // Create a individual retryable Stream operation
    Stream.of("foo").map(value -> Failsafe.with(retryPolicy).get(() -> value + "bar")).forEach(System.out::println);
    // Create a retryable CompletableFuture
    Failsafe.with(retryPolicy).with(executor).future(() -> CompletableFuture.supplyAsync(() -> "foo").thenApplyAsync(value -> value + "bar").thenAccept(System.out::println));
    // Create an individual retryable CompletableFuture stages
    CompletableFuture.supplyAsync(() -> Failsafe.with(retryPolicy).get(() -> "foo")).thenApplyAsync(value -> Failsafe.with(retryPolicy).get(() -> value + "bar")).thenAccept(System.out::println);
}
Also used : Stream(java.util.stream.Stream) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) CompletableFuture(java.util.concurrent.CompletableFuture) RetryPolicy(net.jodah.failsafe.RetryPolicy) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Failsafe(net.jodah.failsafe.Failsafe) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RetryPolicy(net.jodah.failsafe.RetryPolicy)

Example 59 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project jersey by jersey.

the class BasicClientTest method testAsyncClientInvocation.

@Test
public void testAsyncClientInvocation() throws InterruptedException, ExecutionException {
    final WebTarget resource = target().path("resource");
    Future<Response> f1 = resource.request().async().post(text("post1"));
    final Response response = f1.get();
    assertEquals("post1", response.readEntity(String.class));
    Future<String> f2 = resource.request().async().post(text("post2"), String.class);
    assertEquals("post2", f2.get());
    Future<List<JaxbString>> f3 = resource.request().async().get(new GenericType<List<JaxbString>>() {
    });
    assertEquals(Arrays.asList("a", "b", "c").toString(), f3.get().stream().map(input -> input.value).collect(Collectors.toList()).toString());
    CompletableFuture<String> future1 = new CompletableFuture<>();
    final TestCallback<Response> c1 = new TestCallback<Response>(future1) {

        @Override
        protected String process(Response result) {
            return result.readEntity(String.class);
        }
    };
    resource.request().async().post(text("post"), c1);
    assertEquals("post", future1.get());
    CompletableFuture<String> future2 = new CompletableFuture<>();
    final TestCallback<String> c2 = new TestCallback<String>(future2) {

        @Override
        protected String process(String result) {
            return result;
        }
    };
    resource.request().async().post(text("post"), c2);
    assertEquals("post", future2.get());
    CompletableFuture<String> future3 = new CompletableFuture<>();
    final TestCallback<List<JaxbString>> c3 = new TestCallback<List<JaxbString>>(future3) {

        @Override
        protected String process(List<JaxbString> result) {
            return result.stream().map(jaxbString -> jaxbString.value).collect(Collectors.toList()).toString();
        }
    };
    resource.request().async().get(c3);
    assertEquals(Arrays.asList("a", "b", "c").toString(), future3.get());
}
Also used : Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ClientConfig(org.glassfish.jersey.client.ClientConfig) Assert.assertNotSame(org.junit.Assert.assertNotSame) Path(javax.ws.rs.Path) Client(javax.ws.rs.client.Client) CompletableFuture(java.util.concurrent.CompletableFuture) Application(javax.ws.rs.core.Application) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) AsyncInvoker(javax.ws.rs.client.AsyncInvoker) ClientBuilder(javax.ws.rs.client.ClientBuilder) Future(java.util.concurrent.Future) MediaType(javax.ws.rs.core.MediaType) JerseyTest(org.glassfish.jersey.test.JerseyTest) InvocationCallback(javax.ws.rs.client.InvocationCallback) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) Assert.fail(org.junit.Assert.fail) WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) POST(javax.ws.rs.POST) ClientRequestContext(javax.ws.rs.client.ClientRequestContext) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Invocation(javax.ws.rs.client.Invocation) ThreadPoolExecutorProvider(org.glassfish.jersey.spi.ThreadPoolExecutorProvider) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) Collectors(java.util.stream.Collectors) Entity.text(javax.ws.rs.client.Entity.text) NotFoundException(javax.ws.rs.NotFoundException) ExecutionException(java.util.concurrent.ExecutionException) GenericType(javax.ws.rs.core.GenericType) List(java.util.List) WriterInterceptorContext(javax.ws.rs.ext.WriterInterceptorContext) Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) WebTarget(javax.ws.rs.client.WebTarget) ClientAsyncExecutor(org.glassfish.jersey.client.ClientAsyncExecutor) Assert.assertEquals(org.junit.Assert.assertEquals) Response(javax.ws.rs.core.Response) CompletableFuture(java.util.concurrent.CompletableFuture) List(java.util.List) WebTarget(javax.ws.rs.client.WebTarget) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 60 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project jersey by jersey.

the class LoopBackConnector method apply.

@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
    CompletableFuture<ClientResponse> future = new CompletableFuture<>();
    try {
        ClientResponse response = _apply(request);
        callback.response(response);
        future.complete(response);
    } catch (final Throwable t) {
        callback.failure(t);
        future.completeExceptionally(t);
    }
    return future;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) CompletableFuture(java.util.concurrent.CompletableFuture)

Aggregations

CompletableFuture (java.util.concurrent.CompletableFuture)490 Test (org.junit.Test)152 ArrayList (java.util.ArrayList)88 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)77 List (java.util.List)75 UUID (java.util.UUID)62 Futures (io.pravega.common.concurrent.Futures)60 Map (java.util.Map)59 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)57 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)53 HashMap (java.util.HashMap)52 TimeUnit (java.util.concurrent.TimeUnit)52 Cleanup (lombok.Cleanup)49 Exceptions (io.pravega.common.Exceptions)48 Collectors (java.util.stream.Collectors)48 lombok.val (lombok.val)47 IOException (java.io.IOException)46 Duration (java.time.Duration)46 Slf4j (lombok.extern.slf4j.Slf4j)46 AtomicReference (java.util.concurrent.atomic.AtomicReference)45