List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:com.devicehive.service.DeviceCommandService.java
public CompletableFuture<DeviceCommand> insert(DeviceCommandWrapper commandWrapper, DeviceVO device, UserVO user) {//w ww . ja v a2s. c om DeviceCommand command = convertWrapperToCommand(commandWrapper, device, user); CompletableFuture<Response> future = new CompletableFuture<>(); rpcClient.call(Request.newBuilder().withBody(new CommandInsertRequest(command)) .withPartitionKey(device.getGuid()).build(), new ResponseConsumer(future)); return future.thenApply(r -> ((CommandInsertResponse) r.getBody()).getDeviceCommand()); }
From source file:io.pravega.service.server.host.ZKSegmentContainerMonitorTest.java
@Test public void testStartAndStopContainer() throws Exception { @Cleanup//from ww w . j a v a2 s.co m CuratorFramework zkClient = startClient(); initializeHostContainerMapping(zkClient); SegmentContainerRegistry containerRegistry = createMockContainerRegistry(); @Cleanup ZKSegmentContainerMonitor segMonitor = createContainerMonitor(containerRegistry, zkClient); segMonitor.initialize(Duration.ofSeconds(1)); // Simulate a container that starts successfully. CompletableFuture<ContainerHandle> startupFuture = new CompletableFuture<>(); ContainerHandle containerHandle = mock(ContainerHandle.class); when(containerHandle.getContainerId()).thenReturn(2); when(containerRegistry.startContainer(eq(2), any())).thenReturn(startupFuture); // Now modify the ZK entry. HashMap<Host, Set<Integer>> currentData = deserialize(zkClient, PATH); currentData.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(2)); zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData)); // Container finished starting. startupFuture.complete(containerHandle); verify(containerRegistry, timeout(10000).atLeastOnce()).startContainer(eq(2), any()); Thread.sleep(2000); assertEquals(1, segMonitor.getRegisteredContainers().size()); assertTrue(segMonitor.getRegisteredContainers().contains(2)); // Now modify the ZK entry. Remove container 2 and add 1. HashMap<Host, Set<Integer>> newMapping = new HashMap<>(); newMapping.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(1)); zkClient.setData().forPath(PATH, SerializationUtils.serialize(newMapping)); // Verify that stop is called and only the newly added container is in running state. when(containerRegistry.stopContainer(any(), any())).thenReturn(CompletableFuture.completedFuture(null)); verify(containerRegistry, timeout(10000).atLeastOnce()).stopContainer(any(), any()); // Using wait here to ensure the private data structure is updated. // TODO: Removing dependency on sleep here and other places in this class // - https://github.com/pravega/pravega/issues/1079 Thread.sleep(2000); assertEquals(1, segMonitor.getRegisteredContainers().size()); assertTrue(segMonitor.getRegisteredContainers().contains(1)); }
From source file:org.eclipse.hono.service.AbstractApplication.java
/** * Starts up this application.//from w w w .j av a 2 s . c o m * <p> * The start up process entails the following steps: * <ol> * <li>invoke <em>deployRequiredVerticles</em> to deploy the verticle(s) implementing the service's functionality</li> * <li>invoke <em>deployServiceVerticles</em> to deploy the protocol specific service endpoints</li> * <li>invoke <em>postRegisterServiceVerticles</em> to perform any additional post deployment steps</li> * <li>start the health check server</li> * </ol> * * @param args The command line arguments provided to the application. */ public void run(final ApplicationArguments args) { if (vertx == null) { throw new IllegalStateException("no Vert.x instance has been configured"); } else if (serviceFactories.isEmpty()) { throw new IllegalStateException("no service factory has been configured"); } healthCheckServer = new HealthCheckServer(vertx, config); final Future<Void> future = deployRequiredVerticles(config.getMaxInstances()) .compose(s -> deployServiceVerticles()).compose(s -> postRegisterServiceVerticles()) .compose(s -> healthCheckServer.start()); final CompletableFuture<Void> started = new CompletableFuture<>(); future.setHandler(result -> { if (result.failed()) { started.completeExceptionally(result.cause()); } else { started.complete(null); } }); final int startupTimeoutSeconds = config.getStartupTimeout(); try { log.debug("Waiting for {} seconds to start up", startupTimeoutSeconds); started.get(startupTimeoutSeconds, TimeUnit.SECONDS); } catch (TimeoutException e) { log.error("startup timed out after {} seconds, shutting down ...", startupTimeoutSeconds); shutdown(); } catch (InterruptedException e) { log.error("startup process has been interrupted, shutting down ..."); Thread.currentThread().interrupt(); shutdown(); } catch (ExecutionException e) { log.error("exception occurred during startup, shutting down ...", e); shutdown(); } }
From source file:io.pravega.service.server.host.stat.AutoScaleProcessor.java
private void bootstrapRequestWriters() { CompletableFuture<Void> createWriter = new CompletableFuture<>(); // Starting with initial delay, in case request stream has not been created, to give it time to start // However, we have this wrapped in consumeFailure which means the creation of writer will be retried. // We are introducing a delay to avoid exceptions in the log in case creation of writer is attempted before // creation of requeststream. maintenanceExecutor/* w w w .ja v a 2 s.c o m*/ .schedule(() -> Retry .indefinitelyWithExpBackoff(100, 10, 10000, e -> log.error("error while creating writer for requeststream {}", e)) .runAsync(() -> { if (clientFactory.get() == null) { clientFactory.compareAndSet(null, ClientFactory.withScope( NameUtils.INTERNAL_SCOPE_NAME, configuration.getControllerUri())); } this.writer.set(clientFactory.get().createEventWriter( configuration.getInternalRequestStream(), serializer, writerConfig)); initialized.set(true); // even if there is no activity, keep cleaning up the cache so that scale down can be triggered. // caches do not perform clean up if there is no activity. This is because they do not maintain their // own background thread. maintenanceExecutor.scheduleAtFixedRate(cache::cleanUp, 0, configuration.getCacheCleanup().getSeconds(), TimeUnit.SECONDS); log.debug("bootstrapping auto-scale reporter done"); createWriter.complete(null); return createWriter; }, maintenanceExecutor), 10, TimeUnit.SECONDS); }
From source file:opensnap.repository.MongoRepository.java
public CompletableFuture<Long> count(String key, Object value) { CompletableFuture<Long> future = new CompletableFuture<>(); collection.find(new Document(key, value)).count().register((count, e) -> future.complete(count)); return future; }
From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessor.java
private void bootstrapRequestWriters() { CompletableFuture<Void> createWriter = new CompletableFuture<>(); // Starting with initial delay, in case request stream has not been created, to give it time to start // However, we have this wrapped in consumeFailure which means the creation of writer will be retried. // We are introducing a delay to avoid exceptions in the log in case creation of writer is attempted before // creation of requeststream. maintenanceExecutor.schedule(() -> Retry.indefinitelyWithExpBackoff(100, 10, 10000, e -> { log.warn("error while creating writer for requeststream"); log.debug("error while creating writer for requeststream {}", e); }).runAsync(() -> {//w w w. j a va 2 s. co m if (clientFactory.get() == null) { clientFactory.compareAndSet(null, ClientFactory.withScope(NameUtils.INTERNAL_SCOPE_NAME, configuration.getControllerUri())); } this.writer.set(clientFactory.get().createEventWriter(configuration.getInternalRequestStream(), serializer, writerConfig)); initialized.set(true); // even if there is no activity, keep cleaning up the cache so that scale down can be triggered. // caches do not perform clean up if there is no activity. This is because they do not maintain their // own background thread. maintenanceExecutor.scheduleAtFixedRate(cache::cleanUp, 0, configuration.getCacheCleanup().getSeconds(), TimeUnit.SECONDS); log.info("bootstrapping auto-scale reporter done"); createWriter.complete(null); return createWriter; }, maintenanceExecutor), 10, TimeUnit.SECONDS); }
From source file:io.pravega.segmentstore.server.host.ZKSegmentContainerMonitorTest.java
@Test public void testStartAndStopContainer() throws Exception { @Cleanup//w w w . ja v a2 s . c o m CuratorFramework zkClient = startClient(); initializeHostContainerMapping(zkClient); SegmentContainerRegistry containerRegistry = createMockContainerRegistry(); @Cleanup ZKSegmentContainerMonitor segMonitor = createContainerMonitor(containerRegistry, zkClient); segMonitor.initialize(Duration.ofSeconds(1)); // Simulate a container that starts successfully. CompletableFuture<ContainerHandle> startupFuture = new CompletableFuture<>(); ContainerHandle containerHandle = mock(ContainerHandle.class); when(containerHandle.getContainerId()).thenReturn(2); when(containerRegistry.startContainer(eq(2), any())).thenReturn(startupFuture); // Now modify the ZK entry. HashMap<Host, Set<Integer>> currentData = deserialize(zkClient, PATH); currentData.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(2)); zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData)); // Container finished starting. startupFuture.complete(containerHandle); verify(containerRegistry, timeout(1000).atLeastOnce()).startContainer(eq(2), any()); Thread.sleep(2000); assertEquals(1, segMonitor.getRegisteredContainers().size()); assertTrue(segMonitor.getRegisteredContainers().contains(2)); // Now modify the ZK entry. Remove container 2 and add 1. HashMap<Host, Set<Integer>> newMapping = new HashMap<>(); newMapping.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(1)); zkClient.setData().forPath(PATH, SerializationUtils.serialize(newMapping)); // Verify that stop is called and only the newly added container is in running state. when(containerRegistry.stopContainer(any(), any())).thenReturn(CompletableFuture.completedFuture(null)); verify(containerRegistry, timeout(1000).atLeastOnce()).stopContainer(any(), any()); // Using wait here to ensure the private data structure is updated. // TODO: Removing dependency on sleep here and other places in this class // - https://github.com/pravega/pravega/issues/1079 Thread.sleep(2000); assertEquals(1, segMonitor.getRegisteredContainers().size()); assertTrue(segMonitor.getRegisteredContainers().contains(1)); }
From source file:org.onosproject.tl1.impl.DefaultTl1Controller.java
@Override /**/*from w w w. j ava2 s. c o m*/ * This implementation returns an empty string on failure. */ public CompletableFuture<String> sendMsg(DeviceId deviceId, Tl1Command msg) { log.debug("Sending TL1 message to device {}: {}", deviceId, msg); Tl1Device device = deviceMap.get(deviceId); if (device == null || !device.isConnected() || !mastershipService.isLocalMaster(deviceId)) { return CompletableFuture.completedFuture(StringUtils.EMPTY); } // Create and store completable future, complete it in the channel handler when we receive a response CompletableFuture<String> future = new CompletableFuture<>(); Channel channel = device.channel(); if (!msgMap.containsKey(channel)) { return CompletableFuture.completedFuture(StringUtils.EMPTY); } msgMap.get(channel).put(msg.ctag(), future); // Write message to channel channel.writeAndFlush(Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8)); return future; }
From source file:com.teradata.benchto.driver.execution.ExecutionSynchronizer.java
/** * Executes {@code callable} when time comes. The {@code callable} gets executed immediately, without * offloading to a backghround thread, if execution time requested has already passed. *//*from www. j av a 2 s . c om*/ public <T> CompletableFuture<T> execute(Instant when, Callable<T> callable) { if (!Instant.now().isBefore(when)) { // Run immediately. try { return completedFuture(callable.call()); } catch (Exception e) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } } long delay = Instant.now().until(when, ChronoUnit.MILLIS); CompletableFuture<T> future = new CompletableFuture<>(); executorService.schedule(() -> { try { future.complete(callable.call()); } catch (Throwable e) { future.completeExceptionally(e); throw e; } return null; }, delay, MILLISECONDS); return future; }
From source file:com.devicehive.service.DeviceNotificationService.java
public CompletableFuture<DeviceNotification> insert(final DeviceNotification notification, final DeviceVO device) { List<CompletableFuture<Response>> futures = processDeviceNotification(notification, device).stream() .map(n -> {// w w w .j a v a 2 s .c om CompletableFuture<Response> future = new CompletableFuture<>(); rpcClient.call(Request.newBuilder().withBody(new NotificationInsertRequest(n)) .withPartitionKey(device.getGuid()).build(), new ResponseConsumer(future)); return future; }).collect(Collectors.toList()); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) .thenApply(x -> futures.stream().map(CompletableFuture::join) .map(r -> r.getBody().cast(NotificationInsertResponse.class).getDeviceNotification()) .filter(n -> !SpecialNotifications.DEVICE_UPDATE.equals(n.getNotification())) // we are not going to return DEVICE_UPDATE notification .collect(Collectors.toList()).get(0)); // after filter we should get only one notification }