Example usage for java.util.concurrent CompletableFuture completedFuture

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

Introduction

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

Prototype

public static <U> CompletableFuture<U> completedFuture(U value) 

Source Link

Document

Returns a new CompletableFuture that is already completed with the given value.

Usage

From source file:com.heliosdecompiler.helios.gui.view.editors.DisassemblerView.java

@Override
public CompletableFuture<byte[]> save(Node node) {
    if (!(node instanceof CodeArea)) {
        return CompletableFuture.completedFuture(new byte[0]);
    }// w ww .  j  ava2s.  c o m

    String assembledCode = ((CodeArea) node).getText();

    CompletableFuture<byte[]> future = new CompletableFuture<>();

    backgroundTaskHelper.submit(new BackgroundTask(
            Message.TASK_ASSEMBLE_FILE.format(node.getProperties().get("path").toString()), true, () -> {
                if (controller instanceof KrakatauDisassemblerController) {
                    KrakatauAssemblerSettings settings = new KrakatauAssemblerSettings();
                    settings.setPythonExecutable(new File(configuration.getString(Settings.PYTHON2_KEY)));
                    settings.setProcessCreator(processController::launchProcess);

                    try {
                        TransformationResult<byte[]> result = StandardTransformers.Assemblers.KRAKATAU
                                .assemble(assembledCode, settings);
                        if (result.getTransformationData().size() == 1) {
                            future.complete(result.getTransformationData().values().iterator().next());
                        } else {
                            future.completeExceptionally(new KrakatauException(KrakatauException.Reason.UNKNOWN,
                                    result.getStdout(), result.getStderr()));
                        }
                    } catch (TransformationException e) {
                        future.completeExceptionally(e);
                    }
                } else {
                    future.complete(new byte[0]);
                }
            }));

    return future;
}

From source file:io.symcpe.hendrix.api.dao.TestTenantManager.java

@Before
public void before() {
    em = emf.createEntityManager();/*from w w  w . j a  v  a  2 s .  c  om*/
    when(am.getEM()).thenReturn(em);
    when(am.getRuleTopicName()).thenReturn("ruleTopic");
    when(am.getApiKeyTopic()).thenReturn("apikeyTopic");
    when(am.getKafkaProducer()).thenReturn(producer);

    when(producer.send(any())).thenReturn(
            CompletableFuture.completedFuture(new RecordMetadata(new TopicPartition("ruleTopic", 2), 1, 1)));
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> deleteStream() {
    return CompletableFuture.completedFuture(null);
}

From source file:de.ks.activity.initialization.ActivityInitialization.java

public <T> CompletableFuture<DefaultLoader<Node, T>> loadAdditionalControllerWithFuture(
        Class<T> controllerClass) {
    @SuppressWarnings("unchecked")
    DefaultLoader<Node, T> loader = loadAdditionalController(controllerClass);
    CompletableFuture completed = CompletableFuture.completedFuture(loader);
    return completed;
}

From source file:io.pravega.controller.server.eventProcessor.ScaleRequestHandler.java

public CompletableFuture<Void> process(final ScaleEvent request) {
    if (!(request.getTimestamp() + REQUEST_VALIDITY_PERIOD > System.currentTimeMillis())) {
        // request no longer valid. Ignore.
        // log, because a request was fetched from the stream after its validity expired.
        // This should be a rare occurrence. Either the request was unable to acquire lock for a long time. Or
        // we are processing at much slower rate than the message ingestion rate into the stream. We should scale up.
        // Either way, logging this helps us know how often this is happening.

        log.debug(String.format("Scale Request for stream %s/%s expired", request.getScope(),
                request.getStream()));//from  www. ja v a  2  s  .c o m
        return CompletableFuture.completedFuture(null);
    }

    final OperationContext context = streamMetadataStore.createContext(request.getScope(), request.getStream());

    return RETRY.runAsync(() -> {
        final CompletableFuture<ScalingPolicy> policyFuture = streamMetadataStore
                .getConfiguration(request.getScope(), request.getStream(), context, executor)
                .thenApply(StreamConfiguration::getScalingPolicy);

        if (request.getDirection() == ScaleEvent.UP) {
            return policyFuture.thenComposeAsync(policy -> processScaleUp(request, policy, context), executor);
        } else {
            return policyFuture.thenComposeAsync(policy -> processScaleDown(request, policy, context),
                    executor);
        }
    }, executor);
}

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

@Override
@Synchronized//from www.ja v a2  s .c  om
public CompletableFuture<Boolean> createScope(final String scopeName) {
    if (createdScopes.get(scopeName) != null) {
        return CompletableFuture.completedFuture(false);
    }
    createdScopes.put(scopeName, new HashSet<>());
    return CompletableFuture.completedFuture(true);
}

From source file:com.spotify.styx.api.MiddlewaresTest.java

@Test
public void testJsonAsync() throws Exception {
    AsyncHandler<Response<ByteString>> outerHandler = Middlewares.jsonAsync()
            .apply(rc -> CompletableFuture.completedFuture(Response.forPayload(TEST_STRUCT)));

    CompletionStage<Response<ByteString>> completionStage = outerHandler
            .invoke(RequestContexts.create(mock(Request.class), mock(Client.class), Collections.emptyMap()));

    assertThat(completionStage.toCompletableFuture().get().payload().get().utf8(),
            is("{\"foo\":\"blah\"," + "\"inner_object\":{" + "\"field_name_convention\":\"bloh\","
                    + "\"enum_field\":\"enum_value\"}}"));
}

From source file:com.teradata.benchto.driver.listeners.GraphiteEventExecutionListener.java

@Override
public Future<?> executionFinished(QueryExecutionResult executionResult) {
    if (executionResult.getBenchmark().isConcurrent()) {
        return CompletableFuture.completedFuture("");
    }//from   ww  w .jav a  2s.c  om

    QueryExecution queryExecution = executionResult.getQueryExecution();
    GraphiteEventRequest request = new GraphiteEventRequestBuilder()
            .what(format("Benchmark %s, query %s (%d) ended", queryExecution.getBenchmark().getUniqueName(),
                    executionResult.getQueryName(), queryExecution.getRun()))
            .tags("execution", "ended", executionResult.getEnvironment())
            .data(format("duration: %d ms", executionResult.getQueryDuration().toMillis()))
            .when(executionResult.getUtcEnd()).build();

    Future<?> future = taskExecutor.submit(() -> graphiteClient.storeEvent(request));

    executionSynchronizer.awaitAfterQueryExecutionAndBeforeResultReport(executionResult);

    return future;
}

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

@Override
@Synchronized/*from w  w w .ja v a 2 s.  c  o m*/
public CompletableFuture<Boolean> deleteScope(String scopeName) {
    if (createdScopes.get(scopeName) == null) {
        return CompletableFuture.completedFuture(false);
    }

    if (!createdScopes.get(scopeName).isEmpty()) {
        return FutureHelpers.failedFuture(new IllegalStateException("Scope is not empty."));
    }

    createdScopes.remove(scopeName);
    return CompletableFuture.completedFuture(true);
}

From source file:com.spotify.styx.api.deprecated.CliResource.java

private CompletionStage<Response<WorkflowInstance>> proxyTrigger(WorkflowInstance workflowInstance,
        RequestContext rc) {//w ww  .  j av  a 2  s  .  com
    final ByteString payload;
    try {
        payload = Json.serialize(WorkflowInstance.create(workflowInstance));
    } catch (JsonProcessingException e) {
        return CompletableFuture
                .completedFuture(Response.forStatus(Status.BAD_REQUEST.withReasonPhrase("Bad json payload")));
    }
    final Request request = rc.request().withUri(schedulerServiceBaseUrl + SCHEDULER_BASE_PATH + TRIGGER_PATH)
            .withPayload(payload);
    return rc.requestScopedClient().send(request)
            .thenApply(response -> response.withPayload(response.payload().map(p -> {
                try {
                    return WorkflowInstance
                            .create(Json.deserialize(p, com.spotify.styx.model.WorkflowInstance.class));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).orElse(null)));
}