List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:org.apache.servicecomb.foundation.vertx.stream.PumpFromPart.java
private CompletableFuture<ReadStream<Buffer>> prepareReadStream() { CompletableFuture<ReadStream<Buffer>> future = new CompletableFuture<>(); if (ReadStreamPart.class.isInstance(part)) { future.complete(((ReadStreamPart) part).getReadStream()); return future; }// w w w . j a v a 2s.c o m try { InputStream inputStream = part.getInputStream(); InputStreamToReadStream inputStreamToReadStream = new InputStreamToReadStream(context, inputStream, true); inputStreamToReadStream.pause(); future.complete(inputStreamToReadStream); } catch (IOException e) { future.completeExceptionally(e); } return future; }
From source file:org.apache.hadoop.hbase.client.AsyncRegionLocator.java
CompletableFuture<HRegionLocation> getRegionLocation(TableName tableName, byte[] row, boolean reload) { CompletableFuture<HRegionLocation> future = new CompletableFuture<>(); try {/* ww w. jav a 2 s. c o m*/ future.complete(conn.getRegionLocation(tableName, row, reload)); } catch (IOException e) { future.completeExceptionally(e); } return future; }
From source file:org.apache.bookkeeper.mledger.offload.OffloaderUtils.java
/** * Extract the Pulsar offloader class from a offloader archive. * * @param narPath nar package path// www . ja v a2 s.co m * @return the offloader class name * @throws IOException when fail to retrieve the pulsar offloader class */ static Pair<NarClassLoader, LedgerOffloaderFactory> getOffloaderFactory(String narPath) throws IOException { NarClassLoader ncl = NarClassLoader.getFromArchive(new File(narPath), Collections.emptySet()); String configStr = ncl.getServiceDefinition(PULSAR_OFFLOADER_SERVICE_NAME); OffloaderDefinition conf = ObjectMapperFactory.getThreadLocalYaml().readValue(configStr, OffloaderDefinition.class); if (StringUtils.isEmpty(conf.getOffloaderFactoryClass())) { throw new IOException(String.format( "The '%s' offloader does not provide an offloader factory implementation", conf.getName())); } try { // Try to load offloader factory class and check it implements Offloader interface Class factoryClass = ncl.loadClass(conf.getOffloaderFactoryClass()); CompletableFuture<LedgerOffloaderFactory> loadFuture = new CompletableFuture<>(); Thread loadingThread = new Thread(() -> { Thread.currentThread().setContextClassLoader(ncl); log.info("Loading offloader factory {} using class loader {}", factoryClass, ncl); try { Object offloader = factoryClass.newInstance(); if (!(offloader instanceof LedgerOffloaderFactory)) { throw new IOException("Class " + conf.getOffloaderFactoryClass() + " does not implement interface " + LedgerOffloaderFactory.class.getName()); } loadFuture.complete((LedgerOffloaderFactory) offloader); } catch (Throwable t) { loadFuture.completeExceptionally(t); } }, "load-factory-" + factoryClass); try { loadingThread.start(); return Pair.of(ncl, loadFuture.get()); } finally { loadingThread.join(); } } catch (Throwable t) { rethrowIOException(t); } return null; }
From source file:io.pravega.client.segment.impl.SegmentOutputStreamFactoryImpl.java
@Override public SegmentOutputStream createOutputStreamForTransaction(Segment segment, UUID txId, Consumer<Segment> segmentSealedCallback, EventWriterConfig config) { CompletableFuture<String> name = new CompletableFuture<>(); FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override// w w w .j a va2 s. co m public void connectionDropped() { name.completeExceptionally(new ConnectionClosedException()); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { name.completeExceptionally(new NotImplementedException()); } @Override public void transactionInfo(WireCommands.TransactionInfo info) { name.complete(info.getTransactionName()); } @Override public void processingFailure(Exception error) { name.completeExceptionally(error); } }; val connectionFuture = controller.getEndpointForSegment(segment.getScopedName()) .thenCompose((PravegaNodeUri endpointForSegment) -> { return cf.establishConnection(endpointForSegment, replyProcessor); }); connectionFuture.thenAccept((ClientConnection connection) -> { try { connection.send(new WireCommands.GetTransactionInfo(1, segment.getScopedName(), txId)); } catch (ConnectionFailedException e) { throw new RuntimeException(e); } }).exceptionally(t -> { name.completeExceptionally(t); return null; }); name.whenComplete((s, e) -> { getAndHandleExceptions(connectionFuture, RuntimeException::new).close(); }); return new SegmentOutputStreamImpl(getAndHandleExceptions(name, RuntimeException::new), controller, cf, UUID.randomUUID(), segmentSealedCallback, getRetryFromConfig(config)); }
From source file:opensnap.repository.MongoRepository.java
public CompletableFuture<T> insert(T elem) { CompletableFuture<T> future = new CompletableFuture<>(); try {// www.j a v a 2 s. c o m Document doc = Document.valueOf(mapper.writeValueAsString(elem)); collection.insert(doc).register((result, e) -> { if (result != null && result.wasAcknowledged()) { elem.setId(doc.getObjectId("_id")); future.complete(elem); } else { logger.error("Error while creating a new document in insert() : " + doc.toString(), e); future.cancel(true); } }); } catch (JsonProcessingException e) { logger.error("Error while creating element " + elem.toString() + " in insert()", e); future.cancel(true); } return future; }
From source file:com.devicehive.websockets.WebSocketApiInfoHandlerTest.java
@Test public void shouldReturnApiInfo() throws Exception { final String requestId = "62345vxgsa5"; CompletableFuture<TextMessage> future = new CompletableFuture<>(); new StandardWebSocketClient().doHandshake(new TextWebSocketHandler() { @Override/*from w w w . ja va 2 s. c o m*/ protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { future.complete(message); } }, wsBaseUri() + "/websocket/client").addCallback(session -> { JsonObject apiInfoRequest = JsonFixture.createWsCommand("server/info", requestId); try { session.sendMessage(new TextMessage(gson.toJson(apiInfoRequest))); } catch (IOException e) { throw new RuntimeException(e); } }, future::completeExceptionally); future.thenAccept(response -> { JsonObject jsonResp = gson.fromJson(response.getPayload(), JsonObject.class); assertThat(jsonResp.get("action").getAsString(), is("server/info")); assertThat(jsonResp.get("requestId").getAsString(), is(requestId)); assertThat(jsonResp.get("status").getAsString(), is("success")); }).exceptionally(e -> { fail(e.getMessage()); return null; }).get(5, TimeUnit.SECONDS); }
From source file:am.ik.categolj3.api.jest.JestIndexer.java
@Async public CompletableFuture<Void> reindex() { log.info("re-indexing ..."); List<Entry> entries = gitStore.loadEntries(); Bulk.Builder bulkBuilder = new Bulk.Builder(); for (Entry entry : entries) { Index index = new Index.Builder(entry).refresh(true).index(Entry.INDEX_NAME).type(Entry.DOC_TYPE) .build();//w w w. j ava2 s . c om bulkBuilder.addAction(index); } try { jestClient.execute(bulkBuilder.build()); log.info("re-indexed!"); return CompletableFuture.completedFuture(null); } catch (Exception e) { CompletableFuture<Void> f = new CompletableFuture<>(); f.completeExceptionally(e); return f; } }
From source file:org.apache.bookkeeper.tests.integration.utils.DockerUtils.java
public static void dumpContainerLogToTarget(DockerClient docker, String containerId) { File output = new File(getTargetDirectory(containerId), "docker.log"); try (FileOutputStream os = new FileOutputStream(output)) { CompletableFuture<Boolean> future = new CompletableFuture<>(); docker.logContainerCmd(containerId).withStdOut(true).withStdErr(true).withTimestamps(true) .exec(new ResultCallback<Frame>() { @Override// w w w .j av a 2 s. c o m public void close() { } @Override public void onStart(Closeable closeable) { } @Override public void onNext(Frame object) { try { os.write(object.getPayload()); } catch (IOException e) { onError(e); } } @Override public void onError(Throwable throwable) { future.completeExceptionally(throwable); } @Override public void onComplete() { future.complete(true); } }); future.get(); } catch (RuntimeException | ExecutionException | IOException e) { LOG.error("Error dumping log for {}", containerId, e); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.info("Interrupted dumping log from container {}", containerId, ie); } }
From source file:ch.rasc.wampspring.testsupport.CompletableFutureWebSocketHandler.java
public CompletableFutureWebSocketHandler(int expectedNoOfResults, JsonFactory jsonFactory) { this.jsonFactory = jsonFactory; this.timeout = getTimeoutValue(); this.welcomeMessageFuture = new CompletableFuture<>(); this.reset(expectedNoOfResults); }
From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessorTest.java
@Test(timeout = 10000) public void scaleTest() { CompletableFuture<Void> result = new CompletableFuture<>(); CompletableFuture<Void> result2 = new CompletableFuture<>(); CompletableFuture<Void> result3 = new CompletableFuture<>(); EventStreamWriter<AutoScaleEvent> writer = createWriter(event -> { if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM1) && event.getDirection() == AutoScaleEvent.UP) { result.complete(null);//from w w w . jav a 2 s . c om } if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM2) && event.getDirection() == AutoScaleEvent.DOWN) { result2.complete(null); } if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM3) && event.getDirection() == AutoScaleEvent.DOWN) { result3.complete(null); } }); AutoScaleProcessor monitor = new AutoScaleProcessor(writer, AutoScalerConfig.builder().with(AutoScalerConfig.MUTE_IN_SECONDS, 0) .with(AutoScalerConfig.COOLDOWN_IN_SECONDS, 0) .with(AutoScalerConfig.CACHE_CLEANUP_IN_SECONDS, 1) .with(AutoScalerConfig.CACHE_EXPIRY_IN_SECONDS, 1).build(), executor, maintenanceExecutor); String streamSegmentName1 = Segment.getScopedName(SCOPE, STREAM1, 0); String streamSegmentName2 = Segment.getScopedName(SCOPE, STREAM2, 0); String streamSegmentName3 = Segment.getScopedName(SCOPE, STREAM3, 0); monitor.notifyCreated(streamSegmentName1, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); monitor.notifyCreated(streamSegmentName2, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); monitor.notifyCreated(streamSegmentName3, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); long twentyminutesback = System.currentTimeMillis() - Duration.ofMinutes(20).toMillis(); monitor.put(streamSegmentName1, new ImmutablePair<>(twentyminutesback, twentyminutesback)); monitor.put(streamSegmentName3, new ImmutablePair<>(twentyminutesback, twentyminutesback)); monitor.report(streamSegmentName1, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 1001, 500, 200, 200); monitor.report(streamSegmentName3, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 0.0, 0.0, 0.0, 0.0); monitor.notifySealed(streamSegmentName1); assertTrue(FutureHelpers.await(result)); assertTrue(FutureHelpers.await(result)); assertTrue(FutureHelpers.await(result3)); }