List of usage examples for java.util.concurrent CompletableFuture completeExceptionally
public boolean completeExceptionally(Throwable ex)
From source file:Main.java
public static <T> CompletableFuture<T> anyOfFutures(List<? extends CompletableFuture<? extends T>> futures) { CompletableFuture<T> cf = new CompletableFuture<>(); CompletableFuture//from ww w .jav a 2 s . c om .allOf(futures.stream().map(f -> f.thenAccept(cf::complete)).toArray(CompletableFuture<?>[]::new)) .exceptionally(ex -> { cf.completeExceptionally(ex); return null; }); return cf; }
From source file:Main.java
public static <T> CompletableFuture<List<T>> allOfFutures( List<? extends CompletableFuture<? extends T>> futures) { List<T> result = new ArrayList<>(futures.size()); CompletableFuture<List<T>> cf = new CompletableFuture<>(); CompletableFuture// www . ja v a 2 s . c o m .allOf(futures.stream().map(s -> s.thenAccept(result::add)).toArray(CompletableFuture<?>[]::new)) .exceptionally(ex -> { cf.completeExceptionally(ex); return null; }).thenAccept(v -> cf.complete(result)); return cf; }
From source file:net.javacrumbs.futureconverter.springjava.FutureConverter.java
private static <T> CompletableFuture<T> buildCompletableFutureFromListenableFuture( final ListenableFuture<T> listenableFuture) { CompletableFuture<T> completable = new CompletableListenableFuture<T>(listenableFuture); listenableFuture.addCallback(new ListenableFutureCallback<T>() { @Override// w w w . j ava 2s.c o m public void onSuccess(T result) { completable.complete(result); } @Override public void onFailure(Throwable t) { completable.completeExceptionally(t); } }); return completable; }
From source file:com.ikanow.aleph2.analytics.storm.utils.StormControllerUtil.java
/** * Starts up a storm job./*from ww w . j av a2s .c om*/ * * 1. gets the storm instance from the yarn config * 2. Makes a mega jar consisting of: * A. Underlying artefacts (system libs) * B. User supplied libraries * 3. Submit megajar to storm with jobname of the bucket id * * @param bucket * @param underlying_artefacts * @param yarn_config_dir * @param user_lib_paths * @param topology * @return */ public static CompletableFuture<BasicMessageBean> startJob(final IStormController storm_controller, final DataBucketBean bucket, final Optional<String> sub_job, final Collection<Object> underlying_artefacts, final Collection<String> user_lib_paths, final StormTopology topology, final Map<String, String> config, final String cached_jar_dir) { if (null == topology) { return CompletableFuture.completedFuture(ErrorUtils.buildErrorMessage(StormControllerUtil.class, "startJob", ErrorUtils.TOPOLOGY_NULL_ERROR, bucket.full_name())); } _logger.info("Retrieved user Storm config topology: spouts=" + topology.get_spouts_size() + " bolts=" + topology.get_bolts_size() + " configs=" + config.toString()); final Set<String> jars_to_merge = new TreeSet<String>(); final CompletableFuture<String> jar_future = Lambdas.get(() -> { if (RemoteStormController.class.isAssignableFrom(storm_controller.getClass())) { // (This is only necessary in the remote case) jars_to_merge.addAll(underlying_artefacts.stream() .map(artefact -> LiveInjector.findPathJar(artefact.getClass(), "")) .filter(f -> !f.equals("")).collect(Collectors.toSet())); if (jars_to_merge.isEmpty()) { // special case: no aleph2 libs found, this is almost certainly because this is being run from eclipse... final GlobalPropertiesBean globals = ModuleUtils.getGlobalProperties(); _logger.warn( "WARNING: no library files found, probably because this is running from an IDE - instead taking all JARs from: " + (globals.local_root_dir() + "/lib/")); try { //... and LiveInjecter doesn't work on classes ... as a backup just copy everything from "<LOCAL_ALEPH2_HOME>/lib" into there jars_to_merge .addAll(FileUtils .listFiles(new File(globals.local_root_dir() + "/lib/"), new String[] { "jar" }, false) .stream().map(File::toString).collect(Collectors.toList())); } catch (Exception e) { throw new RuntimeException("In eclipse/IDE mode, directory not found: " + (globals.local_root_dir() + "/lib/")); } } //add in the user libs jars_to_merge.addAll(user_lib_paths); //create jar return buildOrReturnCachedStormTopologyJar(jars_to_merge, cached_jar_dir); } else { return CompletableFuture.completedFuture("/unused/dummy.jar"); } }); //submit to storm @SuppressWarnings("unchecked") final CompletableFuture<BasicMessageBean> submit_future = Lambdas.get(() -> { long retries = 0; while (retries < MAX_RETRIES) { try { _logger.debug("Trying to submit job, try: " + retries + " of " + MAX_RETRIES); final String jar_file_location = jar_future.get(); return storm_controller.submitJob(bucketPathToTopologyName(bucket, sub_job), jar_file_location, topology, (Map<String, Object>) (Map<String, ?>) config); } catch (Exception ex) { if (ex instanceof AlreadyAliveException) { retries++; //sleep 1s, was seeing about 2s of sleep required before job successfully submitted on restart try { Thread.sleep(1000); } catch (Exception e) { final CompletableFuture<BasicMessageBean> error_future = new CompletableFuture<BasicMessageBean>(); error_future.completeExceptionally(e); return error_future; } } else { retries = MAX_RETRIES; //we threw some other exception, bail out final CompletableFuture<BasicMessageBean> error_future = new CompletableFuture<BasicMessageBean>(); error_future.completeExceptionally(ex); return error_future; } } } //we maxed out our retries, throw failure final CompletableFuture<BasicMessageBean> error_future = new CompletableFuture<BasicMessageBean>(); error_future.completeExceptionally(new Exception( "Error submitting job, ran out of retries (previous (same name) job is probably still alive)")); return error_future; }); return submit_future; }
From source file:com.yahoo.pulsar.broker.service.BrokerService.java
private static <T> CompletableFuture<T> failedFuture(Throwable t) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(t); return future; }
From source file:com.opopov.cloud.image.utils.Utils.java
public static <T> CompletableFuture<T> fromListenableFuture(ListenableFuture<T> listenable) { CompletableFuture<T> completable = new CompletableFuture<T>() { @Override/*www .ja v a2 s .c om*/ public boolean isCancelled() { return listenable.isCancelled(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { //delegate cancel to the wrapped listenable boolean cancelledStatus = listenable.cancel(mayInterruptIfRunning); super.cancel(mayInterruptIfRunning); return cancelledStatus; } }; //now delegate the callbacks ListenableFutureCallback<T> callback = new ListenableFutureCallback<T>() { @Override public void onFailure(Throwable ex) { //delegate exception completable.completeExceptionally(ex); } @Override public void onSuccess(T result) { //delegate success completable.complete(result); } }; listenable.addCallback(callback); return completable; }
From source file:am.ik.categolj3.api.jest.JestIndexer.java
@Async public CompletableFuture<Void> reindex() { log.info("re-indexing ..."); List<Entry> entries = gitStore.loadEntries(); Bulk.Builder bulkBuilder = new Bulk.Builder(); for (Entry entry : entries) { Index index = new Index.Builder(entry).refresh(true).index(Entry.INDEX_NAME).type(Entry.DOC_TYPE) .build();/*from w ww. j a va 2s. c om*/ bulkBuilder.addAction(index); } try { jestClient.execute(bulkBuilder.build()); log.info("re-indexed!"); return CompletableFuture.completedFuture(null); } catch (Exception e) { CompletableFuture<Void> f = new CompletableFuture<>(); f.completeExceptionally(e); return f; } }
From source file:com.teradata.benchto.driver.execution.ExecutionSynchronizer.java
/** * Executes {@code callable} when time comes. The {@code callable} gets executed immediately, without * offloading to a backghround thread, if execution time requested has already passed. *///from w ww. ja v a 2s. c o m public <T> CompletableFuture<T> execute(Instant when, Callable<T> callable) { if (!Instant.now().isBefore(when)) { // Run immediately. try { return completedFuture(callable.call()); } catch (Exception e) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } } long delay = Instant.now().until(when, ChronoUnit.MILLIS); CompletableFuture<T> future = new CompletableFuture<>(); executorService.schedule(() -> { try { future.complete(callable.call()); } catch (Throwable e) { future.completeExceptionally(e); throw e; } return null; }, delay, MILLISECONDS); return future; }
From source file:org.apache.trafficcontrol.client.trafficops.TOSession.java
public CompletableFuture<Boolean> login(final String username, final String password) { URI uri;/*from www . j a v a2 s . c o m*/ try { uri = this.newUriBuilder("user/login.json").build(); } catch (Throwable e) { final CompletableFuture<Boolean> f = new CompletableFuture<>(); f.completeExceptionally(e); return f; } LOG.debug("Logging into: {}", uri); return ResponseFuture.builder().setHandleException((f, t) -> { f.completeExceptionally( new LoginException(String.format("Failed to login with username %s", username), t)); }).setMethod(ResponseFuture.Method.POST).setUri(uri).setSession(this.restClient()) .setBody(gson.toJson(ImmutableMap.<String, String>of("u", username, "p", password))).build() .thenApply(r -> { isLoggedIn = true; return true; }); }
From source file:org.apache.trafficcontrol.client.trafficops.TOSession.java
public CompletableFuture<Response.CollectionResponse> getServers(final Map<String, ?> filterParams) { URI uri;//w w w .j a v a2s .c o m try { uri = this.newUriBuilder("servers.json").setParameters(this.toPairs(filterParams)).build(); } catch (Throwable e) { final CompletableFuture<Response.CollectionResponse> f = new CompletableFuture<>(); f.completeExceptionally(e); return f; } return ResponseFuture.builder(Response.CollectionResponse.class).setMethod(ResponseFuture.Method.GET) .setUri(uri).setSession(this.restClient()).build(); }