Java Examples for java.util.concurrent.CompletableFuture
The following java examples will help you to understand the usage of java.util.concurrent.CompletableFuture. These source code samples are taken from different open source projects.
Example 1
| Project: java8-the-missing-tutorial-master File: CompletableFutureExample.java View source code |
public static void main(String[] args) {
CompletableFuture.completedFuture("hello");
CompletableFuture.runAsync(() -> System.out.println("hello"));
CompletableFuture.runAsync(() -> System.out.println("hello"), Executors.newSingleThreadExecutor());
CompletableFuture.supplyAsync(() -> UUID.randomUUID().toString());
CompletableFuture.supplyAsync(() -> UUID.randomUUID().toString(), Executors.newSingleThreadExecutor());
}Example 2
| Project: failsafe-master File: Issue52.java View source code |
public void shouldCancelExecutionViaCompletableFuture() throws Throwable {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
AtomicInteger counter = new AtomicInteger();
CompletableFuture<String> proxyFuture = Failsafe.with(new RetryPolicy().withDelay(10, TimeUnit.MILLISECONDS)).with(scheduler).future( exec -> {
counter.incrementAndGet();
CompletableFuture<String> result = new CompletableFuture<>();
result.completeExceptionally(new RuntimeException());
return result;
});
Thread.sleep(100);
proxyFuture.cancel(true);
int count = counter.get();
assertTrue(proxyFuture.isCancelled());
Asserts.assertThrows(() -> proxyFuture.get(), CancellationException.class);
// Assert that execution has actually stopped
Thread.sleep(20);
assertEquals(count, counter.get());
}Example 3
| Project: play-geolocation-module.edulify.com-master File: GeolocationServiceTest.java View source code |
@Override
public Application provideApplication() {
Geolocation geolocation = new Geolocation(ipAddress, countryCode);
GeolocationProvider provider = Mockito.mock(GeolocationProvider.class);
Mockito.when(provider.get(ipAddress)).thenReturn(CompletableFuture.completedFuture(geolocation));
return new GuiceApplicationBuilder().in(new File(".")).in(Mode.TEST).configure("geolocation.cache.on", true).bindings(bind(GeolocationProvider.class).toInstance(provider)).build();
}Example 4
| Project: rakam-master File: EventMapper.java View source code |
default CompletableFuture<List<Cookie>> mapAsync(EventList events, RequestParams requestParams, InetAddress sourceAddress, HttpHeaders responseHeaders) { List<Cookie> cookies = new ArrayList<>(); CompletableFuture[] futures = null; int futureIndex = 0; for (int i = 0; i < events.events.size(); i++) { Event event = events.events.get(i); CompletableFuture<List<Cookie>> map = mapAsync(event, requestParams, sourceAddress, responseHeaders); if (map == null || map.equals(COMPLETED_EMPTY_FUTURE)) { continue; } CompletableFuture<List<Cookie>> future = map.thenApply( value -> { cookies.addAll(value); return cookies; }); if (futures == null) { futures = new CompletableFuture[events.events.size() - i]; } futures[futureIndex++] = future; } if (futures == null) { return COMPLETED_EMPTY_FUTURE; } else { return CompletableFuture.allOf(futures).thenApply( val -> cookies); } }
Example 5
| Project: femr-master File: ResearchFilter.java View source code |
@Override
public CompletionStage<Result> apply(Function<Http.RequestHeader, CompletionStage<Result>> next, Http.RequestHeader rh) {
//get the research only setting from config file
String researchOnlySetting_String = configuration.getString("settings.researchOnly");
//lets assume it's 0 unless told otherwise
Integer researchOnlySetting_Integer = 0;
try {
researchOnlySetting_Integer = Integer.parseInt(researchOnlySetting_String);
} catch (Exception ex) {
researchOnlySetting_Integer = 0;
}
//they will be stuck on the homepage. These are the actions the user is ALLOWED to take
if (researchOnlySetting_Integer == 1 && !rh.path().contains("/research") && !rh.path().contains("/assets") && !rh.path().contains("/admin") && !rh.path().contains("/login") && !rh.path().contains("/logout") && !rh.path().equals("/"))
return CompletableFuture.completedFuture(Results.redirect(routes.ResearchController.indexGet()));
else {
return next.apply(rh);
}
}Example 6
| Project: infinispan-master File: AsyncMassIndexTest.java View source code |
@Test
public void testListener() throws Exception {
Cache<Integer, Transaction> cache = caches.get(0);
int elements = 50;
populate(elements);
SearchManager searchManager = Search.getSearchManager(cache);
CompletableFuture<Void> future = searchManager.getMassIndexer().startAsync();
final CountDownLatch endLatch = new CountDownLatch(1);
future.whenComplete(( v, t) -> {
endLatch.countDown();
});
endLatch.await();
checkIndex(elements, Transaction.class);
}Example 7
| Project: java-8-lambdas-exercises-master File: CompletableFutureArtistAnalyser.java View source code |
public void isLargerGroup(String artistName, String otherArtistName, Consumer<Boolean> handler) {
CompletableFuture<Long> otherArtistMemberCount = CompletableFuture.supplyAsync(() -> getNumberOfMembers(otherArtistName));
CompletableFuture<Long> artistMemberCount = CompletableFuture.completedFuture(getNumberOfMembers(artistName));
artistMemberCount.thenCombine(otherArtistMemberCount, ( count, otherCount) -> count > otherCount).thenAccept(handler::accept);
}Example 8
| Project: Java8InAction-master File: BestPriceFinder.java View source code |
public void printPricesStream(String product) {
long start = System.nanoTime();
CompletableFuture[] futures = findPricesStream(product).map( f -> f.thenAccept( s -> System.out.println(s + " (done in " + ((System.nanoTime() - start) / 1_000_000) + " msecs)"))).toArray( size -> new CompletableFuture[size]);
CompletableFuture.allOf(futures).join();
System.out.println("All shops have now responded in " + ((System.nanoTime() - start) / 1_000_000) + " msecs");
}Example 9
| Project: webpie-master File: ChainFilters.java View source code |
@Override public CompletableFuture<Action> invoke(MethodMeta meta) { Method method = meta.getMethod(); CompletableFuture<Action> resp = filter.filter(meta, svc).thenApply(( r) -> responseCheck(method, r)); if (resp == null) throw new IllegalStateException("Filter returned null CompletableFuture<Action> which is not allowed=" + filter.getClass() + " after being given request with controller method=" + method); return resp; }
Example 10
| Project: zava-master File: BestPriceFinder.java View source code |
public void printPricesStream(String product) {
long start = System.nanoTime();
CompletableFuture[] futures = findPricesStream(product).map( f -> f.thenAccept( s -> System.out.println(s + " (done in " + ((System.nanoTime() - start) / 1_000_000) + " msecs)"))).toArray( size -> new CompletableFuture[size]);
CompletableFuture.allOf(futures).join();
System.out.println("All shops have now responded in " + ((System.nanoTime() - start) / 1_000_000) + " msecs");
}Example 11
| Project: presto-master File: ShardOrganizer.java View source code |
public CompletableFuture<?> enqueue(OrganizationSet organizationSet) {
shardsInProgress.addAll(organizationSet.getShards());
return runAsync(jobFactory.create(organizationSet), executorService).whenComplete(( none, throwable) -> {
shardsInProgress.removeAll(organizationSet.getShards());
if (throwable == null) {
successCount.update(1);
} else {
log.warn(throwable, "Error running organization job");
failureCount.update(1);
}
});
}Example 12
| Project: asyncrmi-master File: UnexportTest.java View source code |
@Test(timeout = 5000)
@SuppressWarnings("SpellCheckingInspection")
public void asyncUnexportProxy() throws Exception {
exporter.unexport(proxy);
CompletableFuture<Integer> asyncRead = client.asyncRead();
try {
asyncRead.get();
fail("Should throw RemoteException");
} catch (ExecutionException e) {
assertThat((RemoteException) e.getCause(), isA(RemoteException.class));
}
}Example 13
| Project: downlords-faf-client-master File: ClientUpdateServiceImplTest.java View source code |
/**
* Never version is available on server.
*/
@Test
@SuppressWarnings("unchecked")
public void testCheckForUpdateInBackgroundUpdateAvailable() throws Exception {
instance.currentVersion = new ComparableVersion("v0.4.8.0-alpha");
CheckForUpdateTask taskMock = mock(CheckForUpdateTask.class, withSettings().useConstructor());
when(applicationContext.getBean(CheckForUpdateTask.class)).thenReturn(taskMock);
UpdateInfo updateInfo = new UpdateInfo("v0.4.8.1-alpha", "test.exe", new URL("http://www.example.com"), 56098816, new URL("http://www.example.com"));
when(taskMock.getFuture()).thenReturn(CompletableFuture.completedFuture(updateInfo));
instance.checkForUpdateInBackground();
verify(taskService).submitTask(taskMock);
ArgumentCaptor<PersistentNotification> captor = ArgumentCaptor.forClass(PersistentNotification.class);
verify(notificationService).addNotification(captor.capture());
PersistentNotification persistentNotification = captor.getValue();
verify(i18n).get("clientUpdateAvailable.notification", "v0.4.8.1-alpha", Bytes.formatSize(56079360L, i18n.getLocale()));
assertThat(persistentNotification.getSeverity(), is(INFO));
}Example 14
| Project: ecf-master File: AbstractAsyncProxyRemoteService.java View source code |
@SuppressWarnings("unchecked")
protected Object callFuture(AbstractAsyncProxyRemoteCall call, @SuppressWarnings("rawtypes") Class returnType) {
// we callCompletableAsync
if (CompletableFuture.class.isAssignableFrom(returnType)) {
@SuppressWarnings("rawtypes") CompletableFuture result = new CompletableFuture();
callCompletableAsync(call, ( r, hadException, exception) -> {
if (hadException)
result.completeExceptionally(exception);
else
result.complete(r);
});
// And return the CompletableFuture
return result;
}
// IFuture result of callAsync
if (IFuture.class.isAssignableFrom(returnType))
return callAsync(call);
// Else it must be a Future return value
return callFutureAsync(call);
}Example 15
| Project: EnrichmentMapApp-master File: ClusterRankingOption.java View source code |
@Override public CompletableFuture<Optional<Map<Integer, RankValue>>> computeRanking(Collection<Integer> genes) { if (genes.size() < 2) { // The HierarchicalClusterTask requires at least 2 genes return CompletableFuture.completedFuture(Optional.of(Collections.emptyMap())); } HierarchicalClusterTask task = new HierarchicalClusterTask(map, genes, distance.getMetric()); CompletableFuture<Optional<Map<Integer, RankValue>>> future = new CompletableFuture<>(); taskManager.execute(new TaskIterator(task), new TaskObserver() { @Override public void taskFinished(ObservableTask task) { if (task instanceof HierarchicalClusterTask) { HierarchicalClusterTask clusterTask = (HierarchicalClusterTask) task; Optional<Map<Integer, RankValue>> ranking = clusterTask.getActualResults(); future.complete(ranking); } } @Override public void allFinished(FinishStatus finishStatus) { // Don't see why this would ever happen if (!future.isDone()) { future.completeExceptionally(new RuntimeException("Failed")); } } }); return future; }
Example 16
| Project: eventuate-master File: CommonSwaggerConfiguration.java View source code |
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("net.chrisrichardson.eventstore.examples.management.restaurant")).build().pathMapping("/").genericModelSubstitutes(ResponseEntity.class, CompletableFuture.class).alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)), typeResolver.resolve(WildcardType.class))).useDefaultResponseMessages(false);
}Example 17
| Project: java-learning-master File: BestPriceFinder.java View source code |
/**
* �应 CompletableFuture 的 completion 事件
* 把 Util ç±»ä¸çš„ delay 调一下效果更明显
*/
public void printPricesStream(String product) {
long start = System.nanoTime();
CompletableFuture[] futures = findPricesStream(product).map( f -> f.thenAccept( s -> System.out.println(s + " (done in " + ((System.nanoTime() - start) / 1_000_000) + " msecs)"))).toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).join();
System.out.println("All shops have now responded in " + ((System.nanoTime() - start) / 1_000_000) + " msecs");
}Example 18
| Project: Peergos-master File: UserUtil.java View source code |
public static CompletableFuture<UserWithRoot> generateUser(String username, String password, LoginHasher hasher, Salsa20Poly1305 provider, SafeRandom random, Ed25519 signer, Curve25519 boxer, UserGenerationAlgorithm algorithm) { CompletableFuture<byte[]> fut = hasher.hashToKeyBytes(username, password, algorithm); return fut.thenApply( keyBytes -> { byte[] signBytesSeed = Arrays.copyOfRange(keyBytes, 0, 32); byte[] secretBoxBytes = Arrays.copyOfRange(keyBytes, 32, 64); byte[] rootKeyBytes = Arrays.copyOfRange(keyBytes, 64, 96); byte[] secretSignBytes = Arrays.copyOf(signBytesSeed, 64); byte[] publicSignBytes = new byte[32]; signer.crypto_sign_keypair(publicSignBytes, secretSignBytes); byte[] pubilcBoxBytes = new byte[32]; boxer.crypto_box_keypair(pubilcBoxBytes, secretBoxBytes); SigningKeyPair signingKeyPair = new SigningKeyPair(new Ed25519PublicKey(publicSignBytes, signer), new Ed25519SecretKey(secretSignBytes, signer)); BoxingKeyPair boxingKeyPair = new BoxingKeyPair(new Curve25519PublicKey(pubilcBoxBytes, boxer, random), new Curve25519SecretKey(secretBoxBytes, boxer)); SymmetricKey root = new TweetNaClKey(rootKeyBytes, false, provider, random); return new UserWithRoot(signingKeyPair, boxingKeyPair, root); }); }
Example 19
| Project: redis-protocol-master File: Issue24Test.java View source code |
@Test
public void testRestoreBadData() throws Exception {
RedisClient client = new RedisClient("localhost", 6379);
RedisClient.Pipeline pipeline = client.pipeline();
client.multi();
// Use something other than dump-specific serialization to cause an error on restore
CompletableFuture restoreResults = pipeline.restore("testing".getBytes(), 0, "foo".getBytes());
Future<Boolean> execResults = client.exec();
assertTrue(execResults.get());
// to ErrorReply. Should get() throw an Exception instead?
try {
ErrorReply reply = (ErrorReply) restoreResults.get();
fail("Should have thrown an exception");
} catch (ExecutionException re) {
Assert.assertTrue(re.getCause() instanceof RedisException);
} catch (Exception e) {
fail("Should have thrown an ExecutionException");
}
}Example 20
| Project: scalecube-master File: TransportTestUtils.java View source code |
public static void destroyTransport(Transport transport) {
if (transport != null && !transport.isStopped()) {
CompletableFuture<Void> close = new CompletableFuture<>();
transport.stop(close);
try {
close.get(1, TimeUnit.SECONDS);
} catch (Exception ignore) {
LOGGER.warn("Failed to await transport termination");
}
}
}Example 21
| Project: spring-boot-mvc-completablefuture-master File: AsyncTimedAspect.java View source code |
private Object proceed(final ProceedingJoinPoint joinPoint) throws Throwable {
final Object result = joinPoint.proceed();
if (!isCompletableFuture(result)) {
return result;
}
final String description = joinPoint.toString();
final Stopwatch watch = Stopwatch.createStarted();
String initiatingThread = Thread.currentThread().getName();
return ((CompletableFuture<?>) result).thenApply( __ -> {
String executingThread = Thread.currentThread().getName();
watch.stop();
LOG.info("Timed: " + description + " ; " + watch.toString() + " ; Initiating Thread '" + initiatingThread + "' Executing Thread '" + executingThread + "'.");
return __;
});
}Example 22
| Project: spring-rest-master File: AsyncDeferredController.java View source code |
@RequestMapping(value = "/deferred", method = RequestMethod.GET, produces = "text/html")
public DeferredResult<String> executeSlowTask() {
logger.info("Request received");
DeferredResult<String> deferredResult = new DeferredResult<>();
CompletableFuture.supplyAsync(taskService::execute).whenCompleteAsync(( result, throwable) -> deferredResult.setResult(result));
logger.info("Servlet thread released");
return deferredResult;
}Example 23
| Project: vertx-guice-master File: ConfigVerticleTest.java View source code |
@Override
public void setUp() throws Exception {
super.setUp();
CompletableFuture<Void> future = new CompletableFuture<>();
apiConfig = new JsonObject().put("a", "b").put("b", 123).put("c", true);
JsonObject config = new JsonObject().put("guice_binder", ConfigBinder.class.getName()).put(ConfigBinder.GUICE_CONFIG, new JsonObject().put("api", apiConfig));
vertx.deployVerticle("java-guice:" + ConfigVerticle.class.getName(), new DeploymentOptions().setConfig(config), result -> {
if (result.succeeded()) {
future.complete(null);
} else {
future.completeExceptionally(result.cause());
}
});
future.get(200, TimeUnit.SECONDS);
}Example 24
| Project: vertx-hk2-master File: SimpleVerticleTest.java View source code |
@Override
public void setUp() throws Exception {
super.setUp();
CompletableFuture<Void> future = new CompletableFuture<>();
JsonObject config = new JsonObject().put("hk2_binder", Binder.class.getName());
vertx.deployVerticle("java-hk2:" + SimpleVerticle.class.getName(), new DeploymentOptions().setConfig(config), result -> {
if (result.succeeded()) {
future.complete(null);
} else {
future.completeExceptionally(result.cause());
}
});
future.get(2, TimeUnit.SECONDS);
}Example 25
| Project: vertx-jersey-master File: JerseyIntegrationTestBase.java View source code |
protected void init() throws Exception {
locator.init(vertx);
HttpClientOptions clientOptions = new HttpClientOptions().setConnectTimeout(1000);
httpClient = vertx.createHttpClient(clientOptions);
CompletableFuture<String> future = new CompletableFuture<>();
locator.deployJerseyVerticle().then( id -> {
future.complete(id);
return null;
}).otherwise( t -> {
future.completeExceptionally(t);
return null;
});
deploymentID = future.get(10, TimeUnit.SECONDS);
}Example 26
| Project: assertj-core-master File: ShouldNotHaveFailed_create_Test.java View source code |
@Test
public void should_create_error_message() throws Exception {
CompletableFuture<Object> future = new CompletableFuture<Object>();
future.completeExceptionally(new RuntimeException());
String error = shouldNotHaveFailed(future).create(new TestDescription("TEST"));
assertThat(error).isEqualTo(format("[TEST] %n" + "Expecting%n" + " <CompletableFuture[Failed: java.lang.RuntimeException]>%n" + "to not have failed"));
}Example 27
| Project: java8-playground-master File: CreditRatingService2.java View source code |
private void run() throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
log("Start");
int userId = 1;
supplyAsync(() -> getUser(userId), executor).thenApply(this::getCreditRatingFromSystem1).thenAccept(Utils::log);
//
//
// CompletableFuture<User> user = supplyAsync(() -> getUser(userId), executor);
// CompletableFuture<CreditRating> rating1 = user.thenApply(this::getCreditRatingFromSystem1);
// CompletableFuture<CreditRating> rating2 = user.thenApply(this::getCreditRatingFromSystem2);
// rating1.thenCombine(rating2, CreditRating::combine).thenAccept(Utils::log);
////
// CompletableFuture<User> user = supplyAsync(() -> getUser(userId), executor);
// CompletableFuture<CreditRating> rating1 = user.thenApplyAsync(this::getCreditRatingFromSystem1, executor);
// CompletableFuture<CreditRating> rating2 = user.thenApplyAsync(this::getCreditRatingFromSystem2, executor);
// rating1.thenCombine(rating2, CreditRating::combine).thenAccept(Utils::log);
//
// rating1.acceptEither(rating2, Utils::log);
//
// supplyAsync(() -> getUser(userId), executor).thenApply(this::getCreditRatingFromSystem3)
// .thenAccept(Utils::log);
supplyAsync(() -> getUser(userId), executor).thenApply(this::getCreditRatingFromSystem2).thenAccept(Utils::log).whenComplete(( x, e) -> e.printStackTrace());
//
// CompletableFuture<User> uf = new CompletableFuture<>();
// uf.complete(new User(1));
log("End");
Thread.sleep(1000L);
executor.shutdown();
}Example 28
| Project: openjdk-master File: CheckUnsynchronized.java View source code |
public static void main(String[] args) {
Properties props = new Properties();
synchronized (props) {
props.setProperty("key", "value");
System.out.println("contains(value)? " + CompletableFuture.supplyAsync(() -> props.contains("value")).join());
System.out.println("containsKey(key)? " + CompletableFuture.supplyAsync(() -> props.containsKey("key")).join());
System.out.println("containsValue(value)? " + CompletableFuture.supplyAsync(() -> props.containsValue("value")).join());
Enumeration<Object> elems = CompletableFuture.supplyAsync(() -> props.elements()).join();
System.out.println("first value from elements(): " + elems.nextElement());
System.out.println("value from get(): " + CompletableFuture.supplyAsync(() -> props.getProperty("key")).join());
System.out.println("getOrDefault(\"missing\"): " + CompletableFuture.supplyAsync(() -> props.getOrDefault("missing", "default")).join());
System.out.println("isEmpty()? " + CompletableFuture.supplyAsync(() -> props.isEmpty()).join());
Enumeration<Object> keys = CompletableFuture.supplyAsync(() -> props.keys()).join();
System.out.println("first key from keys(): " + keys.nextElement());
System.out.println("size(): " + CompletableFuture.supplyAsync(() -> props.size()).join());
}
}Example 29
| Project: sphere-sunrise-master File: QueryAll.java View source code |
public CompletionStage<List<T>> run(final SphereClient client) {
return queryPage(client, 0).thenCompose( result -> {
final List<CompletableFuture<List<T>>> futureResults = new ArrayList<>();
futureResults.add(completedFuture(result.getResults()));
futureResults.addAll(queryNextPages(client, result.getTotal()));
return transformListOfFuturesToFutureOfLists(futureResults);
});
}Example 30
| Project: blog-microservices-master File: ProductCompositeService.java View source code |
// @RequestMapping("/{productId}")
public ResponseEntity<ProductAggregated> getProductAsync(@PathVariable int productId) {
try {
CompletableFuture<Product> productFuture = supplyAsync(() -> getBasicProductInfo(productId));
CompletableFuture<List<Recommendation>> recommendationListFuture = supplyAsync(() -> getRecommendations(productId));
CompletableFuture<List<Review>> reviewListFuture = supplyAsync(() -> getReviews(productId));
LOG.info("Asynch, allOf.join...");
allOf(productFuture, recommendationListFuture, reviewListFuture).join();
LOG.info("Asynch, create result and return...");
return util.createOkResponse(new ProductAggregated(productFuture.get(), recommendationListFuture.get(), reviewListFuture.get(), util.getServiceAddress()));
} catch (InterruptedExceptionExecutionException | e) {
LOG.error("getProductAsync error", e);
throw new RuntimeException(e);
}
}Example 31
| Project: blobkeeper-master File: Streams.java View source code |
@NotNull
public static <T> Stream<ResultWrapper<T>> parallelize(int n, @NotNull Supplier<T> supplier) {
// operations will be executed in parallel
List<CompletableFuture<ResultWrapper<T>>> results = IntStream.iterate(0, i -> i + 1).limit(n).boxed().map( ignored -> CompletableFuture.supplyAsync(new ResultSupplier<>(supplier), parallelExecutor)).collect(toImmutableList());
return collect(results);
}Example 32
| Project: accumulo-master File: CompletableFutureUtilTest.java View source code |
@Test
public void testMerge() throws Exception {
ExecutorService es = Executors.newFixedThreadPool(3);
try {
for (int n : new int[] { 1, 2, 3, 997, 1000 }) {
List<CompletableFuture<Integer>> futures = new ArrayList<>();
for (int i = 1; i <= n; i++) {
final int num = i;
futures.add(CompletableFuture.supplyAsync(() -> num, es));
}
CompletableFuture<Integer> mergedFutures = CompletableFutureUtil.merge(futures, Integer::sum, () -> 0);
Assert.assertEquals(n * (n + 1) / 2, mergedFutures.get().intValue());
}
// test zero
CompletableFuture<Integer> mergedFutures = CompletableFutureUtil.merge(Collections.emptyList(), Integer::sum, () -> 0);
Assert.assertEquals(0, mergedFutures.get().intValue());
} finally {
es.shutdown();
}
}Example 33
| Project: Achilles-master File: FutureUtils.java View source code |
public static <T> CompletableFuture<T> toCompletableFuture(ListenableFuture<T> listenableFuture, ExecutorService executor) { CompletableFuture<T> completable = new CompletableListenableFuture<>(listenableFuture); Futures.addCallback(listenableFuture, new FutureCallback<T>() { @Override public void onSuccess(T result) { completable.complete(result); } @Override public void onFailure(Throwable t) { completable.completeExceptionally(t); } }, executor); return completable; }
Example 34
| Project: ajario-master File: LagScore.java View source code |
public static double lagScore(URI uri) {
double lagScore = 0;
final long[] updatePackets = { 0 };
final long[] firstUpdatePacket = { -1 };
final long sample = 10000;
WebSocketHandler webSocketHandler = new WebSocketHandler(uri, null);
CompletableFuture<Double> updateSecondFuture = new CompletableFuture<>();
webSocketHandler.registerPacketListener( agarPacket -> {
long currentTime = System.currentTimeMillis();
if (agarPacket.getType() == PacketType.ClientBound.UPDATE_NODES) {
updatePackets[0] += 1;
if (firstUpdatePacket[0] == -1) {
firstUpdatePacket[0] = currentTime;
} else {
long elapsed = currentTime - firstUpdatePacket[0];
if (elapsed > sample) {
double updatesSecond = (double) updatePackets[0] / (elapsed / 1000.0);
updateSecondFuture.complete(updatesSecond);
webSocketHandler.close();
}
}
}
});
webSocketHandler.sendPacket(new SetNickname("facebook"));
double updateSecond = 10;
try {
updateSecond = updateSecondFuture.get(20000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
}
double avgPing = 0;
try {
int times = 15;
double total = 0;
for (int i = 0; i < times; i++) {
long before = System.currentTimeMillis();
InetAddress.getByName(uri.getHost()).isReachable(300);
total += System.currentTimeMillis() - before;
}
avgPing = total / times;
} catch (IOException e) {
e.printStackTrace();
}
if (avgPing <= 90) {
lagScore += avgPing;
} else {
lagScore += Math.pow(avgPing, 1.2);
}
lagScore -= Math.pow(updateSecond, 1.6);
return lagScore;
}Example 35
| Project: armeria-master File: HttpAuthServiceImpl.java View source code |
@Override
public CompletionStage<Boolean> authorize(HttpRequest req, ServiceRequestContext ctx) {
CompletableFuture<Boolean> result = CompletableFuture.completedFuture(false);
for (Authorizer<HttpRequest> authorizer : authorizers) {
result = result.exceptionally( t -> {
logger.warn("Unexpected exception during authorization:", t);
return false;
}).thenComposeAsync( previousResult -> {
if (previousResult) {
return CompletableFuture.completedFuture(true);
}
return authorizer.authorize(ctx, req);
}, ctx.contextAwareEventLoop());
}
return result;
}Example 36
| Project: async-google-pubsub-client-master File: PublisherIT.java View source code |
@Test
public void testPublish() throws UnsupportedEncodingException, ExecutionException, InterruptedException {
final Message message = Message.ofEncoded("hello world");
final List<CompletableFuture<String>> futures = range(0, 10).mapToObj( i -> publisher.publish(TOPIC, message)).collect(toList());
futures.stream().map(Futures::getUnchecked).forEach( id -> out.println("message id: " + id));
}Example 37
| Project: async-retry-master File: AsyncRetryExecutorOneFailureTest.java View source code |
@Test
public void shouldRethrowAbortExceptionIfFirstIterationThrownIt() throws Exception {
//given
final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock);
given(serviceMock.sometimesFails()).willThrow(AbortRetryException.class);
//when
final CompletableFuture<String> future = executor.getWithRetry(serviceMock::sometimesFails);
//then
assertThat(future.isCompletedExceptionally()).isTrue();
try {
future.get();
failBecauseExceptionWasNotThrown(ExecutionException.class);
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(AbortRetryException.class);
}
}Example 38
| Project: aurora-master File: BatchWorkerUtil.java View source code |
public static <T> IExpectationSetters<CompletableFuture<T>> expectBatchExecute(BatchWorker<T> batchWorker, Storage storage, IMocksControl control, T resultValue) throws Exception { final CompletableFuture<T> result = new EasyMockTest.Clazz<CompletableFuture<T>>() { }.createMock(control); expect(result.get()).andReturn(resultValue).anyTimes(); final Capture<Work<T>> capture = createCapture(); return expect(batchWorker.execute(capture(capture))).andAnswer(() -> { storage.write((Storage.MutateWork.NoResult.Quiet) store -> capture.getValue().apply(store)); return result; }); }
Example 39
| Project: Blossom-master File: FutureCellRenderer.java View source code |
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int rowIndex, final int columnIndex) {
setNativeLookAndFeel(table, value, isSelected);
if (value != null) {
@SuppressWarnings("unchecked") final CompletableFuture<String> future = (CompletableFuture<String>) value;
if (future.isDone()) {
final String resolvedValue = future.getNow("Failed.");
setText(resolvedValue);
setToolTipText(resolvedValue);
} else {
// We set a default text.
setText("... Loading ...");
future.thenAcceptAsync((String text) -> asyncSetValue(text, table, rowIndex, columnIndex));
}
}
return this;
}Example 40
| Project: BlossomsPokemonGoManager-master File: FutureCellRenderer.java View source code |
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int rowIndex, final int columnIndex) {
setNativeLookAndFeel(table, value, isSelected);
if (value != null) {
@SuppressWarnings("unchecked") final CompletableFuture<String> future = (CompletableFuture<String>) value;
if (future.isDone()) {
final String resolvedValue = future.getNow("Failed.");
setText(resolvedValue);
setToolTipText(resolvedValue);
} else {
// We set a default text.
setText("... Loading ...");
future.thenAcceptAsync((String text) -> asyncSetValue(text, table, rowIndex, columnIndex));
}
}
return this;
}Example 41
| Project: bookkeeper-master File: SynchCallbackUtils.java View source code |
/**
* Wait for a result. This is convenience method to implement callbacks
*
* @param <T>
* @param future
* @return
* @throws InterruptedException
* @throws BKException
*/
public static <T> T waitForResult(CompletableFuture<T> future) throws InterruptedException, BKException {
try {
return future.get();
} catch (ExecutionException err) {
if (err.getCause() instanceof BKException) {
throw (BKException) err.getCause();
} else {
BKException unexpectedConditionException = BKException.create(BKException.Code.UnexpectedConditionException);
unexpectedConditionException.initCause(err.getCause());
throw unexpectedConditionException;
}
}
}Example 42
| Project: caffeine-master File: IsValidUnboundedLocalCache.java View source code |
private void checkMap(UnboundedLocalCache<K, V> map, DescriptionBuilder desc) {
if (map.isEmpty()) {
desc.expectThat("empty map", map, emptyMap());
}
map.data.forEach(( key, value) -> {
desc.expectThat("non null key", key, is(not(nullValue())));
desc.expectThat("non null value", value, is(not(nullValue())));
if (value instanceof CompletableFuture<?>) {
CompletableFuture<?> future = (CompletableFuture<?>) value;
boolean success = future.isDone() && !future.isCompletedExceptionally();
desc.expectThat("future is done", success, is(true));
desc.expectThat("not null value", future.getNow(null), is(not(nullValue())));
}
});
}Example 43
| Project: camel-master File: DefaultProducerTemplateNonBlockingAsyncTest.java View source code |
public void testRunningInSameThread() throws ExecutionException, InterruptedException {
Thread originalThread = Thread.currentThread();
CompletableFuture<Exchange> future = template.asyncSend("direct:echo", e -> {
Assert.assertSame(originalThread, Thread.currentThread());
e.getIn().setBody("Hi");
});
Assert.assertEquals("HiHi", template.extractFutureBody(future, String.class));
}Example 44
| Project: clc-java-sdk-master File: AbstractSingleJobFuture.java View source code |
@Override public CompletableFuture<Void> waitAsync() { CompletableFuture<Void> future = new CompletableFuture<>(); SdkThreadPool.get().execute(() -> { try { waitUntilComplete(); future.complete(null); } catch (Exception e) { future.completeExceptionally(e); } }); return future; }
Example 45
| Project: completion-stage-master File: CompletableFutureComposeTest.java View source code |
@Test
public void completedAfter() {
CompletableFuture<String> future1 = new CompletableFuture<>();
CompletableFuture<String> future2 = new CompletableFuture<>();
future1.thenCompose( x -> future2).whenComplete(( r, e) -> System.out.println("After: " + e));
future1.complete("value");
future2.completeExceptionally(new RuntimeException());
}Example 46
| Project: copycat-master File: OrderedCompletableFutureTest.java View source code |
/**
* Tests ordered completion of future callbacks.
*/
public void testOrderedCompletion() throws Throwable {
CompletableFuture<String> future = new OrderedCompletableFuture<>();
AtomicInteger order = new AtomicInteger();
future.whenComplete(( r, e) -> assertEquals(1, order.incrementAndGet()));
future.whenComplete(( r, e) -> assertEquals(2, order.incrementAndGet()));
future.handle(( r, e) -> {
assertEquals(3, order.incrementAndGet());
assertEquals(r, "foo");
return "bar";
});
future.thenRun(() -> assertEquals(3, order.incrementAndGet()));
future.thenAccept( r -> {
assertEquals(5, order.incrementAndGet());
assertEquals(r, "foo");
});
future.thenApply( r -> {
assertEquals(6, order.incrementAndGet());
assertEquals(r, "foo");
return "bar";
});
future.whenComplete(( r, e) -> {
assertEquals(7, order.incrementAndGet());
assertEquals(r, "foo");
});
future.complete("foo");
}Example 47
| Project: crate-master File: UserDefinedFunctionDDLClient.java View source code |
public CompletableFuture<Long> execute(final CreateFunctionAnalyzedStatement statement, Row params) {
UserDefinedFunctionMetaData metaData = new UserDefinedFunctionMetaData(statement.schema(), statement.name(), statement.arguments(), statement.returnType(), ExpressionToStringVisitor.convert(statement.language(), params), ExpressionToStringVisitor.convert(statement.definition(), params));
CreateUserDefinedFunctionRequest request = new CreateUserDefinedFunctionRequest(metaData, statement.replace());
FutureActionListener<UserDefinedFunctionResponse, Long> listener = new FutureActionListener<>( r -> 1L);
createUserDefinedFunctionAction.execute(request, listener);
return listener;
}Example 48
| Project: deadbolt-2-java-master File: CompositeDynamicResourceHandler.java View source code |
@Override
public CompletionStage<Boolean> isAllowed(final String name, final Optional<String> meta, final DeadboltHandler deadboltHandler, final Http.Context ctx) {
final DynamicResourceHandler delegate = delegates.get(name);
final CompletionStage<Boolean> result;
if (delegate == null) {
LOGGER.error("No DynamicResourceHandler with name [{}] found, denying access", name);
result = CompletableFuture.completedFuture(false);
} else {
result = delegate.isAllowed(name, meta, deadboltHandler, ctx);
}
return result;
}Example 49
| Project: elasticsearch-readonlyrest-plugin-master File: LdapClientWithCacheDecoratorTests.java View source code |
@Test
public void testIfAuthenticatedUserIsCachedByGivenDuration() throws Exception {
GroupsProviderLdapClient client = Mockito.mock(GroupsProviderLdapClient.class);
String dn = "cn=Example user,ou=People,dc=example,dc=com";
LdapCredentials credentials = new LdapCredentials("user", "password");
when(client.authenticate(any(LdapCredentials.class))).thenReturn(CompletableFuture.completedFuture(Optional.of(new LdapUser("user", dn))));
Duration ttl = Duration.ofSeconds(1);
GroupsProviderLdapClientCacheDecorator clientWithCache = new GroupsProviderLdapClientCacheDecorator(client, ttl);
Optional<LdapUser> ldapUser = clientWithCache.authenticate(credentials).get();
assertEquals(ldapUser.get().getDN(), dn);
Optional<LdapUser> ldapUserSecondAttempt = clientWithCache.authenticate(credentials).get();
assertEquals(ldapUserSecondAttempt.get().getDN(), dn);
Thread.sleep((long) (ttl.toMillis() * 1.5));
Optional<LdapUser> ldapUserThirdAttempt = clientWithCache.authenticate(credentials).get();
assertEquals(ldapUserThirdAttempt.get().getDN(), dn);
verify(client, times(2)).authenticate(credentials);
}Example 50
| Project: es4j-master File: LockProviderTest.java View source code |
@Test(timeOut = 2000)
@SneakyThrows
public void waiting() {
Lock lock = lockProvider.lock("test");
CompletableFuture<Lock> future = new CompletableFuture<>();
new Thread() {
@Override
public void run() {
Lock lock1 = lockProvider.lock("test");
future.complete(lock1);
}
}.start();
try {
future.get(1, TimeUnit.SECONDS);
fail("Lock wasn't locked");
return;
} catch (InterruptedExceptionExecutionException | e) {
e.printStackTrace();
} catch (TimeoutException e) {
}
lock.unlock();
future.join();
assertTrue(future.isDone() && !future.isCancelled());
future.get().unlock();
}Example 51
| Project: Glowstone-master File: ProfileCache.java View source code |
/**
* Look up the UUID for a given username.
*
* @param playerName The name to look up.
* @return The UUID, or null on failure.
*/
public static UUID getUUID(String playerName) {
if (uuidCache.containsKey(playerName)) {
return uuidCache.get(playerName);
}
UUID uuid = null;
CompletableFuture<UUID> uuidFuture = CompletableFuture.supplyAsync(() -> PlayerDataFetcher.getUUID(playerName));
uuidFuture.thenAcceptAsync( uid -> uuidCache.put(playerName, uid));
try {
uuid = uuidFuture.get(5, TimeUnit.SECONDS);
} catch (InterruptedExceptionExecutionException | e) {
GlowServer.logger.log(Level.SEVERE, "UUID Cache interrupted: ", e);
} catch (TimeoutException e) {
GlowServer.logger.log(Level.SEVERE, "UUID Cache lookup timed out: ", e);
}
return uuid;
}Example 52
| Project: j8iterables-master File: J8Futures.java View source code |
/**
* Convert a {@link CompletableFuture} to a {@link ListenableFuture}.
*
* @param completableFuture The Java8 completable future to convert
* @param <T> The value type of the future
* @return a Guava listenable future
*/
@Nonnull
public static <T> ListenableFuture<T> asListenableFuture(CompletableFuture<T> completableFuture) {
if (completableFuture instanceof CompletableListenableFuture) {
return ((CompletableListenableFuture<T>) completableFuture).delegateListenableFuture;
}
SettableFuture<T> ret = SettableFuture.create();
completableFuture.whenComplete(( result, ex) -> {
if (completableFuture.isCancelled()) {
ret.cancel(true);
} else if (ex != null) {
ret.setException(ex);
} else {
ret.set(result);
}
});
return ret;
}Example 53
| Project: jactr-master File: BasicAsynchronousModuleDelegate.java View source code |
public CompletableFuture<R> process(final IRequest request, final double requestTime, final Object... parameters) { boolean canProcess = shouldProcess(request, parameters); if (canProcess) { CompletableFuture<R> rtn = AbstractModule.delayedFuture(new Callable<R>() { public R call() throws Exception { R result = _errorResult; try { result = processInternal(request, requestTime, parameters); } catch (Exception e) { LOGGER.error("Failed to process pattern request ", e); } processInternalCompleted(request, result, parameters); return result; } }, getModule().getExecutor()); return rtn; } else { /* * nothing can be done, return right now */ processInternalCompleted(request, _errorResult, parameters); return AbstractModule.immediateReturn(_errorResult); } }
Example 54
| Project: jooby-master File: CompletableFutureMapperTest.java View source code |
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void resolve() throws Exception {
Object value = new Object();
new MockUnit(CompletableFuture.class).expect(deferred).expect(future).expect( unit -> {
Deferred deferred = unit.get(Deferred.class);
deferred.resolve(value);
}).run( unit -> {
new CompletableFutureMapper().map(unit.get(CompletableFuture.class));
}, init0, unit -> {
BiConsumer next = unit.captured(BiConsumer.class).iterator().next();
next.accept(value, null);
});
}Example 55
| Project: kaif-master File: JavaMailAgent.java View source code |
public CompletableFuture<Boolean> send(final Mail message) { return CompletableFuture.supplyAsync(() -> { //TODO timeout ? mailSender.send(new EncodingMimeMessagePreparator(message)); if (logger.isDebugEnabled()) { logger.debug("mail message sent:\n{}", message); } else { logger.info("mail message sent to:{} ", Arrays.toString(message.getTo())); } return true; }).handle(( result, e) -> { logger.error("mail message sent failed:" + Arrays.toString(message.getTo()) + ", cause:" + e.getMessage()); return false; }); }
Example 56
| Project: lettuce-core-master File: AsyncConnections.java View source code |
/**
* @return the {@link Connections}.
* @throws RedisConnectionException if no connection could be established.
*/
public Connections get(long timeout, TimeUnit timeUnit) throws InterruptedException {
Connections connections = new Connections();
List<Throwable> exceptions = new CopyOnWriteArrayList<>();
List<Future<?>> sync = new ArrayList<>(this.futures.size());
for (Map.Entry<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> entry : this.futures.entrySet()) {
CompletableFuture<StatefulRedisConnection<String, String>> future = entry.getValue();
sync.add(future.whenComplete(( connection, throwable) -> {
if (throwable != null) {
exceptions.add(throwable);
} else {
connections.addConnection(entry.getKey(), connection);
}
}));
}
RefreshFutures.awaitAll(timeout, timeUnit, sync);
if (connections.isEmpty() && !sync.isEmpty() && !exceptions.isEmpty()) {
RedisConnectionException collector = new RedisConnectionException("Unable to establish a connection to Redis Cluster");
exceptions.forEach(collector::addSuppressed);
throw collector;
}
return connections;
}Example 57
| Project: micro-server-master File: EmbeddedAppTest.java View source code |
<T> CompletableFuture<T> toCompletableFuture(final ListenableFuture<T> listenableFuture) { //create an instance of CompletableFuture CompletableFuture<T> completable = new CompletableFuture<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { // propagate cancel to the listenable future boolean result = listenableFuture.cancel(mayInterruptIfRunning); super.cancel(mayInterruptIfRunning); return result; } }; // add callback listenableFuture.addCallback(new ListenableFutureCallback<T>() { @Override public void onSuccess(T result) { completable.complete(result); } @Override public void onFailure(Throwable t) { completable.completeExceptionally(t); } }); return completable; }
Example 58
| Project: mldht-master File: TokenizerTest.java View source code |
@Test
public void correctNumberHandling() {
ByteBuffer num = str2buf("d3:fooi-17ee");
CompletableFuture<Long> parsed = new CompletableFuture<>();
t.inputBuffer(num);
t.consumer(new TokenConsumer() {
@Override
public void pop(Token st) {
if (st.type() == TokenType.LONG)
parsed.complete(t.lastDecodedNum());
}
@Override
public void push(Token st) {
}
});
t.tokenize();
assertEquals(-17L, (long) parsed.getNow(0L));
}Example 59
| Project: mpd-2015-i41n-master File: HttpGwAsyncNio.java View source code |
public CompletableFuture<Response> getDataAsync(String path) { CompletableFuture<Response> promise = new CompletableFuture<>(); client.prepareGet(path).execute(new AsyncCompletionHandler<Object>() { @Override public Object onCompleted(Response response) throws Exception { promise.complete(response); return response; } }); return promise; }
Example 60
| Project: mug-master File: ExceptionWrappingBenchmark.java View source code |
@Benchmark
void futuresGetChecked(int n) {
IOException exception = new IOException();
CompletableFuture<?> future = new CompletableFuture<>();
future.completeExceptionally(exception);
for (int i = 0; i < n; i++) {
try {
Futures.getChecked(future, IOException.class);
throw new AssertionError();
} catch (IOException expected) {
}
}
}Example 61
| Project: MULE-master File: NonBlockingExtensionsClientTestCase.java View source code |
@Override
<T, A> Result<T, A> doExecute(String extension, String operation, OperationParameters params) throws Throwable {
CompletableFuture<Result<T, A>> future = client.executeAsync(extension, operation, params);
try {
return future.get();
} catch (InterruptedException e) {
throw new RuntimeException("Failure. The test throw an exception: " + e.getMessage(), e);
} catch (ExecutionException e) {
throw e.getCause();
}
}Example 62
| Project: nem.core-master File: VersionProviderTest.java View source code |
public void setHttpResult(final ErrorResponseDeserializerUnion result) {
@SuppressWarnings("unchecked") final HttpMethodClient.AsyncToken<ErrorResponseDeserializerUnion> token = Mockito.mock(HttpMethodClient.AsyncToken.class);
Mockito.when(token.getFuture()).thenReturn(CompletableFuture.completedFuture(result));
Mockito.when(this.client.get(Mockito.any(), Mockito.any())).thenReturn(token);
}Example 63
| Project: openhab2-master File: HomekitSwitchImpl.java View source code |
@Override public CompletableFuture<Void> setSwitchState(boolean state) throws Exception { GenericItem item = getItem(); if (item instanceof SwitchItem) { ((SwitchItem) item).send(state ? OnOffType.ON : OnOffType.OFF); } else if (item instanceof GroupItem) { ((GroupItem) item).send(state ? OnOffType.ON : OnOffType.OFF); } return CompletableFuture.completedFuture(null); }
Example 64
| Project: opensnap-master File: DefaultUserService.java View source code |
@Override public CompletableFuture<User> create(User user) { Assert.hasLength(user.getUsername()); Assert.hasLength(user.getPassword()); CompletableFuture<User> futureUser = userRepository.count("username", user.getUsername()).thenCompose(( count) -> { Assert.isTrue(count == 0, "User " + user.getUsername() + " already exists!"); user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null)); return userRepository.insert(user); }); futureUser.thenAccept( createdUser -> template.convertAndSend(Topic.USER_CREATED, createdUser.withoutPasswordAndRoles())); return futureUser; }
Example 65
| Project: opslogger-master File: AsyncExecutor.java View source code |
public Future<?> execute(Runnable runnable) {
CompletableFuture<?> result = new CompletableFuture<Object>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
throw new UnsupportedOperationException("Calling thread.stop is deprecated. Arrange termination directly with the runnable");
}
};
factory.newThread(() -> {
try {
runnable.run();
} finally {
result.complete(null);
}
}).start();
return result;
}Example 66
| Project: piggy-master File: NotificationServiceImpl.java View source code |
@Override
@Scheduled(cron = "${backup.cron}")
public void sendBackupNotifications() {
final NotificationType type = NotificationType.BACKUP;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for backup notification", recipients.size());
recipients.forEach( recipient -> CompletableFuture.runAsync(() -> {
try {
String attachment = client.getAccount(recipient.getAccountName());
emailService.send(type, recipient, attachment);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during backup notification for {}", recipient, t);
}
}));
}Example 67
| Project: PiggyMetrics-master File: NotificationServiceImpl.java View source code |
@Override
@Scheduled(cron = "${backup.cron}")
public void sendBackupNotifications() {
final NotificationType type = NotificationType.BACKUP;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for backup notification", recipients.size());
recipients.forEach( recipient -> CompletableFuture.runAsync(() -> {
try {
String attachment = client.getAccount(recipient.getAccountName());
emailService.send(type, recipient, attachment);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during backup notification for {}", recipient, t);
}
}));
}Example 68
| Project: play-pac4j-master File: CallbackController.java View source code |
public CompletionStage<Result> callback() {
assertNotNull("callbackLogic", callbackLogic);
assertNotNull("config", config);
final PlayWebContext playWebContext = new PlayWebContext(ctx(), playSessionStore);
return CompletableFuture.supplyAsync(() -> callbackLogic.perform(playWebContext, config, config.getHttpActionAdapter(), this.defaultUrl, this.multiProfile, false), ec.current());
}Example 69
| Project: protonpack-master File: CompletableFuturesTest.java View source code |
@Test
public void collectsValuesFromCompletableFutures() throws ExecutionException, InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
CompletableFuture<List<Integer>> integers = IntStream.range(0, 1000).mapToObj( i -> CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(random.nextInt(100));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return i;
}, threadPool)).collect(CompletableFutures.toFutureList());
assertThat(integers.get(), equalTo(IntStream.range(0, 1000).mapToObj(Integer::valueOf).collect(toList())));
}Example 70
| Project: Pulsar-master File: MockedZooKeeperClientFactoryImpl.java View source code |
@Override public CompletableFuture<ZooKeeper> create(String serverList, SessionType sessionType, int zkSessionTimeoutMillis) { MockZooKeeper mockZooKeeper = MockZooKeeper.newInstance(); // not used for mock mode List<ACL> dummyAclList = new ArrayList<ACL>(0); try { ZkUtils.createFullPathOptimistic(mockZooKeeper, "/ledgers/available/192.168.1.1:" + 5000, "".getBytes(ZookeeperClientFactoryImpl.ENCODING_SCHEME), dummyAclList, CreateMode.PERSISTENT); mockZooKeeper.create("/ledgers/LAYOUT", "1\nflat:1".getBytes(ZookeeperClientFactoryImpl.ENCODING_SCHEME), dummyAclList, CreateMode.PERSISTENT); return CompletableFuture.completedFuture(mockZooKeeper); } catch (KeeperExceptionInterruptedException | e) { CompletableFuture<ZooKeeper> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } }
Example 71
| Project: requery-master File: BaseScalar.java View source code |
@Override public CompletableFuture<E> toCompletableFuture(Executor executor) { final java.util.function.Supplier<E> supplier = new java.util.function.Supplier<E>() { @Override public E get() { return BaseScalar.this.value(); } }; return executor == null ? CompletableFuture.supplyAsync(supplier) : CompletableFuture.supplyAsync(supplier, executor); }
Example 72
| Project: riptide-master File: HystrixPluginTest.java View source code |
@Test
public void shouldCancel() throws IOException {
when(execution.execute()).thenReturn(new CompletableFuture<>());
final RequestExecution unit = new HystrixPlugin().prepare(arguments, execution);
final CompletableFuture<ClientHttpResponse> future = unit.execute();
future.cancel(true);
assertThat(future.isCancelled(), is(true));
}Example 73
| Project: sfc-master File: SfcGeniusServiceHandlerTest.java View source code |
@Before
public void setup() {
when(sfcGeniusServiceHandler.getBoundServiceWriter()).thenReturn(sfcGeniusBoundServiceWriter);
when(sfcGeniusServiceHandler.getTsaWriter()).thenReturn(sfcGeniusTsaWriter);
when(sfcGeniusBoundServiceWriter.bindService(any())).thenReturn(CompletableFuture.completedFuture(null));
when(sfcGeniusBoundServiceWriter.unbindService(any())).thenReturn(CompletableFuture.completedFuture(null));
}Example 74
| Project: speedment-master File: CompletableFutureUtil.java View source code |
@SafeVarargs public static <T> CompletableFuture<T> allOf(T defaultValue, BinaryOperator<T> merger, CompletableFuture<T>... futures) { @SuppressWarnings("unchecked") final CompletableFuture<Void>[] accumulators = (CompletableFuture<Void>[]) Array.newInstance(CompletableFuture.class, futures.length); final AtomicReference<T> result = new AtomicReference<>(defaultValue); for (int i = 0; i < futures.length; i++) { final CompletableFuture<T> future = futures[i]; accumulators[i] = future.thenAcceptAsync( r -> result.accumulateAndGet(r, merger)); } return CompletableFuture.allOf(accumulators).thenApplyAsync( v -> result.get()); }
Example 75
| Project: spring-reactive-master File: MonoToCompletableFutureConverterTests.java View source code |
@Test
public void canConvert() throws Exception {
assertTrue(this.conversionService.canConvert(Mono.class, CompletableFuture.class));
assertTrue(this.conversionService.canConvert(CompletableFuture.class, Mono.class));
assertFalse(this.conversionService.canConvert(Flux.class, CompletableFuture.class));
assertFalse(this.conversionService.canConvert(CompletableFuture.class, Flux.class));
assertFalse(this.conversionService.canConvert(Publisher.class, CompletableFuture.class));
assertFalse(this.conversionService.canConvert(CompletableFuture.class, Publisher.class));
}Example 76
| Project: torodb-master File: ListeningFutureToCompletableFuture.java View source code |
public static <T> CompletableFuture<T> toCompletableFuture(final ListenableFuture<T> listenableFuture) { //create an instance of CompletableFuture CompletableFuture<T> completable = new CompletableFuture<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { // propagate cancel to the listenable future boolean result = listenableFuture.cancel(mayInterruptIfRunning); super.cancel(mayInterruptIfRunning); return result; } }; // add callback Futures.addCallback(listenableFuture, new FutureCallback<T>() { @Override @SuppressFBWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE") public void onSuccess(T result) { completable.complete(result); } @Override public void onFailure(Throwable t) { completable.completeExceptionally(t); } }); return completable; }
Example 77
| Project: ua-client-sdk-master File: AbstractUaMethod.java View source code |
public CompletableFuture<Variant[]> invoke(Variant[] inputArguments) { CallMethodRequest request = new CallMethodRequest(objectId, methodId, inputArguments); return client.call(request).thenCompose( result -> { StatusCode statusCode = result.getStatusCode(); if (statusCode.isGood()) { Variant[] outputArguments = result.getOutputArguments(); return CompletableFuture.completedFuture(outputArguments); } else { UaMethodException ex = new UaMethodException(statusCode, result.getInputArgumentResults(), result.getInputArgumentDiagnosticInfos()); CompletableFuture<Variant[]> f = new CompletableFuture<>(); f.completeExceptionally(ex); return f; } }); }
Example 78
| Project: vertx-pac4j-master File: VertxClusteredMapStore.java View source code |
@Override
public V get(K key) {
voidAsyncOpToBlocking( map -> map.getObservable((key)));
final CompletableFuture<V> valueFuture = new CompletableFuture<>();
rxVertx.sharedData().<K, V>getClusterWideMapObservable(PAC4J_SHARED_DATA_KEY).flatMap( map -> map.getObservable(key)).subscribe(valueFuture::complete);
try {
return valueFuture.get(blockingTimeoutSeconds, TimeUnit.SECONDS);
} catch (InterruptedExceptionExecutionException | TimeoutException | e) {
throw new TechnicalException(e);
}
}Example 79
| Project: vertx-zookeeper-master File: ConsumerRoundRobinTest.java View source code |
private CompletableFuture<Void> addConsumer(int index) { CompletableFuture<Void> future = new CompletableFuture<>(); vertices[0].eventBus().consumer(MESSAGE_ADDRESS, message -> message.reply(index)).completionHandler( event -> { if (event.succeeded()) { future.complete(null); } else { future.completeExceptionally(event.cause()); } }); return future; }
Example 80
| Project: werval-master File: RemoveHeaders.java View source code |
@Override
public CompletableFuture<Outcome> filter(FilterChain chain, Context context, Optional<RemoveHeaders> annotation) {
return chain.next(context).thenApply(( outcome) -> {
String[] blacklist = annotation.map( annot -> annot.value()).orElse(new String[0]);
for (String blacklisted : blacklist) {
outcome.responseHeader().headers().without(blacklisted);
}
return outcome;
});
}Example 81
| Project: scribble-java-master File: InputFutureGenerator.java View source code |
@Override
public ClassBuilder generateType() throws ScribbleException {
final String FUTURE_PARAM = "fut";
Module main = this.apigen.getMainModule();
GProtocolName gpn = this.apigen.getGProtocolName();
// Fresh enough? need only one future class per receive (unary receive)
String futureClass = getInputFutureName(this.parent.getName());
//cb.addImports("java.util.concurrent.CompletableFuture"); // "parent" cb, not the future class
//cb.addImports("java.util.concurrent.ExecutionException");
//ClassBuilder future = cb.newClass(); // FIXME: inner class
// Duplicated from BranchInterfaceBuilder -- FIXME: factor out
ClassBuilder future = new ClassBuilder();
// FIXME: factor out with ScribSocketBuilder
future.setPackage(SessionApiGenerator.getStateChannelPackageName(gpn, this.apigen.getSelf()));
future.addImports("java.io.IOException");
// "parent" cb, not the future class
future.addImports("java.util.concurrent.CompletableFuture");
future.addModifiers(InterfaceBuilder.PUBLIC);
future.setName(futureClass);
future.setSuperClass(SCRIBFUTURE_CLASS);
List<String> types = new LinkedList<>();
if (a.mid.isOp()) {
if (!a.payload.isEmpty()) {
int i = 1;
for (PayloadType<?> pt : a.payload.elems) {
if (!pt.isDataType()) {
throw new ScribbleException("[TODO] API generation not supported for non- data type payloads: " + pt);
}
DataTypeDecl dtd = main.getDataTypeDecl((DataType) pt);
ScribSocketGenerator.checkJavaDataTypeDecl(dtd);
String type = dtd.extName;
types.add(type);
FieldBuilder f = future.newField("pay" + i++);
f.setType(type);
f.addModifiers(JavaBuilder.PUBLIC);
}
}
} else {
MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName());
ScribSocketGenerator.checkMessageSigNameDecl(msd);
String type = msd.extName;
types.add(type);
FieldBuilder f = future.newField("msg");
f.setType(type);
f.addModifiers(JavaBuilder.PUBLIC);
}
ConstructorBuilder cons = future.newConstructor("CompletableFuture<" + StateChannelApiGenerator.SCRIBMESSAGE_CLASS + "> " + FUTURE_PARAM);
cons.addModifiers(JavaBuilder.PROTECTED);
cons.addBodyLine(JavaBuilder.SUPER + "(" + FUTURE_PARAM + ");");
MethodBuilder sync = future.newMethod("sync");
sync.addModifiers(JavaBuilder.PUBLIC);
sync.setReturn(futureClass);
//sync.addExceptions("ExecutionException", "InterruptedException");
sync.addExceptions("IOException");
String ln = (a.mid.isOp() && a.payload.isEmpty()) ? "" : StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " m = ";
ln += JavaBuilder.SUPER + ".get();";
sync.addBodyLine(ln);
if (a.mid.isOp()) {
if (!a.payload.isEmpty()) {
int i = 1;
for (String type : types) {
sync.addBodyLine(JavaBuilder.THIS + "." + "pay" + i + " = (" + type + ") m.payload[" + (i - 1) + "];");
i++;
}
}
} else {
sync.addBodyLine(JavaBuilder.THIS + "." + "msg" + " = (" + types.get(0) + ") m;");
}
sync.addBodyLine(JavaBuilder.RETURN + " " + JavaBuilder.THIS + ";");
return future;
}Example 82
| Project: AsciidocFX-master File: Current.java View source code |
public String currentEditorValue() {
if (Platform.isFxApplicationThread())
return (String) currentEngine().executeScript("editor.getValue()");
final CompletableFuture<String> completableFuture = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
threadService.runActionLater(() -> {
try {
Object result = currentEngine().executeScript("editor.getValue()");
completableFuture.complete((String) result);
} catch (Exception ex) {
completableFuture.completeExceptionally(ex);
}
});
}, threadService.executor());
return completableFuture.join();
}Example 83
| Project: BuyCraft-master File: SignUpdater.java View source code |
@Override
public void run() {
List<RecentPurchaseSignPosition> signs = plugin.getRecentPurchaseSignStorage().getSigns();
OptionalInt maxPos = signs.stream().mapToInt(RecentPurchaseSignPosition::getPosition).max();
if (!maxPos.isPresent()) {
// Nothing to do
return;
}
if (plugin.getApiClient() == null) {
// Can't use API client
return;
}
List<RecentPayment> payments;
try {
payments = plugin.getApiClient().getRecentPayments(Math.min(100, maxPos.getAsInt()));
} catch (IOExceptionApiException | e) {
plugin.getLogger().error("Could not fetch recent purchases", e);
return;
}
Map<RecentPurchaseSignPosition, RecentPayment> signToPurchases = new HashMap<>();
for (RecentPurchaseSignPosition sign : signs) {
if (sign.getPosition() >= payments.size()) {
signToPurchases.put(sign, null);
} else {
signToPurchases.put(sign, payments.get(sign.getPosition() - 1));
}
}
// Now look up game profiles so that heads can be properly displayed.
Set<String> usernames = payments.stream().map( payment -> payment.getPlayer().getName()).collect(Collectors.toSet());
// Add MHF_Question too.
usernames.add("MHF_Question");
CompletableFuture<Collection<GameProfile>> future = Sponge.getServer().getGameProfileManager().getAllByName(usernames, true);
future.whenComplete(( result, throwable) -> {
if (throwable != null) {
plugin.getLogger().error("Unable to fetch player profiles", throwable);
return;
}
Map<String, GameProfile> profileMap = result.stream().filter( p -> p.getName().isPresent()).collect(Collectors.toMap( p -> p.getName().get(), Function.identity()));
Sponge.getScheduler().createTaskBuilder().execute(new SignUpdateApplication(plugin, signToPurchases, profileMap)).submit(plugin);
});
}Example 84
| Project: catalyst-master File: LocalTransportTest.java View source code |
/**
* Tests connecting to a server and sending a message.
*/
public void testSendReceive() throws Throwable {
LocalServerRegistry registry = new LocalServerRegistry();
Transport clientTransport = new LocalTransport(registry);
Transport serverTransport = new LocalTransport(registry);
Server server = serverTransport.server();
Client client = clientTransport.client();
ThreadContext context = new SingleThreadContext("test-thread-%d", new Serializer());
context.executor().execute(() -> {
try {
server.listen(new Address(new InetSocketAddress(InetAddress.getByName("localhost"), 5555)), connection -> {
connection.<String, String>handler(String.class, message -> {
threadAssertEquals("Hello world!", message);
return CompletableFuture.completedFuture("Hello world back!");
});
}).thenRun(this::resume);
} catch (UnknownHostException e) {
threadFail(e);
}
});
await();
context.executor().execute(() -> {
try {
client.connect(new Address(new InetSocketAddress(InetAddress.getByName("localhost"), 5555))).thenAccept( connection -> {
connection.sendAndReceive("Hello world!").thenAccept( response -> {
threadAssertEquals("Hello world back!", response);
resume();
});
});
} catch (UnknownHostException e) {
threadFail(e);
}
});
await();
}Example 85
| Project: clickstream-rest-proxy-master File: Producer.java View source code |
public <T> CompletableFuture<PublishingResponse> publish(Schema schema, T message, String topic) throws JsonProcessingException, UnsupportedEncodingException {
PublishingData data = new PublishingData(new Record(message), null, null, schema.toString(), null);
HttpCallback<PublishingResponse> callback = new HttpCallback(PublishingResponse.class);
executePost(baseUri.resolve(topic), new StringEntity(mapper.writeValueAsString(data), ContentType.APPLICATION_JSON), callback);
return callback;
}Example 86
| Project: cxf-master File: SseBroadcasterImpl.java View source code |
@Override
public CompletionStage<?> broadcast(OutboundSseEvent event) {
final Collection<CompletableFuture<?>> futures = new ArrayList<>();
for (SseEventSink sink : subscribers) {
try {
futures.add(sink.send(event).toCompletableFuture());
} catch (final Exception ex) {
exceptioners.forEach( exceptioner -> exceptioner.accept(sink, ex));
}
}
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
}Example 87
| Project: devicehive-java-server-master File: WebSocketApiInfoHandlerTest.java View source code |
@Test
public void shouldReturnApiInfo() throws Exception {
final String requestId = "62345vxgsa5";
CompletableFuture<TextMessage> future = new CompletableFuture<>();
new StandardWebSocketClient().doHandshake(new TextWebSocketHandler() {
@Override
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);
}Example 88
| Project: diqube-master File: DiqubeCatalystClient.java View source code |
@Override public CompletableFuture<Connection> connect(Address address) { CompletableFuture<Connection> res = new CompletableFuture<>(); try { DiqubeCatalystConnection con = factory.createDiqubeCatalystConnection(ThreadContext.currentContextOrThrow()); con.openAndRegister(address); connections.add(con); // TODO #92 workaround as long as copycat pullrequest #76 is not merged. ThreadContext.currentContextOrThrow().executor().execute(() -> res.complete(con)); // res.complete(con); } catch (TransportException e) { res.completeExceptionally(e); } return res; }
Example 89
| Project: FireFly-master File: Promise.java View source code |
/**
* <p>Creates a promise from the given incomplete CompletableFuture.</p>
* <p>When the promise completes, either succeeding or failing, the
* CompletableFuture is also completed, respectively via
* {@link CompletableFuture#complete(Object)} or
* {@link CompletableFuture#completeExceptionally(Throwable)}.</p>
*
* @param completable the CompletableFuture to convert into a promise
* @param <T> the type of the result
* @return a promise that when completed, completes the given CompletableFuture
*/
static <T> Promise<T> from(CompletableFuture<? super T> completable) {
if (completable instanceof Promise)
return (Promise<T>) completable;
return new Promise<T>() {
@Override
public void succeeded(T result) {
completable.complete(result);
}
@Override
public void failed(Throwable x) {
completable.completeExceptionally(x);
}
};
}Example 90
| Project: future-converter-master File: Java8FutureUtils.java View source code |
public static <T> ValueSourceFuture<T> createValueSourceFuture(CompletableFuture<T> completableFuture) {
if (completableFuture instanceof ValueSourcebackedCompletableFuture && ((ValueSourcebackedCompletableFuture<T>) completableFuture).getValueSource() instanceof ValueSourceFuture) {
return (ValueSourceFuture<T>) ((ValueSourcebackedCompletableFuture<T>) completableFuture).getValueSource();
} else {
return new CompletableFuturebackedValueSource<>(completableFuture);
}
}Example 91
| Project: HAP-Java-master File: HomekitRootTest.java View source code |
@Before
public void setup() throws Exception {
accessory = mock(HomekitAccessory.class);
when(accessory.getId()).thenReturn(2);
webHandler = mock(HomekitWebHandler.class);
when(webHandler.start(any())).thenReturn(CompletableFuture.completedFuture(PORT));
advertiser = mock(JmdnsHomekitAdvertiser.class);
authInfo = mock(HomekitAuthInfo.class);
root = new HomekitRoot(LABEL, webHandler, authInfo, advertiser);
}Example 92
| Project: hibernate-orm-master File: LockingInterceptor.java View source code |
@Override
protected Object visitDataWriteCommand(InvocationContext ctx, DataWriteCommand command) throws Throwable {
Object returnValue = null;
try {
// Clear any metadata; we'll set them as appropriate in TombstoneCallInterceptor
command.setMetadata(null);
lockAndRecord(ctx, command.getKey(), getLockTimeoutMillis(command));
returnValue = invokeNextInterceptor(ctx, command);
return returnValue;
} catch (TimeoutException e) {
if (!ctx.isOriginLocal() && command.hasFlag(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT)) {
if (trace) {
log.tracef("Silently ignoring exception", e);
}
return null;
} else {
throw e;
}
} finally {
lockManager.unlockAll(ctx);
if (returnValue instanceof CompletableFuture) {
try {
((CompletableFuture) returnValue).join();
} catch (CompletionException e) {
throw e.getCause();
}
}
}
}Example 93
| Project: htwplus-master File: ScheduleService.java View source code |
private void schedule() {
// set the email schedule to next full hour clock for sending daily and hourly emails
Cancellable emailScheudler = system.scheduler().schedule(Duration.create(nextExecutionInSeconds(getNextHour(), 0), TimeUnit.SECONDS), Duration.create(1, TimeUnit.HOURS), () -> {
emailService.sendDailyHourlyNotificationsEmails();
}, system.dispatcher());
// cancel it on application stop
lifecycle.addStopHook(() -> {
emailScheudler.cancel();
return CompletableFuture.completedFuture(null);
});
// Sets the schedule for cleaning the media temp directory
Cancellable cleanUpScheudler = system.scheduler().schedule(Duration.create(0, TimeUnit.MILLISECONDS), Duration.create(2, TimeUnit.HOURS), () -> {
mediaManager.cleanUpTemp();
}, system.dispatcher());
// cancel it on application stop
lifecycle.addStopHook(() -> {
cleanUpScheudler.cancel();
return CompletableFuture.completedFuture(null);
});
}Example 94
| Project: idnadrev-master File: ThumbnailCacheTest.java View source code |
@Test
public void testMutliThreadAccess() throws Exception {
int nThreads = 8;
int amountPerThread = 10;
// ExecutorService executorService = Executors.newFixedThreadPool(1);
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
ArrayList<Future<CompletableFuture<List<Thumbnail>>>> futures = new ArrayList<>();
for (int i = 0; i < nThreads; i++) {
futures.add(executorService.submit(() -> {
return cache.reserve(amountPerThread);
}));
}
for (Future<CompletableFuture<List<Thumbnail>>> future : futures) {
Collection<Thumbnail> thumbnails = future.get().get();
assertEquals(amountPerThread, thumbnails.size());
}
assertEquals(0, cache.available.size());
assertEquals(nThreads * amountPerThread, cache.reserved.size());
}Example 95
| Project: itol-master File: DeferredSuggest.java View source code |
/** * Find suggestions for given text. * Starts a timer that waits deferMillis milliseconds before it calls the suggest interface. * Right before the suggest interface is invoked, it is checked, whether another thread has * already invoked this function. In this case, the returned Future object is cancelled. * Otherwise the suggest interface is invoked and the Future object is completed with the results. * * @param text * Text * @param max * Maximum number of items to return. * @param ignoreHits * Return only items that do not exist in this collection. Can be null. * @return Future object that is completed, when the results are available. If the search is cancelled, the Future object is completed exceptionally. */ public CompletableFuture<Collection<T>> find(String text, int max, Collection<T> ignoreHits) { CompletableFuture<Collection<T>> ret = new CompletableFuture<>(); final int suggestionId = suggestionCounter.incrementAndGet(); Timeline timer = new Timeline(new KeyFrame(Duration.millis(deferMillis), ( event) -> { if (suggestionId == suggestionCounter.get()) { CompletableFuture.supplyAsync(() -> { Collection<T> items = suggest.find(text, max, ignoreHits); return items; }).thenApply(( items) -> { ret.complete(items); return null; }); } else { ret.completeExceptionally(new CancellationException()); } })); timer.setCycleCount(1); timer.play(); return ret; }
Example 96
| Project: josm-plugins-master File: WikidataTagCellRenderer.java View source code |
protected JLabel renderValues(Collection<String> ids, JTable table, JLabel component) {
ids.forEach( id -> labelCache.computeIfAbsent(id, x -> CompletableFuture.supplyAsync(() -> WikipediaApp.getLabelForWikidata(x, Locale.getDefault()))));
final Collection<String> texts = new ArrayList<>(ids.size());
for (String id : ids) {
if (!labelCache.get(id).isDone()) {
labelCache.get(id).thenRun(() -> GuiHelper.runInEDT(table::repaint));
return null;
}
final String label;
try {
label = labelCache.get(id).get();
} catch (InterruptedExceptionExecutionException | e) {
Main.warn("Could not fetch Wikidata label for " + id);
Main.warn(e);
return null;
}
if (label == null) {
return null;
}
texts.add(WikidataEntry.getLabelText(id, label));
}
component.setText("<html>" + texts.stream().collect(Collectors.joining("; ")));
component.setToolTipText("<html>" + Utils.joinAsHtmlUnorderedList(texts));
return component;
}Example 97
| Project: kume-master File: AppendLogEntryRequest.java View source code |
@Override
public void run(InternalService service, OperationContext<Boolean> ctx) {
// synchronized (service.cluster) {
Set<Member> counter = new HashSet<>();
Set<Member> members = service.cluster.getMembers();
AtomicInteger size = new AtomicInteger(members.size());
long index = service.cluster.getLastCommitIndex().get();
ArrayList<CompletableFuture> reqs = new ArrayList(members.size());
for (Member member : members) {
CompletableFuture<R> f = new CompletableFuture<>();
service.cluster.tryAskUntilDoneInternal(member, new UncommittedLogRequest(index, request), 5, 0, f);
reqs.add(f.whenComplete(( result, ex) -> {
int lastSize;
if (ex != null) {
service.cluster.removeMemberAsMaster(member, true);
lastSize = size.decrementAndGet();
} else {
counter.add(member);
lastSize = counter.size();
}
if (lastSize == members.size()) {
commit(service.cluster, index);
ctx.reply(true);
}
}));
}
reqs.forEach( f -> f.join());
// }
}Example 98
| Project: onos-master File: BlockingAwareFutureTest.java View source code |
/**
* Tests normal callback execution.
*/
@Test
public void testNonBlockingThread() throws Exception {
CompletableFuture<String> future = new CompletableFuture<>();
Executor executor = SharedExecutors.getPoolThreadExecutor();
BlockingAwareFuture<String> blockingFuture = (BlockingAwareFuture<String>) Tools.orderedFuture(future, new OrderedExecutor(executor), executor);
CountDownLatch latch = new CountDownLatch(1);
blockingFuture.thenRun(() -> latch.countDown());
executor.execute(() -> future.complete("foo"));
latch.await(5, TimeUnit.SECONDS);
assertEquals(0, latch.getCount());
assertEquals("foo", blockingFuture.join());
assertFalse(blockingFuture.isBlocked());
}Example 99
| Project: orb-master File: SimpleStreamTest.java View source code |
@SuppressWarnings("Duplicates")
@Test(timeout = 30_000L)
public void test() {
createStage();
CompletableFuture<String> push = new Task<>();
AsyncStream<String> test = AsyncStream.getStream(String.class, "test");
test.subscribe(( d, t) -> {
push.complete(d);
return Task.done();
}).join();
test.publish("hello");
assertEquals("hello", push.join());
dumpMessages();
}Example 100
| Project: orbit-master File: SimpleStreamTest.java View source code |
@SuppressWarnings("Duplicates")
@Test(timeout = 30_000L)
public void test() {
createStage();
CompletableFuture<String> push = new Task<>();
AsyncStream<String> test = AsyncStream.getStream(String.class, "test");
test.subscribe(( d, t) -> {
push.complete(d);
return Task.done();
}).join();
test.publish("hello");
assertEquals("hello", push.join());
dumpMessages();
}Example 101
| Project: PerfCake-master File: AbstractSequence.java View source code |
@Override
@SuppressWarnings("unchecked")
public final void publishNext(final String sequenceId, final Properties values) {
// cannot use get and set as this could break the order of values (the task added later can be computed sooner)
final CompletableFuture<String> previousValue = nextValue.get();
try {
final String result = previousValue.get();
nextValue.set(CompletableFuture.supplyAsync(this::doGetNext));
values.setProperty(sequenceId, result);
} catch (InterruptedExceptionConcurrentModificationException | ExecutionException | e) {
values.setProperty(sequenceId, doGetNext());
}
}