List of usage examples for com.google.common.util.concurrent Futures immediateFailedFuture
@CheckReturnValue public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable)
From source file:co.cask.cdap.internal.app.runtime.AbstractProgramController.java
@Override public final ListenableFuture<ProgramController> stop() { if (!state.compareAndSet(State.STARTING, State.STOPPING) && !state.compareAndSet(State.ALIVE, State.STOPPING) && !state.compareAndSet(State.SUSPENDED, State.STOPPING)) { return Futures .immediateFailedFuture(new IllegalStateException("Stopping not allowed").fillInStackTrace()); }//from ww w . j av a2 s. com final SettableFuture<ProgramController> result = SettableFuture.create(); executor(State.STOPPING).execute(new Runnable() { @Override public void run() { try { caller.stopping(); doStop(); state.set(State.KILLED); result.set(AbstractProgramController.this); caller.killed(); } catch (Throwable t) { error(t, result); } } }); return result; }
From source file:co.cask.cdap.internal.app.deploy.InMemoryConfigurator.java
/** * Executes the <code>Application.configure</code> within the same JVM. * <p>//from ww w. j a va 2 s. co m * This method could be dangerous and should be used only in standalone mode. * </p> * * @return A instance of {@link ListenableFuture}. */ @Override public ListenableFuture<ConfigResponse> config() { SettableFuture<ConfigResponse> result = SettableFuture.create(); try { // Load the JAR using the JAR class load and load the manifest file. Manifest manifest = BundleJarUtil.getManifest(archive); Preconditions.checkArgument(manifest != null, "Failed to load manifest from %s", archive.toURI()); Preconditions.checkArgument(manifest.getMainAttributes() != null, "Failed to load manifest attributes from %s", archive.toURI()); String mainClassName = manifest.getMainAttributes().getValue(ManifestFields.MAIN_CLASS); Preconditions.checkArgument(mainClassName != null && !mainClassName.isEmpty(), "Main class attribute cannot be empty"); File unpackedJarDir = Files.createTempDir(); try (Archive archive = new Archive(BundleJarUtil.unpackProgramJar(this.archive, unpackedJarDir), mainClassName)) { Object appMain = archive.getMainClass().newInstance(); if (!(appMain instanceof Application)) { throw new IllegalStateException(String.format("Application main class is of invalid type: %s", appMain.getClass().getName())); } String bundleVersion = manifest.getMainAttributes().getValue(ManifestFields.BUNDLE_VERSION); Application app = (Application) appMain; ConfigResponse response = createResponse(app, bundleVersion); result.set(response); } finally { removeDir(unpackedJarDir); } return result; } catch (Throwable t) { LOG.error(t.getMessage(), t); return Futures.immediateFailedFuture(t); } }
From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java
public ListenableFuture<Boolean> delete(Identifier id) { ListenableFuture<ResultSet> future = submitDelete(id); return Futures.transformAsync(future, new AsyncFunction<ResultSet, Boolean>() { @Override/*w w w . jav a 2 s .c o m*/ public ListenableFuture<Boolean> apply(ResultSet result) { if (!result.wasApplied()) { return Futures.immediateFailedFuture(new ItemNotFoundException(id.toString())); } return Futures.immediateFuture(true); } }, MoreExecutors.directExecutor()); }
From source file:com.mypurecloud.sdk.v2.api.BillingApiAsync.java
/** * Get a report of the billable usages (e.g. licenses and devices utilized) for a given period. * /*from w w w . j a v a 2 s .c o m*/ * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<BillingUsageReport>> getBillingReportsBillableusageAsync(ApiRequest<Void> request, final AsyncApiCallback<ApiResponse<BillingUsageReport>> callback) { try { final SettableFuture<ApiResponse<BillingUsageReport>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<BillingUsageReport>() { }, new AsyncApiCallback<ApiResponse<BillingUsageReport>>() { @Override public void onCompleted(ApiResponse<BillingUsageReport> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<BillingUsageReport> response = (ApiResponse<BillingUsageReport>) (ApiResponse<?>) exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<BillingUsageReport> response = (ApiResponse<BillingUsageReport>) (ApiResponse<?>) (new ApiException( exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } }
From source file:zipkin.storage.cassandra.DeduplicatingExecutor.java
/** * Upon success, the statement's result will be remembered and returned for all subsequent * executions with the same key, subject to a local TTL. * * <p>The results of failed statements are forgotten based on the supplied key. * * @param statement what to conditionally execute * @param key determines equivalence of the bound statement * @return future of work initiated by this or a previous request *//*ww w . j a v a 2 s . c o m*/ ListenableFuture<Void> maybeExecuteAsync(BoundStatement statement, Object key) { BoundStatementKey cacheKey = new BoundStatementKey(statement, key); try { ListenableFuture<Void> result = cache.get(new BoundStatementKey(statement, key)); // A future could be constructed directly (i.e. immediate future), get the value to // see if it was exceptional. If so, the catch block will invalidate that key. if (result.isDone()) result.get(); return result; } catch (UncheckedExecutionException | ExecutionException e) { cache.invalidate(cacheKey); return Futures.immediateFailedFuture(e.getCause()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError(); } }
From source file:com.facebook.buck.remoteexecution.util.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//w w w .ja v a 2s . c o m 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 ListenableFuture<Void> fetchToStream(Digest digest, OutputStream outputStream) { try (InputStream stream = getData(digest)) { ByteStreams.copy(stream, outputStream); return Futures.immediateFuture(null); } catch (IOException e) { return Futures.immediateFailedFuture(e); } } }; 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), "Path %s doesn't exist.", 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()); Path normalized = target.normalize(); Preconditions.checkState(normalized.startsWith(root), "%s doesn't start with %s.", normalized, root); Files.createLink(target, path); } @Override public InputStream getData(Protocol.Digest digest) throws IOException { return LocalContentAddressedStorage.this.getData(digest); } }); }
From source file:org.opendaylight.faas.fabric.general.EndPointRegister.java
@Override public Future<RpcResult<RegisterEndpointOutput>> registerEndpoint(RegisterEndpointInput input) { final RpcResultBuilder<RegisterEndpointOutput> resultBuilder = RpcResultBuilder .<RegisterEndpointOutput>success(); final RegisterEndpointOutputBuilder outputBuilder = new RegisterEndpointOutputBuilder(); final FabricId fabricid = input.getFabricId(); final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricid); if (fabricObj == null) { return Futures.immediateFailedFuture(new IllegalArgumentException("fabric is not exist!")); }//w w w . ja v a2s . c o m Uuid epId = input.getEndpointUuid(); if (epId == null) { epId = new Uuid(UUID.randomUUID().toString()); } final Uuid newepId = epId; final InstanceIdentifier<Endpoint> eppath = Constants.DOM_ENDPOINTS_PATH.child(Endpoint.class, new EndpointKey(newepId)); EndpointBuilder epBuilder = new EndpointBuilder(); epBuilder.setEndpointUuid(newepId); epBuilder.setGateway(input.getGateway()); epBuilder.setIpAddress(input.getIpAddress()); epBuilder.setLocation(input.getLocation()); epBuilder.setLogicalLocation(input.getLogicalLocation()); epBuilder.setMacAddress(input.getMacAddress()); epBuilder.setPublicIp(input.getPublicIp()); epBuilder.setOwnFabric(fabricid); ReadWriteTransaction trans = dataBroker.newReadWriteTransaction(); trans.put(LogicalDatastoreType.OPERATIONAL, eppath, epBuilder.build(), true); CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit(); return Futures.transform(future, new AsyncFunction<Void, RpcResult<RegisterEndpointOutput>>() { @Override public ListenableFuture<RpcResult<RegisterEndpointOutput>> apply(Void input) throws Exception { outputBuilder.setEndpointId(newepId); return Futures.immediateFuture(resultBuilder.withResult(outputBuilder.build()).build()); } }, executor); }
From source file:org.opendaylight.groupbasedpolicy.renderer.ofoverlay.arp.ArpSender.java
/** * Sends ARP Request as packet-out from the given port (node connector). * * @param senderAddress the addresses used in sender part of ARP packet * @param tpa the target protocol address, in this case IPv4 address for which MAC should be * discovered/*from w w w. j av a 2 s. co m*/ * @param egressNc the path to node connector from where the ARP packet will be sent * @return future result about success of packet-out */ public ListenableFuture<RpcResult<Void>> sendArp(ArpMessageAddress senderAddress, Ipv4Address tpa, InstanceIdentifier<NodeConnector> egressNc) { checkNotNull(senderAddress); checkNotNull(tpa); checkNotNull(egressNc); final Ethernet arpFrame = createArpFrame(senderAddress, tpa); byte[] arpFrameAsBytes; try { arpFrameAsBytes = arpFrame.serialize(); } catch (PacketException e) { LOG.warn("Serializition of ARP packet is not successful.", e); if (LOG.isDebugEnabled()) { LOG.debug("ARP packet: {}", ArpUtils.getArpFrameToStringFormat(arpFrame)); } return Futures.immediateFailedFuture(e); } // Generate packet with destination switch and port TransmitPacketInput packet = new TransmitPacketInputBuilder().setEgress(new NodeConnectorRef(egressNc)) .setNode(new NodeRef(egressNc.firstIdentifierOf(Node.class))).setPayload(arpFrameAsBytes).build(); if (LOG.isTraceEnabled()) { LOG.trace("Sending ARP REQUEST \n{}", ArpUtils.getArpFrameToStringFormat(arpFrame)); } Future<RpcResult<Void>> futureTransmitPacketResult = packetProcessingService.transmitPacket(packet); return JdkFutureAdapters.listenInPoolThread(futureTransmitPacketResult); }
From source file:com.microsoftopentechnologies.wacommon.adauth.BrowserLauncherEclipse.java
@Override public ListenableFuture<Void> browseAsync(final String url, final String redirectUri, final String callbackUrl, final String windowTitle, final boolean noShell) { try {/*ww w . j a va 2 s.c o m*/ Display.getDefault().syncExec(new Runnable() { public void run() { // get the display from Eclipse Display display = PlatformUI.getWorkbench().getDisplay(); Shell shell = (parentShell != null) ? new Shell(parentShell, SWT.PRIMARY_MODAL | SWT.CLOSE | SWT.TITLE | SWT.BORDER) : new Shell(display, SWT.APPLICATION_MODAL | SWT.CLOSE | SWT.TITLE | SWT.BORDER); shell.setText(windowTitle); Browser browser; ADAuthCodeCallback authCodeCallback = new ADAuthCodeCallback(display, shell, callbackUrl); shell.setLayout(new FillLayout()); Monitor monitor = display.getPrimaryMonitor(); Rectangle bounds = monitor.getBounds(); Dimension size = new Dimension((int) (bounds.width * 0.40), (int) (bounds.height * 0.70)); shell.setSize(size.width, size.height); shell.setLocation((bounds.width - size.width) / 2, (bounds.height - size.height) / 2); shell.setActive(); try { browser = new org.eclipse.swt.browser.Browser(shell, SWT.NONE); } catch (SWTError err) { authCodeCallback.onFailed(Messages.browserErr + " \n" + err.getMessage()); throw err; } BrowserLocationListener locationListener = new BrowserLocationListener(redirectUri, authCodeCallback); browser.addLocationListener(locationListener); if (noShell) { BrowserSilentProgressListener progressListener = new BrowserSilentProgressListener( authCodeCallback); browser.addProgressListener(progressListener); } browser.setUrl(url); if (!noShell) { shell.open(); } while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } }); } catch (SWTError ex) { return Futures.immediateFuture(null); } // notify the caller that the window was closed try { httpRequest(new URI(callbackUrl).resolve("closed").toURL()); } catch (IOException e) { return Futures.immediateFailedFuture(e); } catch (URISyntaxException e) { return Futures.immediateFailedFuture(e); } return Futures.immediateFuture(null); }
From source file:com.metamx.http.client.NettyHttpClient.java
@Override public <Intermediate, Final> ListenableFuture<Final> go(final Request request, final HttpResponseHandler<Intermediate, Final> handler, final Duration requestReadTimeout) { final HttpMethod method = request.getMethod(); final URL url = request.getUrl(); final Multimap<String, String> headers = request.getHeaders(); final String requestDesc = String.format("%s %s", method, url); if (log.isDebugEnabled()) { log.debug("[%s] starting", requestDesc); }//w ww . ja v a2 s . c o m // Block while acquiring a channel from the pool, then complete the request asynchronously. final Channel channel; final String hostKey = getPoolKey(url); final ResourceContainer<ChannelFuture> channelResourceContainer = pool.take(hostKey); final ChannelFuture channelFuture = channelResourceContainer.get().awaitUninterruptibly(); if (!channelFuture.isSuccess()) { channelResourceContainer.returnResource(); // Some other poor sap will have to deal with it... return Futures.immediateFailedFuture( new ChannelException("Faulty channel in resource pool", channelFuture.getCause())); } else { channel = channelFuture.getChannel(); } final String urlFile = Strings.nullToEmpty(url.getFile()); final HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, urlFile.isEmpty() ? "/" : urlFile); if (!headers.containsKey(HttpHeaders.Names.HOST)) { httpRequest.headers().add(HttpHeaders.Names.HOST, getHost(url)); } httpRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); for (Map.Entry<String, Collection<String>> entry : headers.asMap().entrySet()) { String key = entry.getKey(); for (String obj : entry.getValue()) { httpRequest.headers().add(key, obj); } } if (request.hasContent()) { httpRequest.setContent(request.getContent()); } final long readTimeout = getReadTimeout(requestReadTimeout); final SettableFuture<Final> retVal = SettableFuture.create(); if (readTimeout > 0) { channel.getPipeline().addLast(READ_TIMEOUT_HANDLER_NAME, new ReadTimeoutHandler(timer, readTimeout, TimeUnit.MILLISECONDS)); } channel.getPipeline().addLast(LAST_HANDLER_NAME, new SimpleChannelUpstreamHandler() { private volatile ClientResponse<Intermediate> response = null; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (log.isDebugEnabled()) { log.debug("[%s] messageReceived: %s", requestDesc, e.getMessage()); } try { Object msg = e.getMessage(); if (msg instanceof HttpResponse) { HttpResponse httpResponse = (HttpResponse) msg; if (log.isDebugEnabled()) { log.debug("[%s] Got response: %s", requestDesc, httpResponse.getStatus()); } response = handler.handleResponse(httpResponse); if (response.isFinished()) { retVal.set((Final) response.getObj()); } if (!httpResponse.isChunked()) { finishRequest(); } } else if (msg instanceof HttpChunk) { HttpChunk httpChunk = (HttpChunk) msg; if (log.isDebugEnabled()) { log.debug("[%s] Got chunk: %sB, last=%s", requestDesc, httpChunk.getContent().readableBytes(), httpChunk.isLast()); } if (httpChunk.isLast()) { finishRequest(); } else { response = handler.handleChunk(response, httpChunk); if (response.isFinished() && !retVal.isDone()) { retVal.set((Final) response.getObj()); } } } else { throw new IllegalStateException(String.format("Unknown message type[%s]", msg.getClass())); } } catch (Exception ex) { log.warn(ex, "[%s] Exception thrown while processing message, closing channel.", requestDesc); if (!retVal.isDone()) { retVal.set(null); } channel.close(); channelResourceContainer.returnResource(); throw ex; } } private void finishRequest() { ClientResponse<Final> finalResponse = handler.done(response); if (!finalResponse.isFinished()) { throw new IllegalStateException( String.format("[%s] Didn't get a completed ClientResponse Object from [%s]", requestDesc, handler.getClass())); } if (!retVal.isDone()) { retVal.set(finalResponse.getObj()); } removeHandlers(); channelResourceContainer.returnResource(); } @Override public void exceptionCaught(ChannelHandlerContext context, ExceptionEvent event) throws Exception { if (log.isDebugEnabled()) { final Throwable cause = event.getCause(); if (cause == null) { log.debug("[%s] Caught exception", requestDesc); } else { log.debug(cause, "[%s] Caught exception", requestDesc); } } retVal.setException(event.getCause()); // response is non-null if we received initial chunk and then exception occurs if (response != null) { handler.exceptionCaught(response, event.getCause()); } removeHandlers(); try { channel.close(); } catch (Exception e) { // ignore } finally { channelResourceContainer.returnResource(); } context.sendUpstream(event); } @Override public void channelDisconnected(ChannelHandlerContext context, ChannelStateEvent event) throws Exception { if (log.isDebugEnabled()) { log.debug("[%s] Channel disconnected", requestDesc); } // response is non-null if we received initial chunk and then exception occurs if (response != null) { handler.exceptionCaught(response, new ChannelException("Channel disconnected")); } channel.close(); channelResourceContainer.returnResource(); if (!retVal.isDone()) { log.warn("[%s] Channel disconnected before response complete", requestDesc); retVal.setException(new ChannelException("Channel disconnected")); } context.sendUpstream(event); } private void removeHandlers() { if (readTimeout > 0) { channel.getPipeline().remove(READ_TIMEOUT_HANDLER_NAME); } channel.getPipeline().remove(LAST_HANDLER_NAME); } }); channel.write(httpRequest).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { channel.close(); channelResourceContainer.returnResource(); if (!retVal.isDone()) { retVal.setException(new ChannelException( String.format("[%s] Failed to write request to channel", requestDesc), future.getCause())); } } } }); return retVal; }