List of usage examples for com.google.common.util.concurrent SettableFuture create
public static <V> SettableFuture<V> create()
From source file:com.facebook.buck.remoteexecution.grpc.GrpcRemoteExecutionServiceClient.java
@Override public ListenableFuture<ExecutionResult> execute(Protocol.Digest actionDigest, String ruleName) throws IOException, InterruptedException { SettableFuture<Operation> future = SettableFuture.create(); StubAndResponseMetadata<ExecutionStub> stubAndMetadata = GrpcHeaderHandler .wrapStubToSendAndReceiveMetadata(executionStub, metadataProvider .getForAction(RemoteExecutionActionEvent.actionDigestToString(actionDigest), ruleName)); stubAndMetadata.getStub().execute(//from w w w. ja v a 2 s . co m ExecuteRequest.newBuilder().setInstanceName(instanceName) .setActionDigest(GrpcProtocol.get(actionDigest)).setSkipCacheLookup(false).build(), new StreamObserver<Operation>() { @Nullable Operation op = null; @Override public void onNext(Operation value) { op = value; } @Override public void onError(Throwable t) { String msg = String.format( "Failed execution request with metadata=[%s] and exception=[%s].", stubAndMetadata.getMetadata(), t.toString()); LOG.error(msg); future.setException(new IOException(msg, t)); } @Override public void onCompleted() { future.set(op); } }); return Futures.transform(future, operation -> { Objects.requireNonNull(operation); if (operation.hasError()) { throw new RuntimeException( String.format("Execution failed due to an infra error with Status=[%s] Metadata=[%s].", operation.getError().toString(), stubAndMetadata.getMetadata())); } if (!operation.hasResponse()) { throw new RuntimeException(String.format( "Invalid operation response: missing ExecutionResponse object. " + "Response=[%s] Metadata=[%s].", operation.toString(), stubAndMetadata.getMetadata())); } try { return getExecutionResult(operation.getResponse().unpack(ExecuteResponse.class).getResult(), stubAndMetadata.getMetadata()); } catch (InvalidProtocolBufferException e) { throw new BuckUncheckedExecutionException(e, "Exception getting execution result with Metadata=[%s].", stubAndMetadata.getMetadata()); } }, MoreExecutors.directExecutor()); }
From source file:com.twitter.heron.statemgr.NullStateManager.java
@Override public ListenableFuture<ExecutionEnvironment.ExecutionState> getExecutionState(WatchCallback watcher, String topologyName) { return SettableFuture.create(); }
From source file:com.spotify.apollo.test.experimental.AsyncRequester.java
public <T> ListenableFuture<Void> pump(final int rps, final int runtimeSeconds, final ResponseTimeMetric metric, final Callable<ListenableFuture<T>> request) { final AtomicInteger rate = new AtomicInteger(); final int hundredth = rps / 100; final Runnable command = new Runnable() { @Override/*from w ww. j a v a2s . c o m*/ public void run() { try { for (int i = 0; i < 100; i++) { if (metric.activeTracked.get() > 10000) { metric.totalRejected.incrementAndGet(); continue; } final long t0 = nanoTime(); final ListenableFuture<T> future = request.call(); metric.track(future, t0, rate.get()); } } catch (Exception e) { LOG.error("exception", e); } } }; class PhaseSwitcher implements Runnable { private final ScheduledFuture<?> prev; final int factor; PhaseSwitcher(ScheduledFuture<?> prev, int factor) { this.prev = prev; this.factor = factor; } PhaseSwitcher(int factor) { this(null, factor); } @Override public void run() { if (prev != null) { prev.cancel(false); } if (factor == 100) { LOG.info("running @ 100% = " + rps + " rps"); } else { LOG.info("running @ " + factor + "% = " + rps * factor / 100 + " rps"); } rate.set(factor * hundredth); final ScheduledFuture<?> phaseSchedule = executor.scheduleAtFixedRate(command, 0, 1000000 / (hundredth * factor / 100), TimeUnit.MICROSECONDS); if (factor < 100) { final int step = factor < 80 ? 10 : 5; executor.schedule(new PhaseSwitcher(phaseSchedule, factor + step), 20, TimeUnit.SECONDS); } } } executor.execute(new PhaseSwitcher(10)); final SettableFuture<Void> finish = SettableFuture.create(); executor.schedule(new Runnable() { @Override public void run() { finish.set(null); } }, runtimeSeconds, TimeUnit.SECONDS); return finish; }
From source file:org.wso2.andes.kernel.distruptor.inbound.InboundQueueEvent.java
/** * create an instance of andes queue//from ww w .j a va 2 s . c o m * * @param queueAsStr queue information as encoded string */ public InboundQueueEvent(String queueAsStr) { super(queueAsStr); purgedCount = SettableFuture.create(); isTopic = false; }
From source file:org.opendaylight.openflowjava.protocol.impl.core.UdpHandler.java
@Override public ListenableFuture<Boolean> shutdown() { final SettableFuture<Boolean> result = SettableFuture.create(); group.shutdownGracefully()/*from w w w . j a v a2 s . com*/ .addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() { @Override public void operationComplete(final io.netty.util.concurrent.Future<Object> downResult) throws Exception { result.set(downResult.isSuccess()); if (downResult.cause() != null) { result.setException(downResult.cause()); } } }); return result; }
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 {//from w ww. j av a 2 s .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; }
From source file:com.microsoft.office365.snippetapp.helpers.AuthenticationController.java
/** * Description: Calls AuthenticationContext.acquireToken(...) once to initialize with * user's credentials and avoid interactive prompt on later calls. * If all tokens expire, app must call initialize() again to prompt user interactively and * set up authentication context.//from w w w .j av a 2 s . c om * * @return A signal to wait on before continuing execution. */ public SettableFuture<AuthenticationResult> initialize() { final SettableFuture<AuthenticationResult> result = SettableFuture.create(); if (verifyAuthenticationContext()) { AuthenticationContext authContext = getAuthenticationContext(); if (authContext != null) authContext.acquireToken(this.contextActivity, this.resourceId, Constants.CLIENT_ID, Constants.REDIRECT_URI, PromptBehavior.Auto, new AuthenticationCallback<AuthenticationResult>() { @Override public void onSuccess(final AuthenticationResult authenticationResult) { if (authenticationResult != null && authenticationResult.getStatus() == AuthenticationStatus.Succeeded) { dependencyResolver = new ADALDependencyResolver(getAuthenticationContext(), resourceId, Constants.CLIENT_ID); O365ServicesManager.initialize(authenticationResult.getTenantId()); result.set(authenticationResult); } } @Override public void onError(Exception t) { result.setException(t); } }); else result.setException( new Throwable("Auth context verification failed. Did you set a context activity?")); } else { result.setException(new Throwable("Auth context verification failed. Did you set a context activity?")); } return result; }
From source file:co.cask.cdap.explore.jdbc.MockExploreClient.java
@Override public ListenableFuture<ExploreExecutionResult> columns(@Nullable String catalog, @Nullable String schemaPattern, String tableNamePattern, String columnNamePattern) { SettableFuture<ExploreExecutionResult> futureDelegate = SettableFuture.create(); futureDelegate.set(new MockExploreExecutionResult(statementsToResults.get("columns_stmt").iterator(), statementsToMetadata.get("columns_stmt"))); return new MockStatementExecutionFuture(futureDelegate, "columns_stmt", statementsToMetadata, statementsToResults);/*from w ww . j a va2s . c o m*/ }
From source file:com.yahoo.yqlplus.engine.internal.java.runtime.TimeoutHandler.java
public <T> ListenableFuture<T> withTimeout(final ListenableFuture<T> source, long timeout, TimeUnit timeoutUnits) {/*ww w. ja v a2 s . c om*/ if (timeout != 0) { final SettableFuture<T> result = SettableFuture.create(); final Future<?> scheduledFuture = timers .schedule(new TimeoutTask<T>(source, result, timeout, timeoutUnits), timeout, timeoutUnits); result.addListener(new Runnable() { @Override public void run() { scheduledFuture.cancel(false); if (result.isCancelled()) { source.cancel(true); } } }, MoreExecutors.sameThreadExecutor()); Futures.addCallback(source, new FutureCallback<T>() { @Override public void onSuccess(T out) { scheduledFuture.cancel(false); result.set(out); } @Override public void onFailure(Throwable t) { scheduledFuture.cancel(false); result.setException(t); } }); return scoper.scopeCallbacks(result); } else { return source; } }
From source file:co.cask.cdap.internal.app.deploy.InMemoryAdapterConfigurator.java
/** * Executes the <code>ApplicationTemplate.configureAdapter</code> within the same JVM. * <p>/*from w w w. j a v a2s .c o m*/ * This method could be dangerous and should be used only in standalone mode. * </p> * * @return A instance of {@link ListenableFuture}. */ 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()); 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 ApplicationTemplate)) { throw new IllegalStateException(String.format("Application main class is of invalid type: %s", appMain.getClass().getName())); } ApplicationTemplate template = (ApplicationTemplate) appMain; try (PluginInstantiator pluginInstantiator = new PluginInstantiator(cConf, adapterConfig.getTemplate(), template.getClass().getClassLoader())) { DefaultAdapterConfigurer configurer = new DefaultAdapterConfigurer(namespaceId, adapterName, adapterConfig, templateSpec, pluginRepository, pluginInstantiator); TypeToken typeToken = TypeToken.of(template.getClass()); TypeToken<?> resultToken = typeToken .resolveType(ApplicationTemplate.class.getTypeParameters()[0]); Type configType; // if the user parameterized their template, like 'xyz extends ApplicationTemplate<T>', // we can deserialize the config into that object. Otherwise it'll just be an Object if (resultToken.getType() instanceof Class) { configType = resultToken.getType(); } else { configType = Object.class; } template.configureAdapter(adapterName, decodeConfig(adapterConfig, configType), configurer); AdapterDefinition spec = configurer.createSpecification(); result.set(new DefaultConfigResponse(0, CharStreams.newReaderSupplier(GSON.toJson(spec)))); } } finally { removeDir(unpackedJarDir); } return result; } catch (Throwable t) { LOG.error(t.getMessage(), t); return Futures.immediateFailedFuture(t); } }