List of usage examples for com.google.common.util.concurrent Futures immediateFailedFuture
@CheckReturnValue public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable)
From source file:org.thingsboard.server.service.script.AbstractNashornJsInvokeService.java
@Override protected ListenableFuture<Object> doInvokeFunction(UUID scriptId, String functionName, Object[] args) { try {//w ww.ja v a 2s . co m Object result; if (useJsSandbox()) { result = sandbox.getSandboxedInvocable().invokeFunction(functionName, args); } else { result = ((Invocable) engine).invokeFunction(functionName, args); } return Futures.immediateFuture(result); } catch (Exception e) { onScriptExecutionError(scriptId); return Futures.immediateFailedFuture(e); } }
From source file:com.google.devtools.build.lib.remote.ByteStreamBuildEventArtifactUploader.java
@Override public ListenableFuture<PathConverter> upload(Map<Path, LocalFile> files) { if (files.isEmpty()) { return Futures.immediateFuture(PathConverter.NO_CONVERSION); }//w w w. j a v a2s . c om List<ListenableFuture<PathDigestPair>> uploads = new ArrayList<>(files.size()); Context prevCtx = ctx.attach(); try { for (Path file : files.keySet()) { Chunker chunker = new Chunker(file); Digest digest = chunker.digest(); ListenableFuture<PathDigestPair> upload = Futures.transform( uploader.uploadBlobAsync(chunker, /*forceUpload=*/false), unused -> new PathDigestPair(file, digest), MoreExecutors.directExecutor()); uploads.add(upload); } return Futures.transform(Futures.allAsList(uploads), (uploadsDone) -> new PathConverterImpl(remoteServerInstanceName, uploadsDone), MoreExecutors.directExecutor()); } catch (IOException e) { return Futures.immediateFailedFuture(e); } finally { ctx.detach(prevCtx); } }
From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java
public ListenableFuture<T> create(T entity) { ListenableFuture<ResultSet> future = submitCreate(entity); return Futures.transformAsync(future, new AsyncFunction<ResultSet, T>() { @Override// w w w. jav a 2s . co m public ListenableFuture<T> apply(ResultSet result) throws Exception { if (result.wasApplied()) { return Futures.immediateFuture(entity); } return Futures.immediateFailedFuture(new DuplicateItemException(entity.toString())); } }, MoreExecutors.directExecutor()); }
From source file:io.v.rx.syncbase.RxTable.java
private <T> Observable<T> getInitial(final BatchDatabase db, final String tableName, final String key, final TypeToken<T> tt, final T defaultValue) { @SuppressWarnings("unchecked") final ListenableFuture<T> fromGet = (ListenableFuture<T>) db.getTable(tableName).get(mVContext, key, tt == null ? Object.class : tt.getType()); return toObservable(Futures.withFallback(fromGet, t -> t instanceof NoExistException ? Futures.immediateFuture(defaultValue) : Futures.immediateFailedFuture(t))); }
From source file:com.proofpoint.event.monitor.test.SerialScheduledExecutorService.java
@Override public <T> Future<T> submit(Runnable runnable, T t) { try {//from w w w . j a v a 2s. c o m runnable.run(); return Futures.immediateFuture(t); } catch (Exception e) { return Futures.immediateFailedFuture(e); } }
From source file:de.dfki.kiara.impl.AbstractMessageConnection.java
@Override public ListenableFuture<Void> send(Message message) { if (message == null) { throw new NullPointerException("message"); }/* w ww. j a v a 2 s. c o m*/ try { final TransportMessage tmessage; synchronized (messageMap) { tmessage = messageMap.remove(message.getRequestMessage()); } final TransportMessage tresponse = transportConnection.createTransportMessage(tmessage); tresponse.setPayload(message.getMessageData()); tresponse.setContentType(message.getProtocol().getMimeType()); return transportConnection.send(tresponse); } catch (Exception ex) { logger.error("Could not send message", ex); return Futures.immediateFailedFuture(ex); } }
From source file:org.esbtools.eventhandler.PollingNotificationProcessorRoute.java
@Override public void configure() throws Exception { from("timer:pollForNotifications" + id + "?period=" + pollingInterval.toMillis()) .routeId("notificationProcessor-" + id).process(exchange -> { List<? extends Notification> notifications = notificationRepository .retrieveOldestNotificationsUpTo(batchSize); Map<Notification, Future<Collection<DocumentEvent>>> notificationsToFutureEvents = new HashMap<>( notifications.size()); // Intentionally cache all futures before waiting for any. for (Notification notification : notifications) { try { Future<Collection<DocumentEvent>> futureEvents = notification.toDocumentEvents(); notificationsToFutureEvents.put(notification, futureEvents); } catch (Exception e) { log.error("Failed to get future document events for notification: " + notification, e); notificationsToFutureEvents.put(notification, Futures.immediateFailedFuture(e)); }//from ww w. j a va 2s. c om } Map<Notification, Collection<DocumentEvent>> notificationsToDocumentEvents = new HashMap<>(); List<FailedNotification> failedNotifications = new ArrayList<>(); for (Entry<Notification, Future<Collection<DocumentEvent>>> notificationToFutureEvents : notificationsToFutureEvents .entrySet()) { Notification notification = notificationToFutureEvents.getKey(); Future<Collection<DocumentEvent>> futureEvents = notificationToFutureEvents.getValue(); try { Collection<DocumentEvent> events = futureEvents.get(processTimeout.toMillis(), TimeUnit.MILLISECONDS); notificationsToDocumentEvents.put(notification, events); } catch (ExecutionException | InterruptedException e) { log.error("Failed to get document events for notification: " + notification, e); failedNotifications.add(new FailedNotification(notification, e)); } } Iterator<Entry<Notification, Collection<DocumentEvent>>> notificationsToEventsIterator = notificationsToDocumentEvents .entrySet().iterator(); while (notificationsToEventsIterator.hasNext()) { Entry<Notification, Collection<DocumentEvent>> notificationToEvents = notificationsToEventsIterator .next(); try { notificationRepository.ensureTransactionActive(notificationToEvents.getKey()); } catch (Exception e) { notificationsToEventsIterator.remove(); if (log.isWarnEnabled()) { log.warn("Notification transaction no longer active, not processing: " + notificationToEvents.getKey(), e); } } } List<DocumentEvent> documentEvents = notificationsToDocumentEvents.values().stream() .flatMap(Collection::stream).collect(Collectors.toList()); log.debug("Persisting {} document events via route {}: {}", documentEvents.size(), exchange.getFromRouteId(), documentEvents); try { documentEventRepository.addNewDocumentEvents(documentEvents); } catch (Exception e) { log.error("Failed to persist new document events from notifications. Rolling " + "back processing. Document events were: " + documentEvents, e); notificationsToDocumentEvents.clear(); } notificationRepository.markNotificationsProcessedOrFailed( notificationsToDocumentEvents.keySet(), failedNotifications); }); }
From source file:org.opendaylight.sxp.route.core.RouteReactorZipImpl.java
@Override public ListenableFuture<Void> updateRouting(@Nullable final SxpClusterRoute oldRoute, @Nullable final SxpClusterRoute newRoute) { // with state compression ListenableFuture<Void> futureResult; try {// w w w .j a v a 2s . c om queueGuard.acquire(); if (compressionQueue.isEmpty()) { compressionQueue.add(new MutablePair<>(oldRoute, newRoute)); // schedule task futureResult = servicePool.submit(updateRouteTask); } else { // compress, expect that task is already scheduled compressionQueue.peek().setRight(newRoute); futureResult = COMPRESSED_FUTURE_RESULT; LOG.trace("route update request got state compressed - firing immediate future"); } queueGuard.release(); } catch (Exception e) { LOG.warn("failed to get lock upon compression queue: {}", e.getMessage()); futureResult = Futures.immediateFailedFuture(e); } return futureResult; }
From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentService.java
public ListenableFuture<Document> create(String database, String table, Document document) { ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(database, table); return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, Document>() { @Override//from w w w . ja v a 2s. c o m public ListenableFuture<Document> apply(AbstractDocumentRepository docRepo) throws Exception { try { ValidationEngine.validateAndThrow(document); Document newDoc = docRepo.create(document).get(); updateViews(newDoc); return Futures.immediateFuture(newDoc); } catch (ValidationException e) { return Futures.immediateFailedFuture(e); } } private void updateViews(Document document) throws InterruptedException, ExecutionException { List<View> tableViews = getTableViews(database, table).get(); tableViews.forEach(new Consumer<View>() { @Override public void accept(View v) { try { Identifier id = v.identifierFrom(document); if (id != null) { Document viewDoc = new Document(document.object()); viewDoc.identifier(id); Document newView = createViewDocument(v, viewDoc).get(); System.out.println(newView.createdAt()); } } catch (KeyDefinitionException e) { e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } // private ListenableFuture<List<Document>> updateViews(Document document) // { // ListenableFuture<List<View>> tableViews = getTableViews(database, table); // return Futures.transformAsync(tableViews, new AsyncFunction<List<View>, List<Document>>() // { // @Override // public ListenableFuture<List<Document>> apply(List<View> input) // throws Exception // { // List<ListenableFuture<Document>> newDocs = new ArrayList<>(input.size()); // input.parallelStream().forEach(new Consumer<View>() // { // @Override // public void accept(View v) // { // try // { // Identifier id = v.identifierFrom(document); // // if (id != null) // { // Document viewDoc = new Document(document.object()); // viewDoc.identifier(id); // newDocs.add(createViewDocument(v, document)); // } // } // catch (KeyDefinitionException e) // { // e.printStackTrace(); // } // } // }); // // return null; // } // }); // } }, MoreExecutors.directExecutor()); }
From source file:com.vmware.photon.controller.common.zookeeper.LeaderElectedServiceNode.java
@Override protected synchronized ListenableFuture<Void> joinCondition() { logger.debug("Creating the leader latch for {}", serviceName); leaderLatch = new LeaderLatch(zkClient, "/elections/" + serviceName, address.toString()); try {// ww w .j a v a2s .c o m leaderLatch.start(); } catch (Exception e) { return Futures.immediateFailedFuture(e); } final SettableFuture<Void> promise = SettableFuture.create(); waitDone = new CountDownLatch(1); leaderWait = executorService.submit(new Runnable() { @Override public void run() { try { leaderLatch.await(); logger.debug("{} is a leader now", serviceName); promise.set(VOID); } catch (InterruptedException e) { logger.debug("Leader latch waiting for {} interrupted", serviceName); waitDone.countDown(); // See comment below to understand why we do that both in 'finally' and here promise.setException(new InterruptedException("Interrupted while waiting for leader election")); Thread.currentThread().interrupt(); } catch (Exception e) { promise.setException(e); } finally { // There is an interesting race condition here: // 1. Leader elected service starts up and it's not a leader, so it blocks on leader latch acquisition; // 2. ZK goes away, acquisition gets interrupted; // 3. failure callback for the acquisition gets fired and (currently) runs System.exit(0); // 4. According to the Java language spec 'finally' block is NOT guaranteed to run when JVM is exiting BUT // we have a shutdown hook that attempts to leave the service and triggers 'cleanup' method below, where // it blocks indefinitely on waiting for 'waitDone' countdown latch IF 'finally' doesn't execute. // // TODO(olegs): maybe find a cleaner way orchestrate the shutdown? waitDone.countDown(); } } }); return promise; }