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.apache.twill.internal.AbstractZKServiceController.java
/** * Sends a {@link Message} to the remote service. Returns a future that will be completed when the message * has been processed./* www .j a v a2s. c om*/ * @param message The message to send. * @param result Object to set into the future when message is being processed. * @param <V> Type of the result. * @return A {@link ListenableFuture} that will be completed when the message has been processed. */ protected final synchronized <V> ListenableFuture<V> sendMessage(Message message, V result) { if (!isRunning()) { return Futures.immediateFailedFuture( new IllegalStateException("Cannot send message to non-running application")); } final ListenableFuture<V> messageFuture = ZKMessages.sendMessage(zkClient, getMessagePrefix(), message, result); messageFutures.add(messageFuture); messageFuture.addListener(new Runnable() { @Override public void run() { // If the completion is triggered when stopping, do nothing. if (state() == State.STOPPING) { return; } synchronized (AbstractZKServiceController.this) { messageFutures.remove(messageFuture); } } }, Threads.SAME_THREAD_EXECUTOR); return messageFuture; }
From source file:com.facebook.buck.rules.modern.builders.LocalContentAddressedStorage.java
public LocalContentAddressedStorage(Path cacheDir, Protocol protocol) { this.cacheDir = cacheDir; this.protocol = protocol; ExecutorService uploadService = MostExecutors.newMultiThreadExecutor("local-cas-write", 4); this.uploader = new MultiThreadedBlobUploader(MISSING_CHECK_LIMIT, UPLOAD_SIZE_LIMIT, uploadService, new CasBlobUploader() { @Override/*from ww w. j a v a 2 s . c om*/ public ImmutableList<UploadResult> batchUpdateBlobs(ImmutableList<UploadData> blobData) { return LocalContentAddressedStorage.this.batchUpdateBlobs(blobData); } @Override public ImmutableSet<String> getMissingHashes(List<Protocol.Digest> requiredDigests) { return findMissing(requiredDigests).map(Protocol.Digest::getHash) .collect(ImmutableSet.toImmutableSet()); } }); AsyncBlobFetcher fetcher = new AsyncBlobFetcher() { @Override public ListenableFuture<ByteBuffer> fetch(Protocol.Digest digest) { try (InputStream stream = getData(digest)) { return Futures.immediateFuture(ByteBuffer.wrap(ByteStreams.toByteArray(stream))); } catch (IOException e) { return Futures.immediateFailedFuture(e); } } @Override public void fetchToStream(Protocol.Digest digest, OutputStream outputStream) { throw new UnsupportedOperationException(); } }; this.outputsMaterializer = new OutputsMaterializer(fetcher, protocol); this.inputsMaterializer = new InputsMaterializer(protocol, new InputsMaterializer.Delegate() { @Override public void materializeFile(Path root, FileNode file) throws IOException { Path path = getPath(file.getDigest().getHash()); Preconditions.checkState(Files.exists(path)); // As this file could potentially be materialized as both executable and // non-executable, and // links share that, we need two concrete versions of the file. if (file.getIsExecutable()) { Path exePath = path.getParent().resolve(path.getFileName() + ".x"); if (!Files.exists(exePath)) { try (AutoUnlocker ignored = fileLock.writeLock(exePath.toString())) { if (!Files.exists(exePath)) { Path tempPath = path.getParent().resolve(path.getFileName() + ".x.tmp"); Files.copy(path, tempPath); Preconditions.checkState(tempPath.toFile().setExecutable(true)); Files.move(tempPath, exePath); } } } path = exePath; } Path target = root.resolve(file.getName()); Preconditions.checkState(target.normalize().startsWith(root)); Files.createLink(target, path); } @Override public InputStream getData(Protocol.Digest digest) throws IOException { return LocalContentAddressedStorage.this.getData(digest); } }); }
From source file:com.veloxsw.impl.NcclientServiceImpl.java
@Override public Future<RpcResult<WhichPythonOutput>> whichPython() { try {//from w w w . ja va 2s . c o m final UnixCommandReturnDTO ret = execCommand("which python"); final WhichPythonOutputBuilder builder = new WhichPythonOutputBuilder(); builder.setOutput(ret.getOutput()); builder.setError(ret.getError()); builder.setReturnCode(ret.getReturnCode()); return RpcResultBuilder.success(builder).buildFuture(); } catch (final IOException | InterruptedException e) { return Futures.immediateFailedFuture(e); } }
From source file:co.cask.cdap.common.zookeeper.coordination.ResourceCoordinatorClient.java
/** * Submits the given {@link ResourceRequirement} for allocation. * * @param requirement The requirement to be submitted. * @return A {@link ListenableFuture} that will be completed when submission is completed and it'll carry the * submitted requirement as result. The future will fail if failed to submit the requirement. Calling * {@link ListenableFuture#cancel(boolean)} has no effect. *///from w w w.j a va 2 s . c o m public ListenableFuture<ResourceRequirement> submitRequirement(ResourceRequirement requirement) { try { String zkPath = CoordinationConstants.REQUIREMENTS_PATH + "/" + requirement.getName(); byte[] data = CoordinationConstants.RESOURCE_REQUIREMENT_CODEC.encode(requirement); return ZKExtOperations.createOrSet(zkClient, zkPath, data, requirement, CoordinationConstants.MAX_ZK_FAILURE_RETRY); } catch (Exception e) { return Futures.immediateFailedFuture(e); } }
From source file:org.eclipse.neoscada.da.server.iec60870.Hive.java
protected synchronized ListenableFuture<Void> performAddConnection(final String id, final ConnectionConfiguration configuration) { logger.debug("adding connection - id: {}, cfg: {}", id, configuration); if (this.executor == null) { logger.debug("Hive is not started"); return Futures.immediateFailedFuture(new IllegalStateException("Hive is not started")); }/* w ww . j a va 2s. co m*/ final ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() { @Override public Void call() throws Exception { try { handleAddConnection(id, configuration); } catch (final Exception e) { logger.warn("Failed to create connection", e); throw new InvocationTargetException(e); } return null; } }); this.executor.execute(task); return task; }
From source file:org.thingsboard.server.dao.util.BufferedRateLimiter.java
private ListenableFuture<Void> putInQueue() { int size = queue.size(); if (size > maxQueueSize.get()) { maxQueueSize.set(size);/* ww w.j a va 2 s . c o m*/ } if (queue.remainingCapacity() > 0) { try { LockedFuture lockedFuture = createLockedFuture(); if (!queue.offer(lockedFuture, 1, TimeUnit.SECONDS)) { lockedFuture.cancelFuture(); return Futures.immediateFailedFuture(new BufferLimitException()); } if (permits.get() < permitsLimit) { reprocessQueue(); } return lockedFuture.future; } catch (InterruptedException e) { return Futures.immediateFailedFuture(new BufferLimitException()); } } return Futures.immediateFailedFuture(new BufferLimitException()); }
From source file:net.oneandone.troilus.DBSession.java
/** * @param statement te statement to execute in an async manner * @return the resultset future//from w ww . j a va 2 s .co m */ public ListenableFuture<ResultSet> executeAsync(Statement statement) { try { return getSession().executeAsync(statement); } catch (InvalidQueryException | DriverInternalError e) { cleanUp(); LOG.warn("could not execute statement", e); return Futures.immediateFailedFuture(e); } }
From source file:org.dcache.poolmanager.PoolManagerHandlerSubscriber.java
@PostConstruct public synchronized void start() { current = transformAsync(startGate,/*www . ja v a2s . co m*/ ignored -> CellStub.transform(query(new PoolMgrGetHandler()), PoolMgrGetHandler::getHandler)); Futures.addCallback(current, new FutureCallback<SerializablePoolManagerHandler>() { @Override public void onSuccess(SerializablePoolManagerHandler handler) { synchronized (PoolManagerHandlerSubscriber.this) { try { current = Futures.immediateFuture(handler); if (!isStopped) { ListenableFuture<SerializablePoolManagerHandler> next = CellStub.transform( query(new PoolMgrGetUpdatedHandler(handler.getVersion())), PoolMgrGetHandler::getHandler); Futures.addCallback(next, this); } } catch (Throwable t) { current = Futures.immediateFailedFuture(t); LOGGER.error( "Failure in pool manager handler subscriber. Please report to support@dcache.org.", t); throw t; } } } @Override public void onFailure(Throwable t) { synchronized (PoolManagerHandlerSubscriber.this) { current = Futures.immediateFailedFuture(t); } } }); }
From source file:org.thingsboard.server.dao.nosql.RateLimitedResultSetFuture.java
@Override public void addListener(Runnable listener, Executor executor) { originalFuture.addListener(() -> { try {/* ww w.jav a 2 s . c om*/ ResultSetFuture resultSetFuture = Uninterruptibles.getUninterruptibly(originalFuture); resultSetFuture.addListener(listener, executor); } catch (CancellationException | ExecutionException e) { Futures.immediateFailedFuture(e).addListener(listener, executor); } }, executor); }
From source file:com.orangerhymelabs.helenus.cassandra.table.TableService.java
public ListenableFuture<Table> update(Table table) { ListenableFuture<Boolean> dbFuture = databases.exists(table.databaseName()); return Futures.transformAsync(dbFuture, new AsyncFunction<Boolean, Table>() { @Override/* www. j av a2 s. c o m*/ public ListenableFuture<Table> apply(Boolean exists) throws Exception { if (exists) { try { ValidationEngine.validateAndThrow(table); return tables.update(table); } catch (ValidationException e) { return Futures.immediateFailedFuture(e); } } else { return Futures.immediateFailedFuture( new ItemNotFoundException("Database not found: " + table.databaseName())); } } }, MoreExecutors.directExecutor()); }