Example usage for java.util.concurrent CompletableFuture get

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public T get() throws InterruptedException, ExecutionException 

Source Link

Document

Waits if necessary for this future to complete, and then returns its result.

Usage

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testGetSegmentsImmediatlyFollowing() throws Exception {
    CompletableFuture<Map<Segment, List<Integer>>> successors;
    successors = controllerClient.getSuccessors(new Segment("scope1", "stream1", 0))
            .thenApply(StreamSegmentsWithPredecessors::getSegmentToPredecessor);
    assertEquals(2, successors.get().size());
    assertEquals(20, successors.get().get(new Segment("scope1", "stream1", 2)).get(0).longValue());
    assertEquals(30, successors.get().get(new Segment("scope1", "stream1", 3)).get(0).longValue());

    successors = controllerClient.getSuccessors(new Segment("scope1", "stream2", 0))
            .thenApply(StreamSegmentsWithPredecessors::getSegmentToPredecessor);
    AssertExtensions.assertThrows("Should throw Exception", successors, throwable -> true);
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

/**
 * Tests that request are handled as individual units which don't interfere with each other.
 * This means that request responses can overtake each other.
 *//*from w  w w . j a va 2s. c  o m*/
@Test
public void testRequestInterleaving() throws Exception {
    final HandlerBlocker handlerBlocker = new HandlerBlocker(timeout);
    testHandler.handlerBody = id -> {
        if (id == 1) {
            handlerBlocker.arriveAndBlock();
        }
        return CompletableFuture.completedFuture(new TestResponse(id));
    };

    // send first request and wait until the handler blocks
    final CompletableFuture<TestResponse> response1 = sendRequestToTestHandler(new TestRequest(1));
    handlerBlocker.awaitRequestToArrive();

    // send second request and verify response
    final CompletableFuture<TestResponse> response2 = sendRequestToTestHandler(new TestRequest(2));
    assertEquals(2, response2.get().id);

    // wake up blocked handler
    handlerBlocker.unblockRequest();

    // verify response to first request
    assertEquals(1, response1.get().id);
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testCreateStream() throws Exception {
    CompletableFuture<Boolean> createStreamStatus;
    createStreamStatus = controllerClient.createStream(StreamConfiguration.builder().streamName("stream1")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    assertTrue(createStreamStatus.get());

    createStreamStatus = controllerClient.createStream(StreamConfiguration.builder().streamName("stream2")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Server should throw exception", createStreamStatus, Throwable -> true);

    createStreamStatus = controllerClient.createStream(StreamConfiguration.builder().streamName("stream3")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Server should throw exception", createStreamStatus, Throwable -> true);

    createStreamStatus = controllerClient.createStream(StreamConfiguration.builder().streamName("stream4")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    assertFalse(createStreamStatus.get());

    createStreamStatus = controllerClient.createStream(StreamConfiguration.builder().streamName("stream5")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Server should throw exception", createStreamStatus, Throwable -> true);

    createStreamStatus = controllerClient.createStream(StreamConfiguration.builder().streamName("stream6")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Should throw Exception", createStreamStatus, throwable -> true);
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testUpdateStream() throws Exception {
    CompletableFuture<Boolean> updateStreamStatus;
    updateStreamStatus = controllerClient.updateStream(StreamConfiguration.builder().streamName("stream1")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    assertTrue(updateStreamStatus.get());

    updateStreamStatus = controllerClient.updateStream(StreamConfiguration.builder().streamName("stream2")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Server should throw exception", updateStreamStatus, Throwable -> true);

    updateStreamStatus = controllerClient.updateStream(StreamConfiguration.builder().streamName("stream3")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Server should throw exception", updateStreamStatus, Throwable -> true);

    updateStreamStatus = controllerClient.updateStream(StreamConfiguration.builder().streamName("stream4")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Server should throw exception", updateStreamStatus, Throwable -> true);

    updateStreamStatus = controllerClient.updateStream(StreamConfiguration.builder().streamName("stream5")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Should throw Exception", updateStreamStatus, throwable -> true);

    updateStreamStatus = controllerClient.updateStream(StreamConfiguration.builder().streamName("stream6")
            .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
    AssertExtensions.assertThrows("Should throw Exception", updateStreamStatus, throwable -> true);
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testScale() throws Exception {
    CompletableFuture<Boolean> scaleStream;
    StreamImpl stream = new StreamImpl("scope1", "stream1");
    scaleStream = controllerClient.scaleStream(stream, new ArrayList<>(), new HashMap<>(), executor)
            .getFuture();// ww w.  j  av  a 2  s. c o  m
    assertTrue(scaleStream.get());
    CompletableFuture<StreamSegments> segments = controllerClient.getCurrentSegments("scope1", "stream1");
    assertEquals(2, segments.get().getSegments().size());
    assertEquals(new Segment("scope1", "stream1", 6), segments.get().getSegmentForKey(0.25));
    assertEquals(new Segment("scope1", "stream1", 7), segments.get().getSegmentForKey(0.75));

    scaleStream = controllerClient
            .scaleStream(new StreamImpl("scope1", "stream2"), new ArrayList<>(), new HashMap<>(), executor)
            .getFuture();
    AssertExtensions.assertThrows("Should throw Exception", scaleStream, throwable -> true);

    scaleStream = controllerClient
            .scaleStream(new StreamImpl("UNKNOWN", "stream2"), new ArrayList<>(), new HashMap<>(), executor)
            .getFuture();
    AssertExtensions.assertThrows("Should throw Exception", scaleStream, throwable -> true);

    scaleStream = controllerClient
            .scaleStream(new StreamImpl("scope1", "UNKNOWN"), new ArrayList<>(), new HashMap<>(), executor)
            .getFuture();
    AssertExtensions.assertThrows("Should throw Exception", scaleStream, throwable -> true);
}

From source file:com.ikanow.aleph2.management_db.services.DataBucketCrudService.java

public ManagementFuture<Boolean> deleteObjectById(final Object id) {
    final CompletableFuture<Optional<DataBucketBean>> result = _underlying_data_bucket_db.get()
            .getObjectById(id);//  w w w .j av a 2 s  .  com
    try {
        if (result.get().isPresent()) {
            return this.deleteBucket(result.get().get());
        } else {
            return FutureUtils.createManagementFuture(CompletableFuture.completedFuture(false));
        }
    } catch (Exception e) {
        // This is a serious enough exception that we'll just leave here
        return FutureUtils.createManagementFuture(FutureUtils.returnError(e));
    }
}

From source file:org.apache.pulsar.broker.web.PulsarWebResource.java

/**
 * Checks whether the user has Pulsar Super-User access to the system.
 *
 * @throws WebApplicationException/*  www.  j  a  v  a  2s.c o  m*/
 *             if not authorized
 */
protected void validateSuperUserAccess() {
    if (config().isAuthenticationEnabled()) {
        String appId = clientAppId();
        if (log.isDebugEnabled()) {
            log.debug("[{}] Check super user access: Authenticated: {} -- Role: {}", uri.getRequestUri(),
                    isClientAuthenticated(appId), appId);
        }
        String originalPrincipal = originalPrincipal();
        validateOriginalPrincipal(pulsar.getConfiguration().getProxyRoles(), appId, originalPrincipal);

        if (pulsar.getConfiguration().getProxyRoles().contains(appId)) {

            CompletableFuture<Boolean> proxyAuthorizedFuture;
            CompletableFuture<Boolean> originalPrincipalAuthorizedFuture;

            try {
                proxyAuthorizedFuture = pulsar.getBrokerService().getAuthorizationService().isSuperUser(appId);

                originalPrincipalAuthorizedFuture = pulsar.getBrokerService().getAuthorizationService()
                        .isSuperUser(originalPrincipal);

                if (!proxyAuthorizedFuture.get() || !originalPrincipalAuthorizedFuture.get()) {
                    throw new RestException(Status.UNAUTHORIZED,
                            String.format(
                                    "Proxy not authorized for super-user operation (proxy:%s,original:%s)",
                                    appId, originalPrincipal));
                }
            } catch (InterruptedException | ExecutionException e) {
                throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
            }
            log.debug("Successfully authorized {} (proxied by {}) as super-user", originalPrincipal, appId);
        } else if (!config().getSuperUserRoles().contains(appId)) {
            throw new RestException(Status.UNAUTHORIZED, "This operation requires super-user access");
        }
    }
}

From source file:com.ikanow.aleph2.management_db.services.DataBucketCrudService.java

public ManagementFuture<Boolean> deleteObjectBySpec(final QueryComponent<DataBucketBean> unique_spec) {
    final CompletableFuture<Optional<DataBucketBean>> result = _underlying_data_bucket_db.get()
            .getObjectBySpec(unique_spec);
    try {//from   w  w w. j  a va  2  s  .  c om
        if (result.get().isPresent()) {
            return this.deleteBucket(result.get().get());
        } else {
            return FutureUtils.createManagementFuture(CompletableFuture.completedFuture(false));
        }
    } catch (Exception e) {
        // This is a serious enough exception that we'll just leave here
        return FutureUtils.createManagementFuture(FutureUtils.returnError(e));
    }
}

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

protected MagicCommandOutput timeIt(TimeItOption timeItOption, String codeToExecute, Message message,
        int executionCount, boolean showResult) {
    String output = "%s  %s per loop (mean  std. dev. of %d run, %d loop each)";

    if (timeItOption.getNumber() < 0) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
                "Number of execution must be bigger then 0");
    }/* www .  j  a  va2  s  .  c  o  m*/
    int number = timeItOption.getNumber() == 0 ? getBestNumber(codeToExecute, showResult, message)
            : timeItOption.getNumber();

    if (timeItOption.getRepeat() == 0) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Repeat value must be bigger then 0");
    }

    SimpleEvaluationObject seo = createSimpleEvaluationObject(codeToExecute, kernel, message, executionCount);
    seo.noResult();

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

    try {

        if (either.isError()) {
            return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Please correct your statement");
        }

        List<Long> allRuns = new ArrayList<>();
        List<Long> timings = new ArrayList<>();

        CompletableFuture<Boolean> isReady = new CompletableFuture<>();

        IntStream.range(0, timeItOption.getRepeat()).forEach(repeatIter -> {
            IntStream.range(0, number).forEach(numberIter -> {
                SimpleEvaluationObject seo2 = createSimpleEvaluationObject(codeToExecute, kernel, message,
                        executionCount);
                seo2.noResult();
                Long startOfEvaluationInNanoseconds = System.nanoTime();
                TryResult result = kernel.executeCode(codeToExecute, seo2);
                Long endOfEvaluationInNanoseconds = System.nanoTime();
                allRuns.add(endOfEvaluationInNanoseconds - startOfEvaluationInNanoseconds);
                if (repeatIter == timeItOption.getRepeat() - 1 && numberIter == number - 1) {
                    isReady.complete(true);
                }
            });
        });

        if (isReady.get()) {
            allRuns.forEach(run -> timings.add(run / number));

            //calculating average
            long average = timings.stream().reduce((aLong, aLong2) -> aLong + aLong2).orElse(0L)
                    / timings.size();
            double stdev = Math.pow(
                    timings.stream().map(currentValue -> Math.pow(currentValue - average, 2))
                            .reduce((aDouble, aDouble2) -> aDouble + aDouble2).orElse(0.0) / timings.size(),
                    0.5);

            if (timeItOption.getQuietMode()) {
                output = "";
            } else {
                output = String.format(output, format(average), format((long) stdev), timeItOption.getRepeat(),
                        number);
            }

            return new MagicCommandOutput(MagicCommandOutput.Status.OK, output);
        }
    } catch (InterruptedException | ExecutionException e) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
                "There occurs problem with " + e.getMessage());
    }
    return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
            "There occurs problem with timeIt operations");
}

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

private int getBestNumber(String codeToExecute, boolean showResult, Message message) {
    for (int value = 0; value < 10;) {
        Double numberOfExecution = Math.pow(10, value);
        CompletableFuture<Boolean> keepLooking = new CompletableFuture<>();

        Long startTime = System.nanoTime();
        IntStream.range(0, numberOfExecution.intValue()).forEach(indexOfExecution -> {
            SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel,
                    new Message(new Header(message.type(), message.getHeader().getSession())), 0);
            if (!showResult) {
                simpleEvaluationObject.noResult();
            }//  w w  w  . j a v  a  2 s.c om

            kernel.executeCode(codeToExecute, simpleEvaluationObject);
            if (numberOfExecution.intValue() - 1 == indexOfExecution) {
                if (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime) > 0.2) {
                    keepLooking.complete(false);
                } else {
                    keepLooking.complete(true);
                }
            }
        });

        try {
            if (keepLooking.get()) {
                value++;
            } else {
                return numberOfExecution.intValue();
            }
        } catch (ExecutionException | InterruptedException e) {
            throw new IllegalStateException("Cannot create best number of execution.");
        }
    }

    throw new IllegalStateException("Cannot create best number of execution.");
}