List of usage examples for java.util.concurrent CompletableFuture get
@SuppressWarnings("unchecked") public T get() throws InterruptedException, ExecutionException
From source file:org.apache.tinkerpop.gremlin.driver.ResultQueueTest.java
@Test public void shouldAwaitFailTheFutureOnMarkError() throws Exception { final CompletableFuture<List<Result>> future = resultQueue.await(4); resultQueue.add(new Result("test1")); resultQueue.add(new Result("test2")); resultQueue.add(new Result("test3")); assertThat(future.isDone(), is(false)); resultQueue.markError(new Exception("no worky")); assertThat(future.isDone(), is(true)); try {/*from www .j a v a 2s. c o m*/ future.get(); } catch (Exception ex) { final Throwable t = ExceptionUtils.getRootCause(ex); assertEquals("no worky", t.getMessage()); } }
From source file:com.ikanow.aleph2.harvest.script.services.TestScriptHarvestService.java
@Test public void testRestartScript() throws InterruptedException, ExecutionException { //start up a long running script that: //checks if file exists //if so, creates a second file //if not creates file, spins forever (gets stuck here) final ScriptHarvestService harvester = new ScriptHarvestService(); harvester.onInit(getFakeContext());//from ww w. java 2 s. co m final String tmp_dir = System.getProperty("java.io.tmpdir"); final String file_path_1 = tmp_dir + File.separator + "test5_1"; final String file_path_2 = tmp_dir + File.separator + "test5_2"; final File file_1 = new File(file_path_1); final File file_2 = new File(file_path_2); try { file_1.delete(); } catch (Exception e) { } //cleanup if the file exists from previous test try { file_2.delete(); } catch (Exception e) { } //cleanup if the file exists from previous test final String script = new StringBuilder().append("if [ -f " + file_path_1 + " ]\n").append("then") .append("\n").append(" touch " + file_path_2).append("\n").append("else").append("\n") .append(" touch " + file_path_1).append("\n").append(" while [ : ]").append("\n").append(" do") .append("\n").append(" sleep 1").append("\n").append(" done").append("\n").append("fi") .append("\n").toString(); final DataBucketBean bucket = getTestbucket("/test/script1", Optional.of(script), Optional.empty(), Optional.empty(), new HashMap<String, String>(), new ArrayList<String>()); final CompletableFuture<BasicMessageBean> future = harvester.onNewSource(bucket, getFakeContext(), true); final BasicMessageBean response = future.get(); assertTrue(response.message(), response.success()); //test if the first file was created final long curr_time_1 = System.currentTimeMillis(); while (System.currentTimeMillis() < curr_time_1 + 5000) { if (file_1.exists()) break; Thread.sleep(300); } assertTrue(file_1.exists()); //test periodicPoll still thinks its running assertTrue(harvester.onPeriodicPoll(bucket, getFakeContext()).get().success()); //restart the source final CompletableFuture<BasicMessageBean> future_restart = harvester.onUpdatedSource(bucket, bucket, true, Optional.empty(), getFakeContext()); final BasicMessageBean response_restart = future_restart.get(); assertTrue(response_restart.message(), response_restart.success()); //test if the 2nd file was created final long curr_time_2 = System.currentTimeMillis(); while (System.currentTimeMillis() < curr_time_2 + 5000) { if (file_2.exists()) break; Thread.sleep(300); } assertTrue(file_2.exists()); //stop the source final CompletableFuture<BasicMessageBean> future_stop = harvester.onUpdatedSource(bucket, bucket, false, Optional.empty(), getFakeContext()); final BasicMessageBean response_stop = future_stop.get(); assertTrue(response_stop.message(), response_stop.success()); //cleanup file_1.delete(); file_2.delete(); }
From source file:co.runrightfast.vertx.demo.testHarness.jmx.DemoMXBeanImpl.java
@Override public String verticleDeployments() { if (getVerticleDeploymentsMessageSender == null) { getVerticleDeploymentsMessageSender = new ProtobufMessageProducer(vertx.eventBus(), EventBusAddress.eventBusAddress(RunRightFastVerticleManager.VERTICLE_ID, "get-verticle-deployments"), getProtobufMessageCodec(GetVerticleDeployments.Request.getDefaultInstance()).get(), metricRegistry);/*from w ww. ja va 2 s .c o m*/ } final CompletableFuture<com.google.protobuf.Message> future = new CompletableFuture(); getVerticleDeploymentsMessageSender.send(GetVerticleDeployments.Request.newBuilder().build(), new DeliveryOptions().setSendTimeout(2000L), responseHandler(future, GetVerticleDeployments.Response.class)); final com.google.protobuf.Message response; try { response = future.get(); } catch (final InterruptedException | ExecutionException ex) { throw new RuntimeException(ex); } // TODO: aggregate GetVerticleDeployments.Response from all RunRightFastVerticleManager instances deployed within the JVm // ping return JsonUtils.toVertxJsonObject(ProtobufUtils.protobuMessageToJson(response)).encodePrettily(); }
From source file:org.springframework.cloud.sleuth.instrument.async.issues.issue410.Issue410Tests.java
public Span completableFutures() throws ExecutionException, InterruptedException { log.info("This task is running with completable future"); CompletableFuture<Span> span1 = CompletableFuture.supplyAsync(() -> { AsyncTask.log.info("First completable future"); return AsyncTask.this.tracer.getCurrentSpan(); }, AsyncTask.this.executor); CompletableFuture<Span> span2 = CompletableFuture.supplyAsync(() -> { AsyncTask.log.info("Second completable future"); return AsyncTask.this.tracer.getCurrentSpan(); }, AsyncTask.this.executor); CompletableFuture<Span> response = CompletableFuture.allOf(span1, span2).thenApply(ignoredVoid -> { AsyncTask.log.info("Third completable future"); Span joinedSpan1 = span1.join(); Span joinedSpan2 = span2.join(); then(joinedSpan2).isNotNull();/*from w ww. j a va2 s. c om*/ then(joinedSpan1).hasTraceIdEqualTo(joinedSpan2.getTraceId()); AsyncTask.log.info("TraceIds are correct"); return joinedSpan2; }); this.span.set(response.get()); return this.span.get(); }
From source file:org.springframework.cloud.sleuth.instrument.async.issues.issue410.Issue410Tests.java
public Span taskScheduler() throws ExecutionException, InterruptedException { log.info("This task is running with completable future"); CompletableFuture<Span> span1 = CompletableFuture.supplyAsync(() -> { AsyncTask.log.info("First completable future"); return AsyncTask.this.tracer.getCurrentSpan(); }, new LazyTraceExecutor(AsyncTask.this.beanFactory, AsyncTask.this.taskScheduler)); CompletableFuture<Span> span2 = CompletableFuture.supplyAsync(() -> { AsyncTask.log.info("Second completable future"); return AsyncTask.this.tracer.getCurrentSpan(); }, new LazyTraceExecutor(AsyncTask.this.beanFactory, AsyncTask.this.taskScheduler)); CompletableFuture<Span> response = CompletableFuture.allOf(span1, span2).thenApply(ignoredVoid -> { AsyncTask.log.info("Third completable future"); Span joinedSpan1 = span1.join(); Span joinedSpan2 = span2.join(); then(joinedSpan2).isNotNull();/*from w w w. j a v a2s . c o m*/ then(joinedSpan1).hasTraceIdEqualTo(joinedSpan2.getTraceId()); AsyncTask.log.info("TraceIds are correct"); return joinedSpan2; }); this.span.set(response.get()); return this.span.get(); }
From source file:com.ikanow.aleph2.storage_service_hdfs.services.TestHdfsDataWriteService.java
@Test public void test_writerService_basics() { HfdsDataWriteService<TestBean> write_service = getWriter("/test/writer/basics"); // First off a bunch of top level trivial calls {//from www .j ava 2 s .com try { write_service.getCrudService(); fail("Should have errored on getCrudService"); } catch (Exception e) { } CompletableFuture<Long> cf = write_service.countObjects(); try { cf.get(); fail("Should have errored on getCrudService"); } catch (Exception e) { } HfdsDataWriteService<JsonNode> write_service_json = (HfdsDataWriteService<JsonNode>) write_service .getRawService(); assertEquals(write_service_json._bucket, write_service._bucket); assertEquals(Optional.empty(), write_service.getUnderlyingPlatformDriver(String.class, Optional.empty())); } // Check the batch service isn't loaded assertTrue("Writer not set", !write_service._writer.isSet()); }
From source file:org.apache.pulsar.functions.worker.rest.api.FunctionsImpl.java
private Response updateRequest(FunctionMetaData functionMetaData, InputStream uploadedInputStream) { // Upload to bookkeeper try {// www. j a v a 2 s. co m log.info("Uploading function package to {}", functionMetaData.getPackageLocation()); Utils.uploadToBookeeper(worker().getDlogNamespace(), uploadedInputStream, functionMetaData.getPackageLocation().getPackagePath()); } catch (IOException e) { log.error("Error uploading file {}", functionMetaData.getPackageLocation(), e); return Response.serverError().type(MediaType.APPLICATION_JSON).entity(new ErrorData(e.getMessage())) .build(); } // Submit to FMT FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager(); CompletableFuture<RequestResult> completableFuture = functionMetaDataManager .updateFunction(functionMetaData); RequestResult requestResult = null; try { requestResult = completableFuture.get(); if (!requestResult.isSuccess()) { return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON) .entity(new ErrorData(requestResult.getMessage())).build(); } } catch (ExecutionException e) { return Response.serverError().type(MediaType.APPLICATION_JSON) .entity(new ErrorData(e.getCause().getMessage())).build(); } catch (InterruptedException e) { return Response.status(Status.REQUEST_TIMEOUT).type(MediaType.APPLICATION_JSON) .entity(new ErrorData(e.getCause().getMessage())).build(); } return Response.status(Status.OK).build(); }
From source file:org.apache.pulsar.functions.worker.rest.api.FunctionsImpl.java
@DELETE @Path("/{tenant}/{namespace}/{functionName}") public Response deregisterFunction(final @PathParam("tenant") String tenant, final @PathParam("namespace") String namespace, final @PathParam("functionName") String functionName) { // validate parameters try {//from www .j av a2s .c om validateDeregisterRequestParams(tenant, namespace, functionName); } catch (IllegalArgumentException e) { log.error("Invalid deregister function request @ /{}/{}/{}", tenant, namespace, functionName, e); return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON) .entity(new ErrorData(e.getMessage())).build(); } FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager(); if (!functionMetaDataManager.containsFunction(tenant, namespace, functionName)) { log.error("Function to deregister does not exist @ /{}/{}/{}", tenant, namespace, functionName); return Response.status(Status.NOT_FOUND).type(MediaType.APPLICATION_JSON) .entity(new ErrorData(String.format("Function %s doesn't exist", functionName))).build(); } CompletableFuture<RequestResult> completableFuture = functionMetaDataManager.deregisterFunction(tenant, namespace, functionName); RequestResult requestResult = null; try { requestResult = completableFuture.get(); if (!requestResult.isSuccess()) { return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON) .entity(new ErrorData(requestResult.getMessage())).build(); } } catch (ExecutionException e) { log.error("Execution Exception while deregistering function @ /{}/{}/{}", tenant, namespace, functionName, e); return Response.serverError().type(MediaType.APPLICATION_JSON) .entity(new ErrorData(e.getCause().getMessage())).build(); } catch (InterruptedException e) { log.error("Interrupted Exception while deregistering function @ /{}/{}/{}", tenant, namespace, functionName, e); return Response.status(Status.REQUEST_TIMEOUT).type(MediaType.APPLICATION_JSON).build(); } return Response.status(Status.OK).entity(requestResult.toJson()).build(); }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void invoke_onOkRequest_onIOException_futureCompletesExceptionally() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Req req = new Req(); Channel channel = mock(Channel.class); doAnswer(invocation -> {/*from www .ja v a2 s.c o m*/ throw new IOException("boom"); }).when(channel).basicPublish(anyString(), any(), any(), any()); CompletableFuture<Res> answer = new CompletableFuture<>(); ResponseReceiver receiver = mock(ResponseReceiver.class); doReturn(answer).when(receiver).put(anyString(), any()); ChannelProvider channelProvider = mock(ChannelProvider.class); doReturn(channel).when(channelProvider).provide(instanceId, receiver); doReturn(DEFAULT_RPC_EXCHANGE).when(channelProvider).rpcExchange(); RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver); CompletableFuture<Res> actual = invoker.invoke(req, Res.class); assertSame(answer, actual); assertTrue(actual.isDone()); assertTrue(actual.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { actual.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof IOException); throw ex; } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void invoke_onNokRequest_onIllegalArgEx_futureCompletesExceptionally() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Req req = new Req(); Channel channel = mock(Channel.class); CompletableFuture<Res> answer = new CompletableFuture<>(); ResponseReceiver receiver = mock(ResponseReceiver.class); doReturn(answer).when(receiver).put(anyString(), any()); ChannelProvider channelProvider = mock(ChannelProvider.class); doReturn(channel).when(channelProvider).provide(instanceId, receiver); ObjectMapper mapper = mock(ObjectMapper.class); doThrow(IllegalArgumentException.class).when(mapper).writeValueAsBytes(any()); RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver, new DefaultRequestRouter(), new UidGenerator() { }, new DefaultSerializer(mapper), Maps.newHashMap()); CompletableFuture<Res> actual = invoker.invoke(req, Res.class); assertSame(answer, actual);/*from w w w. j a v a2s . c o m*/ assertTrue(actual.isDone()); assertTrue(actual.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { actual.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof IllegalArgumentException); throw ex; } }