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.teradata.benchto.driver.listeners.LoggingBenchmarkExecutionListener.java

@Override
public Future<?> executionFinished(QueryExecutionResult result) {
    if (result.isSuccessful()) {
        LOG.info("Query finished: {} ({}/{}), rows count: {}, duration: {}", result.getQueryName(),
                result.getQueryExecution().getRun(), result.getBenchmark().getRuns(), result.getRowsCount(),
                result.getQueryDuration());
    } else {//from   www  .j av  a  2s.c  om
        LOG.error("Query failed: {} ({}/{}), execution error: {}", result.getQueryName(),
                result.getQueryExecution().getRun(), result.getBenchmark().getRuns(),
                result.getFailureCause().getMessage());
    }

    return CompletableFuture.completedFuture("");
}

From source file:org.trustedanalytics.routermetrics.GorouterLatencyCollectorTests.java

private CompletableFuture<ResponseEntity<GorouterMetrics>> gorouterAnswer(String hostname,
        ImmutableMap<String, Double> latencyHistogram)

        throws ExecutionException, InterruptedException {

    GorouterMetrics gorouterMetrics = new GorouterMetrics();
    gorouterMetrics.setHost(hostname);//from www  .j  av  a2s  .  c o  m
    gorouterMetrics.setLatency(latencyHistogram);
    ResponseEntity<GorouterMetrics> responseEntity = new ResponseEntity<>(gorouterMetrics, HttpStatus.OK);

    return CompletableFuture.completedFuture(responseEntity);
}

From source file:com.yahoo.pulsar.common.naming.NamespaceBundleFactory.java

public NamespaceBundleFactory(PulsarService pulsar, HashFunction hashFunc) {
    this.hashFunc = hashFunc;

    this.bundlesCache = Caffeine.newBuilder().buildAsync((NamespaceName namespace, Executor executor) -> {
        String path = AdminResource.joinPath(LOCAL_POLICIES_ROOT, namespace.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading cache with bundles for {}", namespace);
        }//from w  ww .j  a v  a  2  s.c o  m

        if (pulsar == null || pulsar.getConfigurationCache() == null) {
            return CompletableFuture.completedFuture(getBundles(namespace, null));
        }

        CompletableFuture<NamespaceBundles> future = new CompletableFuture<>();
        // Read the static bundle data from the policies
        pulsar.getLocalZkCacheService().policiesCache().getAsync(path).thenAccept(policies -> {
            // If no policies defined for namespace, assume 1 single bundle
            BundlesData bundlesData = policies.map(p -> p.bundles).orElse(null);
            NamespaceBundles namespaceBundles = getBundles(namespace, bundlesData);
            future.complete(namespaceBundles);
        }).exceptionally(ex -> {
            future.completeExceptionally(ex);
            return null;
        });
        return future;
    });

    if (pulsar != null && pulsar.getConfigurationCache() != null) {
        pulsar.getLocalZkCacheService().policiesCache().registerListener(this);
    }

    this.pulsar = pulsar;
}

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

public CompletableFuture<Void> process(final AutoScaleEvent 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   w w  w .jav  a  2 s.c om*/
        return CompletableFuture.completedFuture(null);
    }

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

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

        if (request.getDirection() == AutoScaleEvent.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.controller.server.eventProcessor.requesthandlers.AutoScaleTask.java

public CompletableFuture<Void> execute(final AutoScaleEvent 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.info(String.format("Scale Request for stream %s/%s expired", request.getScope(),
                request.getStream()));//from  w  ww.ja  va 2s. co m
        return CompletableFuture.completedFuture(null);
    }

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

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

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

From source file:com.linecorp.armeria.server.http.auth.AuthServiceTest.java

@Override
protected void configureServer(ServerBuilder sb) throws Exception {
    // Auth with arbitrary authorizer
    Authorizer<HttpRequest> authorizer = (ctx, req) -> CompletableFuture
            .supplyAsync(() -> "unit test".equals(req.headers().get(HttpHeaderNames.AUTHORIZATION)));
    sb.serviceAt("/", new AbstractHttpService() {
        @Override/*w  w  w . j a va 2s. c  o m*/
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            res.respond(HttpStatus.OK);
        }
    }.decorate(HttpAuthService.newDecorator(authorizer)).decorate(LoggingService::new));

    // Auth with HTTP basic
    final Map<String, String> usernameToPassword = ImmutableMap.of("brown", "cony", "pangyo", "choco");
    Authorizer<BasicToken> httpBasicAuthorizer = (ctx, token) -> {
        String username = token.username();
        String password = token.password();
        return CompletableFuture.completedFuture(password.equals(usernameToPassword.get(username)));
    };
    sb.serviceAt("/basic", new AbstractHttpService() {
        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            res.respond(HttpStatus.OK);
        }
    }.decorate(new HttpAuthServiceBuilder().addBasicAuth(httpBasicAuthorizer).newDecorator())
            .decorate(LoggingService::new));

    // Auth with OAuth1a
    Authorizer<OAuth1aToken> oAuth1aAuthorizer = (ctx, token) -> CompletableFuture
            .completedFuture("dummy_signature".equals(token.signature()));
    sb.serviceAt("/oauth1a", new AbstractHttpService() {
        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            res.respond(HttpStatus.OK);
        }
    }.decorate(new HttpAuthServiceBuilder().addOAuth1a(oAuth1aAuthorizer).newDecorator())
            .decorate(LoggingService::new));

    // Auth with OAuth2
    Authorizer<OAuth2Token> oAuth2aAuthorizer = (ctx, token) -> CompletableFuture
            .completedFuture("dummy_oauth2_token".equals(token.accessToken()));
    sb.serviceAt("/oauth2", new AbstractHttpService() {
        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            res.respond(HttpStatus.OK);
        }
    }.decorate(new HttpAuthServiceBuilder().addOAuth2(oAuth2aAuthorizer).newDecorator())
            .decorate(LoggingService::new));

    // Auth with all predicates above!
    HttpService compositeService = new AbstractHttpService() {
        @Override
        protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {
            res.respond(HttpStatus.OK);
        }
    };
    HttpAuthService compositeAuth = new HttpAuthServiceBuilder().add(authorizer)
            .addBasicAuth(httpBasicAuthorizer).addOAuth1a(oAuth1aAuthorizer).addOAuth2(oAuth2aAuthorizer)
            .build(compositeService);
    sb.serviceAt("/composite", compositeAuth.decorate(LoggingService::new));
}

From source file:com.srotya.tau.api.dao.TestRuleGroupManager.java

@Before
public void before() {
    em = emf.createEntityManager();//from   w w  w . j a v a 2  s.c o  m
    when(am.getEM()).thenReturn(em);

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

From source file:com.ikanow.aleph2.aleph2_rest_utils.SharedLibraryCrudServiceWrapper.java

@Override
public CompletableFuture<Supplier<Object>> storeObject(Tuple2<SharedLibraryBean, FileDescriptor> new_object) {
    //if storing shared_lib object is successful, try to store the file
    return this.shared_library_crud.storeObject(new_object._1).thenCompose(f -> {
        _logger.debug("stored object: " + f.get()); //I think I should be returning this
        final Tuple2<ICrudService<FileDescriptor>, FileDescriptor> storage = getSharedLibraryDataStore(
                service_context, new_object._1.path_name(), new_object._2);
        storage._1.storeObject(storage._2);
        return CompletableFuture.completedFuture(f);
    });//  ww  w.  j av  a 2s .c  o m
}

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

@Override
public Future<?> executionStarted(QueryExecution execution) {
    if (execution.getBenchmark().isConcurrent()) {
        return CompletableFuture.completedFuture("");
    }//www.  j av  a2  s .  co  m

    GraphiteEventRequest request = new GraphiteEventRequestBuilder()
            .what(format("Benchmark %s, query %s (%d) started", execution.getBenchmark().getUniqueName(),
                    execution.getQueryName(), execution.getRun()))
            .tags("execution", "started", execution.getBenchmark().getEnvironment()).build();

    return taskExecutor.submit(() -> graphiteClient.storeEvent(request));
}

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

@Override
public CompletableFuture<Integer> getNumberOfOngoingTransactions() {
    synchronized (txnsLock) {
        return CompletableFuture.completedFuture(activeTxns.size());
    }/*from w w  w. ja  v a 2  s .com*/
}