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:com.ikanow.aleph2.harvest.script.services.TestScriptHarvestService.java

@Test
public void testOnTest() throws IOException, InterruptedException, ExecutionException {
    final ScriptHarvestService harvester = new ScriptHarvestService();
    harvester.onInit(getFakeContext());//from ww w. j a v  a 2 s.co m

    final String tmp_dir = System.getProperty("java.io.tmpdir");
    final String file_path = tmp_dir + File.separator + "test1";
    final File file = new File(file_path);
    try {
        file.delete();
    } catch (Exception e) {
    } //cleanup if the file exists from previous test
    //have to put quotes around the path on windows systems      
    final CompletableFuture<BasicMessageBean> future = harvester.onTestSource(
            getTestbucket("/test/script1", Optional.of("touch \"" + file_path + "\""), Optional.empty(),
                    Optional.empty(), new HashMap<String, String>(), new ArrayList<String>()),
            new ProcessingTestSpecBean(10L, 10L), getFakeContext());
    final BasicMessageBean response = future.get();
    assertTrue(response.message(), response.success());

    //test if file was created
    final long curr_time = System.currentTimeMillis();
    while (System.currentTimeMillis() < curr_time + 5000) {
        if (file.exists())
            break;
        Thread.sleep(300);
    }
    assertTrue(file.exists());

    //cleanup
    file.delete();
}

From source file:com.ikanow.aleph2.harvest.script.services.TestScriptHarvestService.java

@Test
public void testRunLocalFile() throws InterruptedException, ExecutionException, IOException {
    //save a file to /tmp/somescript.sh and send that as a bucket param, test it works
    final ScriptHarvestService harvester = new ScriptHarvestService();
    harvester.onInit(getFakeContext());/*  w w  w  .  j  a v  a  2 s  . c  o m*/

    final String tmp_dir = System.getProperty("java.io.tmpdir");
    final String file_path = tmp_dir + File.separator + "test1";
    final File file = new File(file_path);
    try {
        file.delete();
    } catch (Exception e) {
    } //cleanup if the file exists from previous test

    //put the script in a local file
    final String file_script_path = tmp_dir + File.separator + "test1.sh";
    final File file_script = new File(file_script_path);
    try {
        file_script.delete();
    } catch (Exception e) {
    } //cleanup if the file exists from previous test
    file_script.createNewFile();
    IOUtils.write("touch \"" + file_path + "\"", new FileOutputStream(file_script));

    //have to put quotes around the path on windows systems      
    final CompletableFuture<BasicMessageBean> future = harvester.onTestSource(
            getTestbucket("/test/script4", Optional.empty(), Optional.of(file_script_path), Optional.empty(),
                    new HashMap<String, String>(), new ArrayList<String>()),
            new ProcessingTestSpecBean(10L, 10L), getFakeContext());
    final BasicMessageBean response = future.get();
    assertTrue(response.message(), response.success());

    //test if file was created
    final long curr_time = System.currentTimeMillis();
    while (System.currentTimeMillis() < curr_time + 5000) {
        if (file.exists())
            break;
        Thread.sleep(300);
    }
    assertTrue(file.exists());

    //cleanup
    file.delete();
    file_script.delete();
}

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

@Test
public void responseReceiver_handleDelivery_onAPIException_exception()
        throws EncodingException, IOException, InterruptedException, ExecutionException {
    Validator validator = new Validator() {
        @Override/*from   w ww . ja  v a2 s  .  c om*/
        public <T> void validate(T value) throws ApiException, IllegalArgumentException {
            throw new ApiException("boom");
        }
    };
    ResponseReceiverImpl receiver = new ResponseReceiverImpl(serializer, validator, 1, TimeUnit.MINUTES);

    String correlationId = "987654321";
    CompletableFuture<Res> answer = receiver.put(correlationId, Res.class);
    assertFalse(answer.isDone());
    assertFalse(answer.isCompletedExceptionally());

    receiver.handleDelivery(correlationId, serializer.encode(Maps.newHashMap()));
    assertTrue(answer.isDone());
    assertTrue(answer.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        answer.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof ApiException);
        assertEquals("boom", ex.getCause().getMessage());
        throw ex;
    }
}

From source file:io.dropwizard.revolver.resource.RevolverRequestResource.java

private Response executeCommandAsync(final String service, final RevolverHttpApiConfig api,
        final RevolverHttpApiConfig.RequestMethod method, final String path, final HttpHeaders headers,
        final UriInfo uriInfo, final byte[] body, final boolean isDownstreamAsync, final String callMode)
        throws Exception {
    val sanatizedHeaders = new MultivaluedHashMap<String, String>();
    headers.getRequestHeaders().forEach(sanatizedHeaders::put);
    cleanHeaders(sanatizedHeaders, api);
    val httpCommand = RevolverBundle.getHttpCommand(service);
    val requestId = headers.getHeaderString(RevolversHttpHeaders.REQUEST_ID_HEADER);
    val transactionId = headers.getHeaderString(RevolversHttpHeaders.TXN_ID_HEADER);
    val mailBoxId = headers.getHeaderString(RevolversHttpHeaders.MAILBOX_ID_HEADER);
    //Short circuit if it is a duplicate request
    if (persistenceProvider.exists(requestId)) {
        return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity(Collections.singletonMap("message", "Duplicate")).build();
    }/*w  w w. j  a v  a2 s . co  m*/
    persistenceProvider.saveRequest(requestId, mailBoxId,
            RevolverCallbackRequest.builder().api(api.getApi())
                    .mode(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALL_MODE_HEADER))
                    .callbackUri(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALLBACK_URI_HEADER))
                    .method(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALLBACK_METHOD_HEADER))
                    .service(service).path(path).headers(headers.getRequestHeaders())
                    .queryParams(uriInfo.getQueryParameters()).body(body).build());
    CompletableFuture<RevolverHttpResponse> response = httpCommand.executeAsync(RevolverHttpRequest.builder()
            .traceInfo(TraceInfo.builder().requestId(requestId).transactionId(transactionId)
                    .timestamp(System.currentTimeMillis()).build())
            .api(api.getApi()).service(service).path(path).method(method).headers(sanatizedHeaders)
            .queryParams(uriInfo.getQueryParameters()).body(body).build());
    //Async Downstream send accept on request path (Still circuit breaker will kick in. Keep circuit breaker aggressive)
    if (isDownstreamAsync) {
        val result = response.get();
        if (result.getStatusCode() == Response.Status.ACCEPTED.getStatusCode()) {
            persistenceProvider.setRequestState(requestId, RevolverRequestState.REQUESTED);
        } else {
            persistenceProvider.setRequestState(requestId, RevolverRequestState.RESPONDED);
            saveResponse(requestId, result);
        }
        return transform(headers, result, api.getApi(), path, method);
    } else {
        response.thenAcceptAsync(result -> {
            if (result.getStatusCode() == Response.Status.ACCEPTED.getStatusCode()) {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.REQUESTED);
            } else if (result.getStatusCode() == Response.Status.OK.getStatusCode()) {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.RESPONDED);
                saveResponse(requestId, result);
            } else {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.ERROR);
                saveResponse(requestId, result);
            }
            if (callMode != null && callMode.equals(RevolverHttpCommand.CALL_MODE_CALLBACK)) {
                callbackHandler.handle(requestId);
            }
        });
        return Response.accepted().entity(RevolverAckMessage.builder().requestId(requestId)
                .acceptedAt(Instant.now().toEpochMilli()).build()).build();
    }
}

From source file:org.apache.flink.client.program.rest.RestClusterClientTest.java

@Test
public void testListJobs() throws Exception {
    try (TestRestServerEndpoint ignored = createRestServerEndpoint(new TestListJobsHandler())) {
        {/*from w  w  w. j a v a 2 s  .  c  o m*/
            CompletableFuture<Collection<JobStatusMessage>> jobDetailsFuture = restClusterClient.listJobs();
            Collection<JobStatusMessage> jobDetails = jobDetailsFuture.get();
            Iterator<JobStatusMessage> jobDetailsIterator = jobDetails.iterator();
            JobStatusMessage job1 = jobDetailsIterator.next();
            JobStatusMessage job2 = jobDetailsIterator.next();
            Assert.assertNotEquals("The job status should not be equal.", job1.getJobState(),
                    job2.getJobState());
        }
    }
}

From source file:com.ikanow.aleph2.harvest.script.services.TestScriptHarvestService.java

@Test
public void testUserArgs() throws IOException, InterruptedException, ExecutionException, URISyntaxException {
    final ScriptHarvestService harvester = new ScriptHarvestService();
    harvester.onInit(getFakeContext());// w w  w .  j a v  a  2  s .  c  om

    final String tmp_dir = System.getProperty("java.io.tmpdir");
    final String file_path = tmp_dir + File.separator + "test2";
    final File file = new File(file_path);
    try {
        file.delete();
    } catch (Exception e) {
    } //cleanup if the file exists from previous test
    //have to put quotes around the path on windows systems      
    final Map<String, String> args = new HashMap<String, String>();
    args.put("arg1", "my_val");
    final CompletableFuture<BasicMessageBean> future = harvester.onTestSource(
            getTestbucket("/test/script1",
                    Optional.of("touch \"" + file_path + "\"\necho \"$arg1\" >> \"" + file_path + "\""),
                    Optional.empty(), Optional.empty(), args, new ArrayList<String>()),
            new ProcessingTestSpecBean(10L, 10L), getFakeContext());
    final BasicMessageBean response = future.get();
    assertTrue(response.message(), response.success());

    //test if file was created      
    final long curr_time = System.currentTimeMillis();
    while (System.currentTimeMillis() < curr_time + 5000) {
        if (file.exists())
            break;
        Thread.sleep(300);
    }
    assertTrue(file.exists());
    //check it has our arg written to it
    final String file_str = IOUtils.toString(new FileInputStream(file), "UTF-8").trim();
    System.out.println(file_str);
    assertTrue(file_str.equals(args.get("arg1")));
    //cleanup
    file.delete();
}

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

@Test
public void testCreateScope() throws Exception {
    CompletableFuture<Boolean> scopeStatus;
    scopeStatus = controllerClient.createScope("scope1");
    assertTrue(scopeStatus.get());

    scopeStatus = controllerClient.createScope("scope2");
    AssertExtensions.assertThrows("Server should throw exception", scopeStatus, Throwable -> true);

    scopeStatus = controllerClient.createScope("scope3");
    AssertExtensions.assertThrows("Server should throw exception", scopeStatus, Throwable -> true);

    scopeStatus = controllerClient.createScope("scope4");
    assertFalse(scopeStatus.get());/*w  w  w .  ja  v  a 2s .c  om*/

    scopeStatus = controllerClient.createScope("scope5");
    AssertExtensions.assertThrows("Should throw Exception", scopeStatus, throwable -> true);
}

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

@Test
public void responseReceiver_put_createsFuture_andCleansUpExpires()
        throws InterruptedException, ExecutionException, TimeoutException {
    ResponseReceiver receiver = new ResponseReceiverImpl(serializer, new Validator() {
    }, 100, TimeUnit.MILLISECONDS);
    CompletableFuture<Res> actual = receiver.put("987654321", Res.class);
    assertFalse(actual.isDone());/*from   www  .java2s . co  m*/
    assertFalse(actual.isCompletedExceptionally());

    // wait for expiry timeout
    Thread.sleep(150);
    // trigger cache operations (to evict the record)
    for (int i = 0; i < 1000; i++) {
        receiver.put(UUID.randomUUID().toString(), Res.class);
    }

    exception.expect(ExecutionException.class);
    try {
        actual.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof TimeoutException);
        assertEquals(
                "Request io.ventu.rpc.amqp.AmqpInvokerimplTest$Res with correlationId 987654321 has expired.",
                ex.getCause().getMessage());
        throw ex;
    }
}

From source file:org.apache.flink.client.program.rest.RestClusterClientTest.java

@Test
public void testTriggerSavepoint() throws Exception {
    final String targetSavepointDirectory = "/tmp";
    final String savepointLocationDefaultDir = "/other/savepoint-0d2fb9-8d5e0106041a";
    final String savepointLocationRequestedDir = targetSavepointDirectory + "/savepoint-0d2fb9-8d5e0106041a";

    final TestSavepointHandlers testSavepointHandlers = new TestSavepointHandlers();
    final TestSavepointHandlers.TestSavepointTriggerHandler triggerHandler = testSavepointHandlers.new TestSavepointTriggerHandler(
            null, targetSavepointDirectory, null, null);
    final TestSavepointHandlers.TestSavepointHandler savepointHandler = testSavepointHandlers.new TestSavepointHandler(
            new SavepointInfo(savepointLocationDefaultDir, null),
            new SavepointInfo(savepointLocationRequestedDir, null),
            new SavepointInfo(null, new SerializedThrowable(new RuntimeException("expected"))),
            new RestHandlerException("not found", HttpResponseStatus.NOT_FOUND));

    // fail first HTTP polling attempt, which should not be a problem because of the retries
    final AtomicBoolean firstPollFailed = new AtomicBoolean();
    failHttpRequest = (messageHeaders, messageParameters,
            requestBody) -> messageHeaders instanceof SavepointStatusHeaders
                    && !firstPollFailed.getAndSet(true);

    try (TestRestServerEndpoint ignored = createRestServerEndpoint(triggerHandler, savepointHandler)) {

        JobID id = new JobID();
        {/*from   w  w w  .j  av  a  2s  .c o m*/
            CompletableFuture<String> savepointPathFuture = restClusterClient.triggerSavepoint(id, null);
            String savepointPath = savepointPathFuture.get();
            assertEquals(savepointLocationDefaultDir, savepointPath);
        }

        {
            CompletableFuture<String> savepointPathFuture = restClusterClient.triggerSavepoint(id,
                    targetSavepointDirectory);
            String savepointPath = savepointPathFuture.get();
            assertEquals(savepointLocationRequestedDir, savepointPath);
        }

        {
            try {
                restClusterClient.triggerSavepoint(id, null).get();
                fail("Expected exception not thrown.");
            } catch (ExecutionException e) {
                final Throwable cause = e.getCause();
                assertThat(cause, instanceOf(SerializedThrowable.class));
                assertThat(((SerializedThrowable) cause).deserializeError(ClassLoader.getSystemClassLoader())
                        .getMessage(), equalTo("expected"));
            }
        }

        try {
            restClusterClient.triggerSavepoint(new JobID(), null).get();
            fail("Expected exception not thrown.");
        } catch (final ExecutionException e) {
            assertTrue("RestClientException not in causal chain",
                    ExceptionUtils.findThrowable(e, RestClientException.class).isPresent());
        }
    }
}

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

@Test
public void testIsSegmentValid() throws Exception {
    CompletableFuture<Boolean> segmentOpen;
    segmentOpen = controllerClient.isSegmentOpen(new Segment("scope1", "stream1", 0));
    assertTrue(segmentOpen.get());

    segmentOpen = controllerClient.isSegmentOpen(new Segment("scope1", "stream2", 0));
    assertFalse(segmentOpen.get());//from  w w  w. jav  a2s. c o m

    segmentOpen = controllerClient.isSegmentOpen(new Segment("scope1", "stream3", 0));
    AssertExtensions.assertThrows("Should throw Exception", segmentOpen, throwable -> true);
}