List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void constructor_channelProviderSuppliesChannel() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Channel channel = mock(Channel.class); CompletableFuture<Res> answer = new CompletableFuture<>(); ResponseReceiver receiver = mock(ResponseReceiver.class); ChannelProvider channelProvider = mock(ChannelProvider.class); doReturn(channel).when(channelProvider).provide(instanceId, receiver); new AmqpInvokerImpl(instanceId, channelProvider, receiver); verify(channelProvider).provide(instanceId, receiver); verifyNoMoreInteractions(channelProvider); }
From source file:io.pravega.segmentstore.server.reading.StorageReaderTests.java
/** * Tests the execute method with valid Requests: * * All StreamSegments exist and have enough data. * * All read offsets are valid (but we may choose to read more than the length of the Segment). * * ReadRequests may overlap.// w w w.ja v a 2s .c o m */ @Test public void testValidRequests() throws Exception { final int defaultReadLength = MIN_SEGMENT_LENGTH - 1; final int offsetIncrement = defaultReadLength / 3; @Cleanup InMemoryStorage storage = new InMemoryStorage(executorService()); storage.initialize(1); byte[] segmentData = populateSegment(storage); @Cleanup StorageReader reader = new StorageReader(SEGMENT_METADATA, storage, executorService()); HashMap<StorageReader.Request, CompletableFuture<StorageReader.Result>> requestCompletions = new HashMap<>(); int readOffset = 0; while (readOffset < segmentData.length) { int readLength = Math.min(defaultReadLength, segmentData.length - readOffset); CompletableFuture<StorageReader.Result> requestCompletion = new CompletableFuture<>(); StorageReader.Request r = new StorageReader.Request(readOffset, readLength, requestCompletion::complete, requestCompletion::completeExceptionally, TIMEOUT); reader.execute(r); requestCompletions.put(r, requestCompletion); readOffset += offsetIncrement; } // Check that the read requests returned with the right data. for (val entry : requestCompletions.entrySet()) { StorageReader.Result readData = entry.getValue().join(); StorageReader.Request request = entry.getKey(); int expectedReadLength = Math.min(request.getLength(), (int) (segmentData.length - request.getOffset())); Assert.assertNotNull("No data returned for request " + request, readData); Assert.assertEquals("Unexpected read length for request " + request, expectedReadLength, readData.getData().getLength()); AssertExtensions.assertStreamEquals("Unexpected read contents for request " + request, new ByteArrayInputStream(segmentData, (int) request.getOffset(), expectedReadLength), readData.getData().getReader(), expectedReadLength); } }
From source file:org.apache.distributedlog.impl.subscription.ZKSubscriptionsStore.java
@Override public CompletableFuture<Map<String, DLSN>> getLastCommitPositions() { final CompletableFuture<Map<String, DLSN>> result = new CompletableFuture<Map<String, DLSN>>(); try {//from w ww . j a v a2s . c o m this.zkc.get().getChildren(this.zkPath, false, new AsyncCallback.Children2Callback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { if (KeeperException.Code.NONODE.intValue() == rc) { result.complete(new HashMap<String, DLSN>()); } else if (KeeperException.Code.OK.intValue() != rc) { result.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), path)); } else { getLastCommitPositions(result, children); } } }, null); } catch (ZooKeeperClient.ZooKeeperConnectionException zkce) { result.completeExceptionally(zkce); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); result.completeExceptionally(new DLInterruptedException("getLastCommitPositions was interrupted", ie)); } return result; }
From source file:com.devicehive.handler.notification.NotificationSearchHandlerTest.java
@Test public void shouldFindSingleNotificationByIdAndGuid() throws Exception { NotificationSearchRequest searchRequest = new NotificationSearchRequest(); searchRequest.setId(notifications.get(0).getId()); searchRequest.setGuid(notifications.get(0).getDeviceGuid()); Request request = Request.newBuilder().withPartitionKey(notifications.get(0).getDeviceGuid()) .withBody(searchRequest).build(); CompletableFuture<Response> future = new CompletableFuture<>(); client.call(request, future::complete); Response response = future.get(10, TimeUnit.SECONDS); NotificationSearchResponse responseBody = (NotificationSearchResponse) response.getBody(); assertEquals(1, responseBody.getNotifications().size()); assertEquals(notifications.get(0), responseBody.getNotifications().get(0)); }
From source file:io.pravega.segmentstore.server.reading.StorageReadManagerTests.java
/** * Tests the execute method with valid Requests: * * All StreamSegments exist and have enough data. * * All read offsets are valid (but we may choose to read more than the length of the Segment). * * ReadRequests may overlap./*from ww w.j a va 2s. co m*/ */ @Test public void testValidRequests() throws Exception { final int defaultReadLength = MIN_SEGMENT_LENGTH - 1; final int offsetIncrement = defaultReadLength / 3; @Cleanup Storage storage = InMemoryStorageFactory.newStorage(executorService()); storage.initialize(1); byte[] segmentData = populateSegment(storage); @Cleanup StorageReadManager reader = new StorageReadManager(SEGMENT_METADATA, storage, executorService()); HashMap<StorageReadManager.Request, CompletableFuture<StorageReadManager.Result>> requestCompletions = new HashMap<>(); int readOffset = 0; while (readOffset < segmentData.length) { int readLength = Math.min(defaultReadLength, segmentData.length - readOffset); CompletableFuture<StorageReadManager.Result> requestCompletion = new CompletableFuture<>(); StorageReadManager.Request r = new StorageReadManager.Request(readOffset, readLength, requestCompletion::complete, requestCompletion::completeExceptionally, TIMEOUT); reader.execute(r); requestCompletions.put(r, requestCompletion); readOffset += offsetIncrement; } // Check that the read requests returned with the right data. for (val entry : requestCompletions.entrySet()) { StorageReadManager.Result readData = entry.getValue().join(); StorageReadManager.Request request = entry.getKey(); int expectedReadLength = Math.min(request.getLength(), (int) (segmentData.length - request.getOffset())); Assert.assertNotNull("No data returned for request " + request, readData); Assert.assertEquals("Unexpected read length for request " + request, expectedReadLength, readData.getData().getLength()); AssertExtensions.assertStreamEquals("Unexpected read contents for request " + request, new ByteArrayInputStream(segmentData, (int) request.getOffset(), expectedReadLength), readData.getData().getReader(), expectedReadLength); } }
From source file:org.auraframework.modules.impl.ModulesCompilerJ2V8.java
private ModulesCompilerData compile(String entry, String options) throws Exception { String script = "" + "const compiler = require('" + ModulesCompilerUtil.COMPILER_JS_PATH + "');" + "const promise = compiler.compile('" + entry + "', " + options + ");" + "promise.then(onResultCallback).catch(onErrorCallback);"; CompletableFuture<ModulesCompilerData> future = new CompletableFuture<>(); JavaVoidCallback onErrorCallback = new JavaVoidCallback() { @Override//from w w w . j a v a2 s. c om public void invoke(final V8Object receiver, final V8Array parameters) { String error = parameters.toString(); future.completeExceptionally(new RuntimeException(error)); logger.warning("ModulesCompilerJ2v8: error " + entry + ": " + error); } }; JavaVoidCallback onResultCallback = new JavaVoidCallback() { @Override public void invoke(final V8Object receiver, final V8Array parameters) { ModulesCompilerData data = ModulesCompilerUtil.parseCompilerOutput(parameters.getObject(0)); future.complete(data); } }; NodeJS nodeJS = J2V8Util.createNodeJS(); MemoryManager memoryManager = new MemoryManager(nodeJS.getRuntime()); nodeJS.getRuntime().registerJavaMethod(onErrorCallback, "onErrorCallback"); nodeJS.getRuntime().registerJavaMethod(onResultCallback, "onResultCallback"); File tempScript = ModulesCompilerUtil.createTempScriptFile(script, "temp"); try { nodeJS.exec(tempScript); while (nodeJS.isRunning()) { nodeJS.handleMessage(); } } finally { memoryManager.release(); nodeJS.release(); tempScript.delete(); } return future.get(); }
From source file:io.liveoak.container.BasicServerTest.java
@Test public void testServer() throws Exception { CompletableFuture<StompMessage> peopleCreationNotification = new CompletableFuture<>(); CompletableFuture<StompMessage> bobCreationNotification = new CompletableFuture<>(); StompClient stompClient = new StompClient(); CountDownLatch subscriptionLatch = new CountDownLatch(1); stompClient.connect("localhost", 8080, (client) -> { stompClient.subscribe("/testApp/memory/people/*", (subscription) -> { subscription.onMessage((msg) -> { System.err.println("******* MESSAGE: " + msg); if (msg.headers().get("location").equals("/testApp/memory/people")) { peopleCreationNotification.complete(msg); } else { bobCreationNotification.complete(msg); }//from www . j av a 2 s .c o m }); subscription.onReceipt(() -> { subscriptionLatch.countDown(); }); }); }); subscriptionLatch.await(); Header header = new BasicHeader("Accept", "application/json"); HttpGet getRequest = null; HttpPost postRequest = null; HttpPut putRequest = null; CloseableHttpResponse response = null; System.err.println("TEST #1"); // Root object should exist. getRequest = new HttpGet("http://localhost:8080/testApp/memory"); getRequest.addHeader(header); response = this.httpClient.execute(getRequest); // { // "id" : "memory", // "self" : { // "href" : "/memory" // }, // "content" : [ ] // } assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); ResourceState state = decode(response); assertThat(state).isNotNull(); assertThat(state.members().size()).isEqualTo(0); response.close(); System.err.println("TEST #2"); // people collection should not exist. getRequest = new HttpGet("http://localhost:8080/testApp/memory/people"); response = this.httpClient.execute(getRequest); assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(404); response.close(); System.err.println("TEST #3"); // create people collection with direct PUT putRequest = new HttpPut("http://localhost:8080/testApp/memory/people"); putRequest.setEntity(new StringEntity("{ \"type\": \"collection\" }")); putRequest.setHeader("Content-Type", "application/json"); response = this.httpClient.execute(putRequest); System.err.println("response: " + response); assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201); response.close(); System.err.println("TEST #4"); // people collection should exist now. getRequest = new HttpGet("http://localhost:8080/testApp/memory/people"); response = this.httpClient.execute(getRequest); assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); response.close(); assertThat(peopleCreationNotification.getNow(null)).isNull(); System.err.println("TEST #5"); // people collection should be enumerable from the root getRequest = new HttpGet("http://localhost:8080/testApp/memory?expand=members"); getRequest.addHeader(header); response = this.httpClient.execute(getRequest); // { // "id" : "memory", // "self" : { // "href" : "/memory" // }, // "content" : [ { // "id" : "people", // "self" : { // "href" : "/memory/people" // }, // "content" : [ ] // } ] // } assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); state = decode(response); assertThat(state).isNotNull(); assertThat(state.members().size()).isEqualTo(1); ResourceState memoryCollection = state.members().get(0); assertThat(memoryCollection.id()).isEqualTo("people"); assertThat(memoryCollection.uri().toString()).isEqualTo("/testApp/memory/people"); System.err.println("TEST #6"); // Post a person postRequest = new HttpPost("http://localhost:8080/testApp/memory/people"); postRequest.setEntity(new StringEntity("{ \"name\": \"bob\" }")); postRequest.setHeader("Content-Type", "application/json"); response = httpClient.execute(postRequest); assertThat(response).isNotNull(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201); state = decode(response); assertThat(state).isNotNull(); assertThat(state).isInstanceOf(ResourceState.class); assertThat(state.id()).isNotNull(); assertThat(state.getProperty("name")).isEqualTo("bob"); // check STOMP System.err.println("TEST #STOMP"); StompMessage obj = bobCreationNotification.get(30000, TimeUnit.SECONDS); assertThat(obj).isNotNull(); ResourceState bobObjState = decode(obj.content()); assertThat(bobObjState.getProperty("name")).isEqualTo("bob"); assertThat(state.getProperty(LiveOak.ID)).isEqualTo(bobObjState.getProperty(LiveOak.ID)); response.close(); }
From source file:org.apache.servicecomb.foundation.vertx.stream.PumpFromPart.java
private CompletableFuture<Void> toOutputStreamSync(OutputStream outputStream, boolean autoCloseOutputStream) { CompletableFuture<Void> future = new CompletableFuture<>(); try (InputStream inputStream = part.getInputStream()) { IOUtils.copyLarge(inputStream, outputStream); } catch (Throwable e) { future.completeExceptionally(e); }/* ww w . j av a 2s . com*/ if (autoCloseOutputStream) { try { outputStream.close(); } catch (Throwable e) { future.completeExceptionally(e); } } future.complete(null); return future; }
From source file:com.devicehive.rpcclient.RpcClientActionTest.java
@Test public void testCommandInsertAction() throws Exception { DeviceCommand command = new DeviceCommand(); command.setCommand("test_command"); command.setDeviceGuid(UUID.randomUUID().toString()); CommandInsertRequest insertRequest = new CommandInsertRequest(command); Request request = Request.newBuilder().withPartitionKey(insertRequest.getDeviceCommand().getDeviceGuid()) .withBody(insertRequest).build(); CompletableFuture<Response> future = new CompletableFuture<>(); client.call(request, future::complete); Response response = future.get(10, TimeUnit.SECONDS); CommandInsertResponse responseBody = (CommandInsertResponse) response.getBody(); assertNotNull(responseBody.getDeviceCommand()); }
From source file:com.microsoft.azure.servicebus.samples.receiveloop.ReceiveLoop.java
CompletableFuture receiveMessagesAsync(IMessageReceiver receiver) { CompletableFuture currentTask = new CompletableFuture(); try {//w w w. j a v a2s. c o m CompletableFuture.runAsync(() -> { while (!currentTask.isCancelled()) { try { IMessage message = receiver.receive(Duration.ofSeconds(60)); if (message != null) { // receives message is passed to callback if (message.getLabel() != null && message.getContentType() != null && message.getLabel().contentEquals("Scientist") && message.getContentType().contentEquals("application/json")) { byte[] body = message.getBody(); Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class); System.out.printf( "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s," + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\", \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n", message.getMessageId(), message.getSequenceNumber(), message.getEnqueuedTimeUtc(), message.getExpiresAtUtc(), message.getContentType(), scientist != null ? scientist.get("firstName") : "", scientist != null ? scientist.get("name") : ""); } receiver.completeAsync(message.getLockToken()); } } catch (Exception e) { currentTask.completeExceptionally(e); } } currentTask.complete(null); }); return currentTask; } catch (Exception e) { currentTask.completeExceptionally(e); } return currentTask; }