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:io.pravega.service.server.host.stat.AutoScaleProcessorTest.java

@Test(timeout = 10000)
public void scaleTest() {
    CompletableFuture<Void> result = new CompletableFuture<>();
    CompletableFuture<Void> result2 = new CompletableFuture<>();
    CompletableFuture<Void> result3 = new CompletableFuture<>();
    EventStreamWriter<ScaleEvent> writer = createWriter(event -> {
        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM1)
                && event.getDirection() == ScaleEvent.UP) {
            result.complete(null);/*  ww w.jav a 2 s .co m*/
        }

        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM2)
                && event.getDirection() == ScaleEvent.DOWN) {
            result2.complete(null);
        }

        if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM3)
                && event.getDirection() == ScaleEvent.DOWN) {
            result3.complete(null);
        }
    });

    AutoScaleProcessor monitor = new AutoScaleProcessor(writer,
            AutoScalerConfig.builder().with(AutoScalerConfig.MUTE_IN_SECONDS, 0)
                    .with(AutoScalerConfig.COOLDOWN_IN_SECONDS, 0)
                    .with(AutoScalerConfig.CACHE_CLEANUP_IN_SECONDS, 1)
                    .with(AutoScalerConfig.CACHE_EXPIRY_IN_SECONDS, 1).build(),
            executor, maintenanceExecutor);

    String streamSegmentName1 = Segment.getScopedName(SCOPE, STREAM1, 0);
    String streamSegmentName2 = Segment.getScopedName(SCOPE, STREAM2, 0);
    String streamSegmentName3 = Segment.getScopedName(SCOPE, STREAM3, 0);
    monitor.notifyCreated(streamSegmentName1, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);
    monitor.notifyCreated(streamSegmentName2, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);
    monitor.notifyCreated(streamSegmentName3, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10);

    long twentyminutesback = System.currentTimeMillis() - Duration.ofMinutes(20).toMillis();
    monitor.put(streamSegmentName1, new ImmutablePair<>(twentyminutesback, twentyminutesback));
    monitor.put(streamSegmentName3, new ImmutablePair<>(twentyminutesback, twentyminutesback));

    monitor.report(streamSegmentName1, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback,
            1001, 500, 200, 200);

    monitor.report(streamSegmentName3, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 0.0,
            0.0, 0.0, 0.0);

    monitor.notifySealed(streamSegmentName1);
    assertTrue(FutureHelpers.await(result));
    assertTrue(FutureHelpers.await(result));
    assertTrue(FutureHelpers.await(result3));
}

From source file:com.devicehive.rpcclient.RpcClientActionTest.java

@Test
public void testNotificationSearchAction() throws Exception {
    NotificationSearchRequest searchRequest = new NotificationSearchRequest();
    searchRequest.setId(Long.MAX_VALUE); // nonexistent id
    searchRequest.setGuid(UUID.randomUUID().toString()); // random guid

    Request request = Request.newBuilder().withPartitionKey(searchRequest.getGuid()).withBody(searchRequest)
            .build();/*from  w  ww . ja  v a 2s  .c  o m*/
    CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(request, future::complete);

    Response response = future.get(10, TimeUnit.SECONDS);
    NotificationSearchResponse responseBody = (NotificationSearchResponse) response.getBody();
    assertTrue(responseBody.getNotifications().isEmpty());
}

From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandler.java

@Override
public final CompletableFuture<Void> process(final T streamEvent) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    Work work = new Work(streamEvent, System.currentTimeMillis(), result);
    String key = streamEvent.getKey();

    final ConcurrentLinkedQueue<Work> queue;

    synchronized (lock) {
        if (workers.containsKey(key)) {
            workers.get(key).add(work);// w  ww  .j  a  v  a 2 s .co m
            queue = null;
        } else {
            queue = new ConcurrentLinkedQueue<>();
            queue.add(work);
            workers.put(key, queue);
        }
    }

    if (queue != null) {
        executor.execute(() -> run(key, queue));
    }

    return result;
}

From source file:net.data.technology.jraft.extensions.http.HttpRpcClient.java

@Override
public CompletableFuture<RaftResponseMessage> send(RaftRequestMessage request) {
    CompletableFuture<RaftResponseMessage> future = new CompletableFuture<RaftResponseMessage>();
    String payload = this.gson.toJson(request);
    HttpPost postRequest = new HttpPost(this.serverUrl);
    postRequest.setEntity(new StringEntity(payload, StandardCharsets.UTF_8));
    this.httpClient.execute(postRequest, new FutureCallback<HttpResponse>() {

        @Override//from  ww w .  j  a  v  a  2s  .co  m
        public void completed(HttpResponse result) {
            if (result.getStatusLine().getStatusCode() != 200) {
                logger.info("receive an response error code "
                        + String.valueOf(result.getStatusLine().getStatusCode()) + " from server");
                future.completeExceptionally(new IOException("Service Error"));
            }

            try {
                InputStreamReader reader = new InputStreamReader(result.getEntity().getContent());
                RaftResponseMessage response = gson.fromJson(reader, RaftResponseMessage.class);
                future.complete(response);
            } catch (Throwable error) {
                logger.info("fails to parse the response from server due to errors", error);
                future.completeExceptionally(error);
            }
        }

        @Override
        public void failed(Exception ex) {
            future.completeExceptionally(ex);
        }

        @Override
        public void cancelled() {
            future.completeExceptionally(new IOException("request cancelled"));
        }
    });
    return future;
}

From source file:com.digitalpetri.opcua.raspberrypi.PiServer.java

private CompletableFuture<Void> shutdownFuture() {
    CompletableFuture<Void> future = new CompletableFuture<>();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        server.shutdown();//  w  w  w .ja  v a2  s  .  c om
        future.complete(null);
    }));

    return future;
}

From source file:org.apache.hadoop.hbase.client.AsyncMetaRegionLocator.java

CompletableFuture<HRegionLocation> getRegionLocation() {
    for (;;) {//from   w  w  w .j  av a2  s  . co  m
        HRegionLocation metaRegionLocation = this.metaRegionLocation.get();
        if (metaRegionLocation != null) {
            return CompletableFuture.completedFuture(metaRegionLocation);
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("Meta region location cache is null, try fetching from registry.");
        }
        if (metaRelocateFuture.compareAndSet(null, new CompletableFuture<>())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Start fetching meta region location from registry.");
            }
            CompletableFuture<HRegionLocation> future = metaRelocateFuture.get();
            registry.getMetaRegionLocation().whenComplete((locs, error) -> {
                if (error != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Failed to fetch meta region location from registry", error);
                    }
                    metaRelocateFuture.getAndSet(null).completeExceptionally(error);
                    return;
                }
                HRegionLocation loc = locs.getDefaultRegionLocation();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("The fetched meta region location is " + loc);
                }
                // Here we update cache before reset future, so it is possible that someone can get a
                // stale value. Consider this:
                // 1. update cache
                // 2. someone clear the cache and relocate again
                // 3. the metaRelocateFuture is not null so the old future is used.
                // 4. we clear metaRelocateFuture and complete the future in it with the value being
                // cleared in step 2.
                // But we do not think it is a big deal as it rarely happens, and even if it happens, the
                // caller will retry again later, no correctness problems.
                this.metaRegionLocation.set(loc);
                metaRelocateFuture.set(null);
                future.complete(loc);
            });
        } else {
            CompletableFuture<HRegionLocation> future = metaRelocateFuture.get();
            if (future != null) {
                return future;
            }
        }
    }
}

From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java

public MagicCommandOutput time(String codeToExecute, Message message, int executionCount, boolean showResult) {
    CompletableFuture<TimeMeasureData> compileTime = new CompletableFuture<>();

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    long currentThreadId = Thread.currentThread().getId();

    Long startWallTime = System.nanoTime();
    Long startCpuTotalTime = threadMXBean.getCurrentThreadCpuTime();
    Long startUserTime = threadMXBean.getCurrentThreadUserTime();

    SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel, message,
            executionCount);/*from ww w.ja  v  a  2 s  .c om*/
    if (!showResult) {
        simpleEvaluationObject.noResult();
    }

    TryResult either = kernel.executeCode(codeToExecute, simpleEvaluationObject);

    Long endWallTime = System.nanoTime();
    Long endCpuTotalTime = threadMXBean.getThreadCpuTime(currentThreadId);
    Long endUserTime = threadMXBean.getThreadUserTime(currentThreadId);

    compileTime.complete(new TimeMeasureData(endCpuTotalTime - startCpuTotalTime, endUserTime - startUserTime,
            endWallTime - startWallTime));
    String messageInfo = "CPU times: user %s, sys: %s, total: %s \nWall Time: %s\n";

    try {
        TimeMeasureData timeMeasuredData = compileTime.get();

        return new MagicCommandOutput(MagicCommandOutput.Status.OK,
                String.format(messageInfo, format(timeMeasuredData.getCpuUserTime()),
                        format(timeMeasuredData.getCpuTotalTime() - timeMeasuredData.getCpuUserTime()),
                        format(timeMeasuredData.getCpuTotalTime()), format(timeMeasuredData.getWallTime())),
                either, simpleEvaluationObject);

    } catch (InterruptedException | ExecutionException e) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
                "There occurs problem during measuring time for your statement.");
    }
}

From source file:org.apache.trafficcontrol.client.trafficops.TOSessionTest.java

@Test(expected = LoginException.class)
public void test401Response() throws Throwable {
    HttpResponse resp = Mockito.mock(HttpResponse.class);
    Mockito.when(resp.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_0, 401, "Not Auth"));

    final CompletableFuture<HttpResponse> f = new CompletableFuture<>();
    f.complete(resp);//from  w  ww.ja v  a 2  s.  c o  m

    Mockito.doReturn(f).when(sessionMock).execute(Mockito.any(RequestBuilder.class));

    TOSession session = TOSession.builder().fromURI(baseUri).setRestClient(sessionMock).build();

    try {
        session.getDeliveryServices().get();
    } catch (Throwable e) {
        throw e.getCause();
    }
}

From source file:org.jnode.net.NServerSocket.java

private CompletableFuture<ServerSocketChannel> createServerChannel(int port) {
    CompletableFuture cf = new CompletableFuture<>();
    try {//from   w  w  w  .  j  av  a  2 s .  c  o  m
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(new InetSocketAddress(port));
        cf.complete(ssc);
    } catch (Exception e) {
        cf.completeExceptionally(e);
    }
    return cf;
}

From source file:com.helion3.prism.api.query.QueryBuilder.java

/**
 * Builds a {@link Query} by parsing an array of arguments.
 *
 * @param parameters String[] Parameter:value list
 * @return {@link Query} Database query object
 *//* w w w.j av  a2 s  .co  m*/
public static CompletableFuture<Query> fromArguments(QuerySession session, @Nullable String[] arguments)
        throws ParameterException {
    checkNotNull(session);

    Query query = new Query();
    CompletableFuture<Query> future = new CompletableFuture<Query>();

    // Track all parameter pairs
    Map<String, String> definedParameters = new HashMap<String, String>();

    if (arguments.length > 0) {
        List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>();
        for (String arg : arguments) {
            Optional<ListenableFuture<?>> listenable;

            if (flagPattern.matcher(arg).matches()) {
                listenable = parseFlagFromArgument(session, query, arg);
            } else {
                // Get alias/value pair
                Pair<String, String> pair = getParameterKeyValue(arg);

                // Parse for handler
                listenable = parseParameterFromArgument(session, query, pair);

                // Add to list of defined
                definedParameters.put(pair.getKey(), pair.getValue());
            }

            if (listenable.isPresent()) {
                futures.add(listenable.get());
            }
        }

        if (!futures.isEmpty()) {
            ListenableFuture<List<Object>> combinedFuture = Futures.allAsList(futures);
            combinedFuture.addListener(new Runnable() {
                @Override
                public void run() {
                    future.complete(query);
                }
            }, MoreExecutors.sameThreadExecutor());
        } else {
            future.complete(query);
        }
    } else {
        future.complete(query);
    }

    if (Prism.getConfig().getNode("defaults", "enabled").getBoolean()) {
        // Require any parameter defaults
        String defaultsUsed = "";
        for (ParameterHandler handler : Prism.getParameterHandlers()) {
            boolean aliasFound = false;

            for (String alias : handler.getAliases()) {
                if (definedParameters.containsKey(alias)) {
                    aliasFound = true;
                    break;
                }
            }

            if (!aliasFound) {
                Optional<Pair<String, String>> pair = handler.processDefault(session, query);
                if (pair.isPresent()) {
                    defaultsUsed += pair.get().getKey() + ":" + pair.get().getValue() + " ";
                }
            }
        }

        // @todo should move this
        if (!defaultsUsed.isEmpty()) {
            session.getCommandSource().get().sendMessage(
                    Format.subduedHeading(Text.of(String.format("Defaults used: %s", defaultsUsed))));
        }
    }

    return future;
}