List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:com.android.tools.idea.diagnostics.crash.GoogleCrash.java
@Override @NotNull//from ww w .j a v a2 s . c o m public CompletableFuture<String> submit(@NotNull CrashReport report, boolean userReported) { if (!userReported) { // all non user reported crash events are rate limited on the client side if (!myRateLimiter.tryAcquire()) { CompletableFuture<String> f = new CompletableFuture<>(); f.completeExceptionally(new RuntimeException("Exceeded Quota of crashes that can be reported")); return f; } } Map<String, String> parameters = getDefaultParameters(); if (report.version != null) { parameters.put(KEY_VERSION, report.version); } parameters.put(KEY_PRODUCT_ID, report.productId); MultipartEntityBuilder builder = newMultipartEntityBuilderWithKv(parameters); report.serialize(builder); return submit(builder.build()); }
From source file:org.apache.pulsar.client.impl.ConnectionPool.java
private CompletableFuture<ClientCnx> createConnection(InetSocketAddress address, int connectionKey) { if (log.isDebugEnabled()) { log.debug("Connection for {} not found in cache", address); }/*w w w. ja v a2s .c o m*/ final CompletableFuture<ClientCnx> cnxFuture = new CompletableFuture<ClientCnx>(); // Trigger async connect to broker bootstrap.connect(address).addListener((ChannelFuture future) -> { if (!future.isSuccess()) { log.warn("Failed to open connection to {} : {}", address, future.cause().getClass().getSimpleName()); cnxFuture.completeExceptionally(new PulsarClientException(future.cause())); cleanupConnection(address, connectionKey, cnxFuture); return; } log.info("[{}] Connected to server", future.channel()); future.channel().closeFuture().addListener(v -> { // Remove connection from pool when it gets closed if (log.isDebugEnabled()) { log.debug("Removing closed connection from pool: {}", v); } cleanupConnection(address, connectionKey, cnxFuture); }); // We are connected to broker, but need to wait until the connect/connected handshake is // complete final ClientCnx cnx = (ClientCnx) future.channel().pipeline().get("handler"); if (!future.channel().isActive() || cnx == null) { if (log.isDebugEnabled()) { log.debug("[{}] Connection was already closed by the time we got notified", future.channel()); } cnxFuture.completeExceptionally(new ChannelException("Connection already closed")); return; } cnx.connectionFuture().thenRun(() -> { if (log.isDebugEnabled()) { log.debug("[{}] Connection handshake completed", cnx.channel()); } cnxFuture.complete(cnx); }).exceptionally(exception -> { log.warn("[{}] Connection handshake failed: {}", cnx.channel(), exception.getMessage()); cnxFuture.completeExceptionally(exception); cleanupConnection(address, connectionKey, cnxFuture); cnx.ctx().close(); return null; }); }); return cnxFuture; }
From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java
protected MagicCommandOutput timeIt(TimeItOption timeItOption, String codeToExecute, Message message, int executionCount, boolean showResult) { String output = "%s %s per loop (mean std. dev. of %d run, %d loop each)"; if (timeItOption.getNumber() < 0) { return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Number of execution must be bigger then 0"); }/*from w w w . jav a 2 s .co m*/ int number = timeItOption.getNumber() == 0 ? getBestNumber(codeToExecute, showResult, message) : timeItOption.getNumber(); if (timeItOption.getRepeat() == 0) { return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Repeat value must be bigger then 0"); } SimpleEvaluationObject seo = createSimpleEvaluationObject(codeToExecute, kernel, message, executionCount); seo.noResult(); TryResult either = kernel.executeCode(codeToExecute, seo); try { if (either.isError()) { return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Please correct your statement"); } List<Long> allRuns = new ArrayList<>(); List<Long> timings = new ArrayList<>(); CompletableFuture<Boolean> isReady = new CompletableFuture<>(); IntStream.range(0, timeItOption.getRepeat()).forEach(repeatIter -> { IntStream.range(0, number).forEach(numberIter -> { SimpleEvaluationObject seo2 = createSimpleEvaluationObject(codeToExecute, kernel, message, executionCount); seo2.noResult(); Long startOfEvaluationInNanoseconds = System.nanoTime(); TryResult result = kernel.executeCode(codeToExecute, seo2); Long endOfEvaluationInNanoseconds = System.nanoTime(); allRuns.add(endOfEvaluationInNanoseconds - startOfEvaluationInNanoseconds); if (repeatIter == timeItOption.getRepeat() - 1 && numberIter == number - 1) { isReady.complete(true); } }); }); if (isReady.get()) { allRuns.forEach(run -> timings.add(run / number)); //calculating average long average = timings.stream().reduce((aLong, aLong2) -> aLong + aLong2).orElse(0L) / timings.size(); double stdev = Math.pow( timings.stream().map(currentValue -> Math.pow(currentValue - average, 2)) .reduce((aDouble, aDouble2) -> aDouble + aDouble2).orElse(0.0) / timings.size(), 0.5); if (timeItOption.getQuietMode()) { output = ""; } else { output = String.format(output, format(average), format((long) stdev), timeItOption.getRepeat(), number); } return new MagicCommandOutput(MagicCommandOutput.Status.OK, output); } } catch (InterruptedException | ExecutionException e) { return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem with " + e.getMessage()); } return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem with timeIt operations"); }
From source file:org.ulyssis.ipp.control.CommandDispatcher.java
public Result send(Command command) { final CompletableFuture<Result> future = new CompletableFuture<>(); sendAsync(command, (c, r) -> {/*from w w w. ja v a 2s . c o m*/ assert (c == command); future.complete(r); }); try { return future.get(); } catch (InterruptedException e) { return Result.TIMEOUT; } catch (ExecutionException e) { LOG.error("We got an ExecutionException. This should not happen.", e.getCause()); return Result.ERROR; } }
From source file:org.springframework.integration.aggregator.AggregatorTests.java
@Test public void testAggPerfDefaultPartial() throws InterruptedException, ExecutionException, TimeoutException { AggregatingMessageHandler handler = new AggregatingMessageHandler( new DefaultAggregatingMessageGroupProcessor()); handler.setCorrelationStrategy(message -> "foo"); handler.setReleasePartialSequences(true); DirectChannel outputChannel = new DirectChannel(); handler.setOutputChannel(outputChannel); final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>(); outputChannel.subscribe(message -> { Collection<?> payload = (Collection<?>) message.getPayload(); logger.warn("Received " + payload.size()); resultFuture.complete(payload);/*from w ww .ja v a 2s . co m*/ }); SimpleMessageStore store = new SimpleMessageStore(); SimpleMessageGroupFactory messageGroupFactory = new SimpleMessageGroupFactory( SimpleMessageGroupFactory.GroupType.BLOCKING_QUEUE); store.setMessageGroupFactory(messageGroupFactory); handler.setMessageStore(store); StopWatch stopwatch = new StopWatch(); stopwatch.start(); for (int i = 0; i < 120000; i++) { if (i % 10000 == 0) { stopwatch.stop(); logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in " + stopwatch.getLastTaskTimeMillis() + "ms)"); stopwatch.start(); } handler.handleMessage( MessageBuilder.withPayload("foo").setSequenceSize(120000).setSequenceNumber(i + 1).build()); } stopwatch.stop(); logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in " + stopwatch.getLastTaskTimeMillis() + "ms)"); Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS); assertNotNull(result); assertEquals(120000, result.size()); assertThat(stopwatch.getTotalTimeSeconds(), lessThan(60.0)); // actually < 2.0, was many minutes }
From source file:org.mascherl.example.page.MailComposePage.java
@POST @Path("/mail/compose") public CompletableFuture<MascherlAction> composeNew() { String mailUuid = composeMailService.composeNewMail(user); Observable<MascherlPage> composeObservable = compose(mailUuid); CompletableFuture<MascherlPage> completableFuture = new CompletableFuture<>(); composeObservable.subscribe(completableFuture::complete, completableFuture::completeExceptionally); return completableFuture.thenApply( (pageDef) -> Mascherl.navigate(UriBuilder.fromMethod(getClass(), "compose").build(mailUuid)) .renderContainer("content").withPageDef(pageDef)); }
From source file:io.pravega.segmentstore.server.reading.StorageReaderTests.java
private CompletableFuture<StorageReader.Result> sendRequest(StorageReader reader, long offset, int length) { CompletableFuture<StorageReader.Result> requestCompletion = new CompletableFuture<>(); reader.execute(new StorageReader.Request(offset, length, requestCompletion::complete, requestCompletion::completeExceptionally, TIMEOUT)); return requestCompletion; }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void invoke_onOkRequest_correctDataPassedToPublisher() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Req req = new Req(); Map<String, Object> headers = Maps.newHashMap(); headers.put("key", Integer.valueOf(12341234)); Channel channel = mock(Channel.class); doAnswer(invocation -> {// w w w . j ava 2 s.c o m assertEquals(DEFAULT_RPC_EXCHANGE, invocation.getArguments()[0]); assertEquals(Req.class.getName(), invocation.getArguments()[1]); BasicProperties props = (BasicProperties) invocation.getArguments()[2]; assertEquals(instanceId, props.getAppId()); assertEquals(instanceId, props.getReplyTo()); assertEquals(CONTENT_TYPE, props.getContentType()); assertEquals(headers.get("key"), props.getHeaders().get("key")); assertEquals(ENCODING, props.getContentEncoding()); String actual = new String((byte[]) invocation.getArguments()[3]); assertEquals(new String(serializer.encode(req)), actual); return null; }).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, new DefaultRequestRouter(), new UidGenerator() { }, serializer, headers); invoker.invoke(req, Res.class); // make sure it was invoked, otherwise our assertions will be void verify(channel).basicPublish(anyString(), any(), any(), any()); }
From source file:org.apache.bookkeeper.bookie.BookieWriteToJournalTest.java
/** * test that Bookie calls correctly Journal.forceLedger and is able to return the correct LastAddPersisted entry id. *//* w w w. j av a 2 s.c om*/ @Test public void testForceLedger() throws Exception { File journalDir = tempDir.newFolder(); Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(journalDir)); File ledgerDir = tempDir.newFolder(); Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(ledgerDir)); ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setJournalDirName(journalDir.getPath()).setLedgerDirNames(new String[] { ledgerDir.getPath() }); Bookie b = new Bookie(conf); b.start(); long ledgerId = 1; long entryId = 0; Object expectedCtx = "foo"; byte[] masterKey = new byte[64]; CompletableFuture<Long> latchForceLedger1 = new CompletableFuture<>(); CompletableFuture<Long> latchForceLedger2 = new CompletableFuture<>(); CompletableFuture<Long> latchAddEntry = new CompletableFuture<>(); final ByteBuf data = buildEntry(ledgerId, entryId, -1); final long expectedEntryId = entryId; b.forceLedger(ledgerId, (int rc, long ledgerId1, long entryId1, BookieSocketAddress addr, Object ctx) -> { if (rc != BKException.Code.OK) { latchForceLedger1.completeExceptionally(org.apache.bookkeeper.client.BKException.create(rc)); return; } complete(latchForceLedger1, null); }, expectedCtx); result(latchForceLedger1); b.addEntry(data, true /* ackBeforesync */, (int rc, long ledgerId1, long entryId1, BookieSocketAddress addr, Object ctx) -> { if (rc != BKException.Code.OK) { latchAddEntry.completeExceptionally(org.apache.bookkeeper.client.BKException.create(rc)); return; } latchAddEntry.complete(entryId); }, expectedCtx, masterKey); assertEquals(expectedEntryId, result(latchAddEntry).longValue()); // issue a new "forceLedger" b.forceLedger(ledgerId, (int rc, long ledgerId1, long entryId1, BookieSocketAddress addr, Object ctx) -> { if (rc != BKException.Code.OK) { latchForceLedger2.completeExceptionally(org.apache.bookkeeper.client.BKException.create(rc)); return; } complete(latchForceLedger2, null); }, expectedCtx); result(latchForceLedger2); b.shutdown(); }
From source file:org.onlab.nio.service.IOLoopMessaging.java
@Override public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) { CompletableFuture<byte[]> response = new CompletableFuture<>(); Long messageId = messageIdGenerator.incrementAndGet(); responseFutures.put(messageId, response); DefaultMessage message = new DefaultMessage(messageId, localEp, type, payload); try {/*from w w w .j av a 2 s. co m*/ sendAsync(ep, message); } catch (Exception e) { responseFutures.invalidate(messageId); response.completeExceptionally(e); } return response; }