List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<CreateStreamResponse> checkStreamExists(StreamConfiguration configuration, long timestamp) { CompletableFuture<CreateStreamResponse> result = new CompletableFuture<>(); final long time; final StreamConfiguration config; final Data<Integer> currentState; synchronized (lock) { time = creationTime.get();/*from w w w .jav a 2s . c o m*/ config = this.configuration; currentState = this.state; } if (time != Long.MIN_VALUE) { if (config != null) { handleStreamMetadataExists(timestamp, result, time, config, currentState); } else { result.complete( new CreateStreamResponse(CreateStreamResponse.CreateStatus.NEW, configuration, time)); } } else { result.complete( new CreateStreamResponse(CreateStreamResponse.CreateStatus.NEW, configuration, timestamp)); } return result; }
From source file:org.apache.servicecomb.foundation.vertx.http.ReadStreamPart.java
public <T> CompletableFuture<T> saveAs(Function<Buffer, T> converter) { CompletableFuture<T> future = new CompletableFuture<>(); Buffer buffer = Buffer.buffer(); // if readStream.resume() not run on correct eventloop, will: // 1.create a context task to save last chunk data to buffer // 2.activate connection to read new data // but maybe 2 will run before 1, that will cause lost data or get incorrect data context.runOnContext(V -> {/* w w w . j av a2s . c o m*/ readStream.exceptionHandler(future::completeExceptionally); readStream.handler(buffer::appendBuffer); readStream.endHandler(v -> future.complete(converter.apply(buffer))); readStream.resume(); }); return future; }
From source file:org.apache.pulsar.client.impl.BinaryProtoLookupService.java
private CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> findBroker( InetSocketAddress socketAddress, boolean authoritative, TopicName topicName) { CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> addressFuture = new CompletableFuture<>(); client.getCnxPool().getConnection(socketAddress).thenAccept(clientCnx -> { long requestId = client.newRequestId(); ByteBuf request = Commands.newLookup(topicName.toString(), authoritative, requestId); clientCnx.newLookup(request, requestId).thenAccept(lookupDataResult -> { URI uri = null;/* w w w . j a v a 2 s . c o m*/ try { // (1) build response broker-address if (useTls) { uri = new URI(lookupDataResult.brokerUrlTls); } else { String serviceUrl = lookupDataResult.brokerUrl; uri = new URI(serviceUrl); } InetSocketAddress responseBrokerAddress = InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort()); // (2) redirect to given address if response is: redirect if (lookupDataResult.redirect) { findBroker(responseBrokerAddress, lookupDataResult.authoritative, topicName) .thenAccept(addressPair -> { addressFuture.complete(addressPair); }).exceptionally((lookupException) -> { // lookup failed log.warn("[{}] lookup failed : {}", topicName.toString(), lookupException.getMessage(), lookupException); addressFuture.completeExceptionally(lookupException); return null; }); } else { // (3) received correct broker to connect if (lookupDataResult.proxyThroughServiceUrl) { // Connect through proxy addressFuture.complete(Pair.of(responseBrokerAddress, socketAddress)); } else { // Normal result with direct connection to broker addressFuture.complete(Pair.of(responseBrokerAddress, responseBrokerAddress)); } } } catch (Exception parseUrlException) { // Failed to parse url log.warn("[{}] invalid url {} : {}", topicName.toString(), uri, parseUrlException.getMessage(), parseUrlException); addressFuture.completeExceptionally(parseUrlException); } }).exceptionally((sendException) -> { // lookup failed log.warn("[{}] failed to send lookup request : {}", topicName.toString(), sendException.getMessage(), sendException instanceof ClosedChannelException ? null : sendException); addressFuture.completeExceptionally(sendException); return null; }); }).exceptionally(connectionException -> { addressFuture.completeExceptionally(connectionException); return null; }); return addressFuture; }
From source file:org.apache.hadoop.hbase.client.RawAsyncTableImpl.java
private static <REQ, PREQ, PRESP, RESP> CompletableFuture<RESP> call(HBaseRpcController controller, HRegionLocation loc, ClientService.Interface stub, REQ req, Converter<PREQ, byte[], REQ> reqConvert, RpcCall<PRESP, PREQ> rpcCall, Converter<RESP, HBaseRpcController, PRESP> respConverter) { CompletableFuture<RESP> future = new CompletableFuture<>(); try {/*from w ww. ja va 2s .c o m*/ rpcCall.call(stub, controller, reqConvert.convert(loc.getRegionInfo().getRegionName(), req), new RpcCallback<PRESP>() { @Override public void run(PRESP resp) { if (controller.failed()) { future.completeExceptionally(controller.getFailed()); } else { try { future.complete(respConverter.convert(controller, resp)); } catch (IOException e) { future.completeExceptionally(e); } } } }); } catch (IOException e) { future.completeExceptionally(e); } return future; }
From source file:org.apache.bookkeeper.metadata.etcd.Etcd64bitIdGeneratorTest.java
/** * Test generating id in parallel and ensure there is no duplicated id. *///from ww w . j a v a 2 s . c o m @Test public void testGenerateIdParallel() throws Exception { final int numThreads = 10; @Cleanup("shutdown") ExecutorService executor = Executors.newFixedThreadPool(numThreads); final int numIds = 10000; final AtomicLong totalIds = new AtomicLong(numIds); final Set<Long> ids = Collections.newSetFromMap(new ConcurrentHashMap<>()); final RateLimiter limiter = RateLimiter.create(1000); final CompletableFuture<Void> doneFuture = new CompletableFuture<>(); for (int i = 0; i < numThreads; i++) { executor.submit(() -> { Client client = Client.builder().endpoints(etcdContainer.getClientEndpoint()).build(); Etcd64bitIdGenerator gen = new Etcd64bitIdGenerator(client.getKVClient(), scope); AtomicBoolean running = new AtomicBoolean(true); while (running.get()) { limiter.acquire(); GenericCallbackFuture<Long> genFuture = new GenericCallbackFuture<>(); gen.generateLedgerId(genFuture); genFuture.thenAccept(lid -> { boolean duplicatedFound = !(ids.add(lid)); if (duplicatedFound) { running.set(false); doneFuture.completeExceptionally( new IllegalStateException("Duplicated id " + lid + " generated : " + ids)); return; } else { if (totalIds.decrementAndGet() <= 0) { running.set(false); doneFuture.complete(null); } } }).exceptionally(cause -> { running.set(false); doneFuture.completeExceptionally(cause); return null; }); } }); } FutureUtils.result(doneFuture); assertTrue(totalIds.get() <= 0); assertTrue(ids.size() >= numIds); }
From source file:spring.travel.site.services.HttpClient.java
private <T> CompletableFuture<T> execute(Supplier<Request> requestSupplier, Consumer<Request> requestConsumer, ResponseMapper<T> responseMapper) { CompletableFuture<T> future = new CompletableFuture<>(); try {/*from w w w .j a va 2s . c o m*/ Request request = requestSupplier.get(); requestConsumer.accept(request); asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<T>() { @Override public T onCompleted(Response response) throws Exception { T t = responseMapper.map(response); future.complete(t); return t; } @Override public void onThrowable(Throwable t) { future.completeExceptionally(t); } }); } catch (Exception e) { future.completeExceptionally(e); } return future; }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void invoke_onOkRequest_encodedAndCorrectlyPublishedToAMQP() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Req req = new Req(); Channel channel = mock(Channel.class); 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); CompletableFuture<Res> actual = invoker.invoke(req, Res.class); assertSame(answer, actual);//from w ww .j a va 2s . c o m assertFalse(actual.isDone()); assertFalse(actual.isCompletedExceptionally()); verify(channelProvider).provide(instanceId, receiver); verify(channelProvider).rpcExchange(); verifyNoMoreInteractions(channelProvider); verify(channel).basicPublish(anyString(), any(), any(), any()); verifyNoMoreInteractions(channel); verify(receiver).put(anyString(), any()); verifyNoMoreInteractions(receiver); }
From source file:org.apache.hadoop.hbase.client.example.AsyncClientExample.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "it is valid to pass NULL to CompletableFuture#completedFuture") private CompletableFuture<Void> closeConn() { CompletableFuture<AsyncConnection> f = future.get(); if (f == null) { return CompletableFuture.completedFuture(null); }//from w w w .j ava 2s . c om CompletableFuture<Void> closeFuture = new CompletableFuture<>(); addListener(f, (conn, error) -> { if (error == null) { IOUtils.closeQuietly(conn); } closeFuture.complete(null); }); return closeFuture; }
From source file:de.thingweb.servient.ServientTestHttp.java
@Test public void attachListenerAndsetDirectly() throws Exception { CompletableFuture<Integer> future = new CompletableFuture<>(); thing.onActionInvoke("testaction", (nv) -> { Integer newVal = ContentHelper.ensureClass(nv, Integer.class); future.complete(newVal);// w ww . ja va2s .co m return null; }); TestTools.postHttpJson("http://localhost:8080/things/simplething/testaction", "42"); assertThat("value is 42", future.get(), is(42)); }
From source file:opensnap.repository.MongoRepository.java
public CompletableFuture<List<T>> getAll() { CompletableFuture<List<T>> future = new CompletableFuture<>(); List<T> list = new ArrayList<>(); collection.find(Document.valueOf("{_id:{ $exists: true }}")).forEach((document) -> { try {// w ww.j a va 2 s . com list.add(mapper.readValue(toJson(document), clazz)); } catch (IOException e) { logger.error("Error while parsing document in getAll() : " + document.toString(), e); } }).register((result, e) -> future.complete(list)); return future; }