Example usage for java.util.concurrent CompletableFuture CompletableFuture

List of usage examples for java.util.concurrent CompletableFuture CompletableFuture

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture CompletableFuture.

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

From source file:org.pentaho.di.ui.repo.controller.RepositoryConnectController.java

public String browse() {
    Spoon spoon = spoonSupplier.get();//from w w  w.  j  av  a  2s.c o m
    CompletableFuture<String> name = new CompletableFuture<>();
    Runnable execute = () -> {
        DirectoryDialog directoryDialog = new DirectoryDialog(spoonSupplier.get().getShell());
        name.complete(directoryDialog.open());
    };
    if (spoon.getShell() != null) {
        spoon.getShell().getDisplay().asyncExec(execute);
    } else {
        execute.run();
    }
    try {
        return name.get();
    } catch (Exception e) {
        return "/";
    }
}

From source file:org.apache.pulsar.functions.runtime.ProcessRuntime.java

@Override
public CompletableFuture<FunctionStatus> getFunctionStatus(int instanceId) {
    CompletableFuture<FunctionStatus> retval = new CompletableFuture<>();
    if (stub == null) {
        retval.completeExceptionally(new RuntimeException("Not alive"));
        return retval;
    }/* www  . j  a  v a 2 s.com*/
    ListenableFuture<FunctionStatus> response = stub.withDeadlineAfter(GRPC_TIMEOUT_SECS, TimeUnit.SECONDS)
            .getFunctionStatus(Empty.newBuilder().build());
    Futures.addCallback(response, new FutureCallback<FunctionStatus>() {
        @Override
        public void onFailure(Throwable throwable) {
            FunctionStatus.Builder builder = FunctionStatus.newBuilder();
            builder.setRunning(false);
            if (deathException != null) {
                builder.setFailureException(deathException.getMessage());
            } else {
                builder.setFailureException(throwable.getMessage());
            }
            retval.complete(builder.build());
        }

        @Override
        public void onSuccess(InstanceCommunication.FunctionStatus t) {
            retval.complete(t);
        }
    });
    return retval;
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

@Override
public CompletableFuture<String> registerTypeMapping(String name, String schema, String... keywords) {
    CompletableFuture<String> future = new CompletableFuture<>();
    if (!checkOpenAndNoErrors(future)) {
        return future;
    }/*from   w ww .  j av  a  2 s .  c  o m*/
    ObjectMapper objectMapper = JacksonObjectMapperFactory.objectMapper(_config.getProtocolFormat());
    JsonNode schemaNode;
    try {
        schemaNode = objectMapper.readTree(schema);
    } catch (IOException e) {
        SqpException error = new TypeConversionException("The schema could not be parsed: " + e.getMessage(),
                e);
        future.completeExceptionally(error);
        return future;
    }

    send(new TypeMappingMessage(name, schemaNode, Arrays.asList(keywords)), new ResponseHandler<>(future, m -> {
        if (m.isA(MessageType.ReadyMessage)) {
            return false; // just ignore them
        } else if (m.isA(MessageType.TypeMappingRegisteredMessage)) {
            TypeMappingRegisteredMessage response = m.secureCast();
            future.complete(response.getNative());
            return true;
        }
        throw new UnexpectedMessageException("waiting for information response", m);
    }));
    return future;
}

From source file:io.pravega.controller.server.SegmentHelper.java

public CompletableFuture<UUID> createTransaction(final String scope, final String stream,
        final int segmentNumber, final UUID txId, final HostControllerStore hostControllerStore,
        final ConnectionFactory clientCF) {
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);

    final CompletableFuture<UUID> result = new CompletableFuture<>();
    final WireCommandType type = WireCommandType.CREATE_TRANSACTION;
    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override/*  w w  w  . ja v  a2  s. c  om*/
        public void connectionDropped() {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped));
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost));
        }

        @Override
        public void transactionCreated(WireCommands.TransactionCreated transactionCreated) {
            result.complete(txId);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };

    WireCommands.CreateTransaction request = new WireCommands.CreateTransaction(idGenerator.get(),
            Segment.getScopedName(scope, stream, segmentNumber), txId);
    sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri));
    return result;
}

From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessor.java

private CompletableFuture<Void> writeRequest(AutoScaleEvent event) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    try {/*from w  ww . ja  v a2  s . co m*/
        CompletableFuture.runAsync(() -> {
            try {
                writer.get().writeEvent(event.getKey(), event).get();
                result.complete(null);
            } catch (InterruptedException | ExecutionException e) {
                log.error("error sending request to requeststream {}", e);
                result.completeExceptionally(e);
            }
        }, executor);
    } catch (RejectedExecutionException e) {
        log.error("our executor queue is full. failed to post scale event for {}/{}/{}", event.getScope(),
                event.getStream(), event.getSegmentNumber());
        result.completeExceptionally(e);
    }

    return result;
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void invoke_onNokRequest_onIllegalArgEx_futureCompletesExceptionally()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Req req = new Req();

    Channel channel = mock(Channel.class);

    CompletableFuture<Res> answer = new CompletableFuture<>();
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    doReturn(answer).when(receiver).put(anyString(), any());

    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);

    ObjectMapper mapper = mock(ObjectMapper.class);
    doThrow(IllegalArgumentException.class).when(mapper).writeValueAsBytes(any());

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver,
            new DefaultRequestRouter(), new UidGenerator() {
            }, new DefaultSerializer(mapper), Maps.newHashMap());
    CompletableFuture<Res> actual = invoker.invoke(req, Res.class);

    assertSame(answer, actual);//  w ww.j  av a 2  s .  co m
    assertTrue(actual.isDone());
    assertTrue(actual.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        actual.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof IllegalArgumentException);
        throw ex;
    }
}

From source file:co.runrightfast.vertx.demo.testHarness.jmx.DemoMXBeanImpl.java

@Override
public String verticleDeployments() {
    if (getVerticleDeploymentsMessageSender == null) {
        getVerticleDeploymentsMessageSender = new ProtobufMessageProducer(vertx.eventBus(),
                EventBusAddress.eventBusAddress(RunRightFastVerticleManager.VERTICLE_ID,
                        "get-verticle-deployments"),
                getProtobufMessageCodec(GetVerticleDeployments.Request.getDefaultInstance()).get(),
                metricRegistry);//from  w ww.j  a  v a2  s . c o  m
    }

    final CompletableFuture<com.google.protobuf.Message> future = new CompletableFuture();

    getVerticleDeploymentsMessageSender.send(GetVerticleDeployments.Request.newBuilder().build(),
            new DeliveryOptions().setSendTimeout(2000L),
            responseHandler(future, GetVerticleDeployments.Response.class));

    final com.google.protobuf.Message response;
    try {
        response = future.get();
    } catch (final InterruptedException | ExecutionException ex) {
        throw new RuntimeException(ex);
    }

    // TODO: aggregate GetVerticleDeployments.Response from all RunRightFastVerticleManager instances deployed within the JVm
    // ping
    return JsonUtils.toVertxJsonObject(ProtobufUtils.protobuMessageToJson(response)).encodePrettily();
}

From source file:com.movilizer.mds.webservice.services.UploadFileService.java

private CompletableFuture<UploadResponse> upload(HttpEntity entity, Integer connectionTimeoutInMillis) {
    CompletableFuture<UploadResponse> future = new CompletableFuture<>();
    try {//from  w  w  w  . j av  a2s  .co  m

        Async.newInstance().execute(
                Request.Post(documentUploadAddress.toURI())
                        .addHeader(USER_AGENT_HEADER_KEY, DefaultValues.USER_AGENT)
                        .connectTimeout(connectionTimeoutInMillis).body(entity),
                new ResponseHandlerAdapter<UploadResponse>(future) {
                    @Override
                    public UploadResponse convertHttpResponse(HttpResponse httpResponse) {
                        logger.info(Messages.UPLOAD_COMPLETE);
                        int statusCode = httpResponse.getStatusLine().getStatusCode();
                        String errorMessage = httpResponse.getStatusLine().getReasonPhrase();
                        if (statusCode == POSSIBLE_BAD_CREDENTIALS) {
                            errorMessage = errorMessage + Messages.FAILED_FILE_UPLOAD_CREDENTIALS;
                        }
                        return new UploadResponse(statusCode, errorMessage);
                    }
                });
    } catch (URISyntaxException e) {
        if (logger.isErrorEnabled()) {
            logger.error(String.format(Messages.UPLOAD_ERROR, e.getMessage()));
        }
        future.completeExceptionally(new MovilizerWebServiceException(e));
    }
    return future;
}

From source file:io.pravega.client.stream.mock.MockController.java

private boolean deleteSegment(String name, PravegaNodeUri uri) {
    CompletableFuture<Boolean> result = new CompletableFuture<>();
    FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override/*w  ww.j av  a2 s. com*/
        public void connectionDropped() {
            result.completeExceptionally(new ConnectionClosedException());
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(new NotImplementedException());
        }

        @Override
        public void segmentDeleted(WireCommands.SegmentDeleted segmentDeleted) {
            result.complete(true);
        }

        @Override
        public void noSuchSegment(WireCommands.NoSuchSegment noSuchSegment) {
            result.complete(false);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };
    DeleteSegment command = new WireCommands.DeleteSegment(idGenerator.get(), name);
    sendRequestOverNewConnection(command, replyProcessor, result);
    return getAndHandleExceptions(result, RuntimeException::new);
}

From source file:co.runrightfast.vertx.core.impl.VertxServiceImpl.java

private void deployVerticleManager() throws InterruptedException {
    final CompletableFuture<AsyncResult<String>> deployVerticleResult = new CompletableFuture<>();
    vertx.deployVerticle(verticleManager, deployVerticleResult::complete);
    while (true) {
        try {/* w  ww .ja v  a 2 s  .  c om*/
            final AsyncResult<String> result = deployVerticleResult.get(10, TimeUnit.SECONDS);
            if (result.succeeded()) {
                LOG.logp(INFO, getClass().getName(), "deployVerticleManager", result.result());
            } else {
                throw new RuntimeException("Failed to deploy RunRightFastVerticleManager", result.cause());
            }
            break;
        } catch (final ExecutionException ex) {
            throw new RuntimeException("Failed to deploy RunRightFastVerticleManager", ex);
        } catch (final TimeoutException ex) {
            LOG.logp(INFO, getClass().getName(), "deployVerticleManager",
                    "Waiting for RunRightFastVerticleManager deployment to complete");
        } catch (final InterruptedException ex) {
            throw new RuntimeException(ex);
        }
    }
}