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 shouldAwaitToReadCompletedAndDrainOnAwait() throws Exception { resultQueue.add(new Result("test1")); resultQueue.add(new Result("test2")); resultQueue.add(new Result("test3")); resultQueue.markComplete();// w w w .j ava 2 s .c om // you might want 30 but there are only three final CompletableFuture<List<Result>> future = resultQueue.await(30); assertThat(future.isDone(), is(true)); final List<Result> results = future.get(); assertEquals("test1", results.get(0).getString()); assertEquals("test2", results.get(1).getString()); assertEquals("test3", results.get(2).getString()); assertEquals(3, results.size()); assertThat(resultQueue.isEmpty(), is(true)); }
From source file:example.springdata.jpa.java8.Java8IntegrationTests.java
/** * Here we demonstrate the usage of {@link CompletableFuture} as a result wrapper for asynchronous repository query * methods. Note, that we need to disable the surrounding transaction to be able to asynchronously read the written * data from from another thread within the same test method. *//*w w w .j a v a 2s. c o m*/ @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void supportsCompletableFuturesAsReturnTypeWrapper() throws Exception { repository.save(new Customer("Customer1", "Foo")); repository.save(new Customer("Customer2", "Bar")); CompletableFuture<Void> future = repository.readAllBy().thenAccept(customers -> { assertThat(customers, hasSize(2)); customers.forEach(customer -> log.info(customer.toString())); log.info("Completed!"); }); while (!future.isDone()) { log.info("Waiting for the CompletableFuture to finish..."); TimeUnit.MILLISECONDS.sleep(500); } future.get(); log.info("Done!"); }
From source file:info.archinnov.achilles.it.TestAsyncCRUDSimpleEntity.java
@Test public void should_find_by_id_async() throws Exception { //Given//from www .j a va2 s . co m final long id = RandomUtils.nextLong(0, Long.MAX_VALUE); scriptExecutor.executeScriptTemplate("SimpleEntity/insert_single_row.cql", ImmutableMap.of("id", id, "table", "simple")); final Date date = buildDateKey(); final CountDownLatch latch = new CountDownLatch(1); final CassandraLogAsserter logAsserter = new CassandraLogAsserter(); logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n"); //When final CompletableFuture<Tuple2<SimpleEntity, ExecutionInfo>> tuple2 = manager.crud().findById(id, date) .withResultSetAsyncListener(rs -> { LOGGER.info(CALLED); latch.countDown(); return rs; }).getAsyncWithStats(); //Then latch.await(); final SimpleEntity actual = tuple2.get()._1(); final ExecutionInfo executionInfo = tuple2.get()._2(); assertThat(actual).isNotNull(); assertThat(actual.getConsistencyList()).containsExactly(ConsistencyLevel.QUORUM, ConsistencyLevel.LOCAL_ONE); assertThat(executionInfo.getQueriedHost().isUp()).isTrue(); logAsserter.assertContains("Called - [achilles-default-executor"); }
From source file:org.apache.bookkeeper.stream.storage.impl.TestStorageContainerStoreImpl.java
private <T> void verifyNotFoundException(CompletableFuture<T> future, Status status) throws InterruptedException { try {/*from www . j a v a2s.c om*/ future.get(); } catch (ExecutionException ee) { assertTrue(ee.getCause() instanceof StatusRuntimeException); StatusRuntimeException sre = (StatusRuntimeException) ee.getCause(); assertEquals(status, sre.getStatus()); } }
From source file:org.apache.flink.runtime.blob.BlobServerGetTest.java
/** * [FLINK-6020] Tests that concurrent get operations don't concurrently access the BlobStore to * download a blob.//from w w w.j av a2s. co m * * @param jobId * job ID to use (or <tt>null</tt> if job-unrelated) * @param blobType * whether the BLOB should become permanent or transient */ private void testConcurrentGetOperations(@Nullable final JobID jobId, final BlobKey.BlobType blobType) throws IOException, InterruptedException, ExecutionException { final Configuration config = new Configuration(); config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath()); final BlobStore blobStore = mock(BlobStore.class); final int numberConcurrentGetOperations = 3; final List<CompletableFuture<File>> getOperations = new ArrayList<>(numberConcurrentGetOperations); final byte[] data = { 1, 2, 3, 4, 99, 42 }; doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { File targetFile = (File) invocation.getArguments()[2]; FileUtils.writeByteArrayToFile(targetFile, data); return null; } }).when(blobStore).get(any(JobID.class), any(BlobKey.class), any(File.class)); final ExecutorService executor = Executors.newFixedThreadPool(numberConcurrentGetOperations); try (final BlobServer server = new BlobServer(config, blobStore)) { server.start(); // upload data first final BlobKey blobKey = put(server, jobId, data, blobType); // now try accessing it concurrently (only HA mode will be able to retrieve it from HA store!) if (blobType == PERMANENT_BLOB) { // remove local copy so that a transfer from HA store takes place assertTrue(server.getStorageLocation(jobId, blobKey).delete()); } for (int i = 0; i < numberConcurrentGetOperations; i++) { CompletableFuture<File> getOperation = CompletableFuture.supplyAsync(() -> { try { File file = get(server, jobId, blobKey); // check that we have read the right data validateGetAndClose(new FileInputStream(file), data); return file; } catch (IOException e) { throw new CompletionException( new FlinkException("Could not read blob for key " + blobKey + '.', e)); } }, executor); getOperations.add(getOperation); } CompletableFuture<Collection<File>> filesFuture = FutureUtils.combineAll(getOperations); filesFuture.get(); } finally { executor.shutdownNow(); } }
From source file:org.onosproject.drivers.odtn.openconfig.TerminalDeviceDiscovery.java
/** * Returns a list of PortDescriptions for the device. * * @return a list of descriptions./*from w w w .j a v a2 s . c o m*/ * * The RPC reply follows the following pattern: * //CHECKSTYLE:OFF * <pre>{@code * <?xml version="1.0" encoding="UTF-8"?> * <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="7"> * <data> * <components xmlns="http://openconfig.net/yang/platform"> * <component>.... * </component> * <component>.... * </component> * </components> * </data> * </rpc-reply> * }</pre> * //CHECKSTYLE:ON */ @Override public List<PortDescription> discoverPortDetails() { try { NetconfSession session = getNetconfSession(did()); /* Note: the method may get called before the netconf session is established 2018-05-24 14:01:43,607 | INFO event NetworkConfigEvent{time=2018-05-24T14:01:43.602Z, type=CONFIG_ADDED, .... configClass=class org.onosproject.netconf.config.NetconfDeviceConfig 2018-05-24 14:01:43,623 | INFO | vice-installer-2 | TerminalDeviceDiscovery TerminalDeviceDiscovery::discoverPortDetails netconf:127.0.0.1:830 2018-05-24 14:01:43,624 | ERROR | vice-installer-2 | TerminalDeviceDiscovery org.onosproject.onos-drivers-metrohaul - 1.14.0.SNAPSHOT | Exception discoverPortDetails() 2018-05-24 14:01:43,631 | INFO | vice-installer-1 | NetconfControllerImpl Creating NETCONF session to netconf:127.0.0.1:830 with apache-mina */ if (session == null) { log.error("discoverPortDetails called with null session for {}", did()); return ImmutableList.of(); } CompletableFuture<String> fut = session.rpc(getDeviceComponentsBuilder()); String rpcReply = fut.get(); XMLConfiguration xconf = (XMLConfiguration) XmlConfigParser.loadXmlString(rpcReply); xconf.setExpressionEngine(new XPathExpressionEngine()); HierarchicalConfiguration components = xconf.configurationAt("data/components"); return parsePorts(components); } catch (Exception e) { log.error("Exception discoverPortDetails() {}", did(), e); return ImmutableList.of(); } }
From source file:org.apache.servicecomb.foundation.vertx.http.TestVertxServerResponseToHttpServletResponse.java
@Test public void sendPart_openInputStreamFailed(@Mocked Part part) throws IOException, InterruptedException, ExecutionException { IOException ioException = new IOException("forbid open stream"); new Expectations() { {//from w ww . j av a 2s .c om part.getInputStream(); result = ioException; } }; CompletableFuture<Void> future = response.sendPart(part); expectedException.expect(ExecutionException.class); expectedException.expectCause(Matchers.sameInstance(ioException)); future.get(); }
From source file:org.apache.servicecomb.foundation.vertx.http.TestVertxServerResponseToHttpServletResponse.java
@Test public void sendPart_inputStreamBreak(@Mocked Part part, @Mocked InputStream inputStream) throws IOException, InterruptedException, ExecutionException { IOException ioException = new IOException("forbid read"); new Expectations() { {//from ww w .ja v a 2s . c om part.getInputStream(); result = inputStream; inputStream.read((byte[]) any); result = ioException; } }; CompletableFuture<Void> future = response.sendPart(part); expectedException.expect(ExecutionException.class); expectedException.expectCause(Matchers.sameInstance(ioException)); future.get(); }
From source file:org.apache.bookkeeper.stream.storage.impl.TestStorageContainerStoreImpl.java
@Test public void testCreateNamespaceMockRootStorageContainerStore() throws Exception { String colName = "test-create-namespace-mock-root-storage-container-store"; CreateNamespaceResponse createResp = CreateNamespaceResponse.newBuilder() .setCode(StatusCode.NAMESPACE_EXISTS).build(); CreateNamespaceRequest request = createCreateNamespaceRequest(colName, namespaceConf); when(mockRangeStoreService.createNamespace(request)) .thenReturn(CompletableFuture.completedFuture(createResp)); CompletableFuture<CreateNamespaceResponse> createRespFuture = fromListenableFuture( rootRangeService.createNamespace(request)); assertTrue(createResp == createRespFuture.get()); verify(mockRangeStoreService, times(1)).createNamespace(request); }
From source file:org.apache.bookkeeper.stream.storage.impl.TestStorageContainerStoreImpl.java
@Test public void testPutMockStorageContainer() throws Exception { PutResponse response = createPutResponse(StatusCode.SUCCESS); PutRequest request = createPutRequest(); when(mockRangeStoreService.put(request)).thenReturn(CompletableFuture.completedFuture(response)); CompletableFuture<PutResponse> future = fromListenableFuture(tableService.put(request)); verify(mockRangeStoreService, times(1)).put(eq(request)); assertTrue(response == future.get()); }