List of usage examples for com.google.common.util.concurrent SettableFuture create
public static <V> SettableFuture<V> create()
From source file:com.continuuity.loom.common.zookeeper.lib.ZKMap.java
public ListenableFuture<T> getOrWait(String key) { if (currentView.get().containsKey(key)) { return Futures.immediateFuture(currentView.get().get(key)); }// w ww. j a v a2 s . c om SettableFuture<T> future = SettableFuture.create(); waitingForElements.put(key, future); return future; }
From source file:org.wso2.andes.kernel.distruptor.inbound.InboundQueueEvent.java
/** * create an instance of andes queue//from ww w.jav a 2 s . c om * * @param queueName name of the queue * @param queueOwner owner of the queue (virtual host) * @param isExclusive is queue exclusive * @param isDurable is queue durable */ public InboundQueueEvent(String queueName, String queueOwner, boolean isExclusive, boolean isDurable) { super(queueName, queueOwner, isExclusive, isDurable); purgedCount = SettableFuture.create(); isQueueDeletable = SettableFuture.create(); isTopic = false; }
From source file:org.apache.beam.runners.fnexecution.data.GrpcDataService.java
private GrpcDataService(ExecutorService executor, OutboundObserverFactory outboundObserverFactory) { this.connectedClient = SettableFuture.create(); this.additionalMultiplexers = new LinkedBlockingQueue<>(); this.executor = executor; this.outboundObserverFactory = outboundObserverFactory; }
From source file:org.pentaho.di.ui.trans.step.StepDialogTestBase.java
public void createTest(final String shellTitle, BaseStepDialog dialog, final String endButton, final Callable<Void> testMethod) { swtBarrier.reset();//w w w . j av a 2s . c o m testResultFuture = SettableFuture.create(); // We assume the textFileInputDialog parameter implements StepDialogInterface, that is the only pattern that works in PDI. this.dialog = dialog; if (uiThread == null) { uiThread = new Thread(new Runnable() { public void run() { TestResults testResults = new TestResults(true, ""); try { // wait for the test setup swtBarrier.await(); while ((shell = getShell(StepDialogTestBase.this.dialog)) == null) { Thread.sleep(100); } bot = new SWTBot(shell); bot.shell(shellTitle).activate(); if (testMethod != null) { testMethod.call(); } } catch (InterruptedException e) { testResultFuture.setException(e); fail("Interrupted during testing"); e.printStackTrace(); } catch (BrokenBarrierException e) { testResultFuture.setException(e); fail("Broken barrier during testing"); e.printStackTrace(); } catch (Exception e) { testResultFuture.setException(e); } catch (AssertionError assertionError) { testResults.setTestPassed(false); testResults.setTestMessage(assertionError.getMessage()); } finally { testResultFuture.set(testResults); String buttonText = mappedButtonNames.get(endButton); if (buttonText == null) { buttonText = endButton; } SWTBotButton button = bot.button(buttonText); button.click(); } } }); uiThread.setDaemon(true); uiThread.start(); } }
From source file:io.viewserver.network.Network.java
public ListenableFuture<IPeerSession> connect(final IEndpoint endpoint) { SettableFuture<IPeerSession> future = SettableFuture.create(); log.debug("Connecting to {}", endpoint); final int connectionId = getNextConnectionId(); ITask connectTask = new ITask() { @Override/*from w w w .j a v a2 s .co m*/ public void execute() { ITask thisTask = this; ListenableFuture<IChannel> channelFuture = networkAdapter.connect(endpoint); reactor.addCallback(channelFuture, new FutureCallback<IChannel>() { @Override public void onSuccess(IChannel channel) { ClientToServerSession peerSession = new ClientToServerSession(channel, executionContext, catalog, Network.this, connectionId, networkAdapter.createMessageManager(channel)); peerSession.addDisconnectionHandler(Network.this); connectionIds.put(channel, connectionId); sessionManager.addSession(peerSession); heartbeatTask.sessions.add(peerSession); heartbeatTask.lastResponses.put(peerSession, System.currentTimeMillis()); log.debug("Connection {} initialised on channel {}", connectionId, channel); future.set(peerSession); } @Override public void onFailure(Throwable t) { log.error(String.format("Failed to connect to %s", endpoint), t); reactor.scheduleTask(thisTask, 1000, -1); } }); } }; reactor.scheduleTask(connectTask, 0, -1); log.debug("Scheduled task to connect to server"); return future; }
From source file:org.apache.qpid.server.virtualhostnode.RedirectingVirtualHostNodeImpl.java
@StateTransition(currentState = { State.UNINITIALIZED, State.STOPPED, State.ERRORED }, desiredState = State.ACTIVE) private ListenableFuture<Void> doActivate() { final SettableFuture<Void> resultFuture = SettableFuture.create(); Map<String, Object> attributes = new HashMap<>(); attributes.put(ConfiguredObject.NAME, getName()); attributes.put(ConfiguredObject.TYPE, RedirectingVirtualHostImpl.VIRTUAL_HOST_TYPE); final ListenableFuture<VirtualHost> virtualHostFuture = getObjectFactory().createAsync(VirtualHost.class, attributes, this); addFutureCallback(virtualHostFuture, new FutureCallback<VirtualHost>() { @Override/*from w w w .ja v a2 s .co m*/ public void onSuccess(final VirtualHost virtualHost) { _virtualHost = (RedirectingVirtualHostImpl) virtualHost; setState(State.ACTIVE); resultFuture.set(null); } @Override public void onFailure(final Throwable t) { setState(State.ERRORED); if (((Broker) getParent()).isManagementMode()) { LOGGER.warn("Failed to make {} active.", this, t); resultFuture.set(null); } else { resultFuture.setException(t); } } }, getTaskExecutor()); return resultFuture; }
From source file:com.facebook.buck.distributed.ServerContentsProvider.java
public ServerContentsProvider(DistBuildService service, ScheduledExecutorService networkScheduler, ListeningExecutorService networkThreadPool, FileMaterializationStatsTracker statsTracker, long multiFetchBufferPeriodMs, int multiFetchBufferMaxSize) { this.service = service; this.multiFetchBufferMaxSize = multiFetchBufferMaxSize; this.statsTracker = statsTracker; this.networkThreadPool = networkThreadPool; synchronized (multiFetchLock) { hashCodesToFetch = new HashSet<>(); multiFetchFuture = SettableFuture.create(); }// w ww. jav a 2 s.com scheduledBufferProcessor = networkScheduler.scheduleAtFixedRate(this::makePeriodicMultiFetchRequest, 0, multiFetchBufferPeriodMs, TimeUnit.MILLISECONDS); }
From source file:com.microsoft.office365.profile.util.AuthenticationManager.java
/** * Calls AuthenticationContext.acquireToken once to get tokens. User must provide credentials * the first time. Subsequent calls retrieve tokens from the local cache or use the refresh * token to get a valid access token.// ww w. j a va 2s. com * If all tokens expire, then the next call to getTokens will prompt for user credentials. * By default, you would use this in an asynchronous mode, but you can also call getTokens in * synchronously by appending get() to getTokens. For example, getTokens(null).get() which * will return an AuthenticationResult object. * @param authenticationCallback The callback to which delegate the execution flow. * @return A signal to wait on before continuing execution that contains an AuthenticationResult * object with information about the user, and the tokens. */ public synchronized SettableFuture<AuthenticationResult> getTokens( final AuthenticationCallback authenticationCallback) { final SettableFuture<AuthenticationResult> result = SettableFuture.create(); if (verifyAuthenticationContext()) { getAuthenticationContext().acquireToken(this.mContextActivity, this.mResourceId, Constants.CLIENT_ID, Constants.REDIRECT_URI, PromptBehavior.Auto, new AuthenticationCallback<AuthenticationResult>() { @Override public void onSuccess(final AuthenticationResult authenticationResult) { if (authenticationResult != null) { if (authenticationCallback != null) { if (authenticationResult.getStatus() == AuthenticationStatus.Succeeded) { authenticationCallback.onSuccess(authenticationResult); } else { // Unknown error. Errors, like when the user cancels the // operation usually go through the onError method authenticationCallback.onError(new AuthenticationException( ADALError.AUTH_FAILED, "Authentication failed")); } } result.set(authenticationResult); } else { result.setException(new AuthenticationException(ADALError.AUTH_FAILED, "Authentication failed")); } } @Override public void onError(Exception e) { if (authenticationCallback != null) { authenticationCallback.onError(e); } result.setException(e); } }); } else { result.setException(new Throwable( "Auth context verification failed. " + "Use setContextActivity(Activity) before getTokens()")); } return result; }
From source file:io.soliton.protobuf.json.JsonRpcRequestInvoker.java
/** * Actually invokes the server method./*from w ww. j av a 2 s.co m*/ * * @param method the method to invoke * @param parameter the request's parameter * @param id the request's client-side identifier * @param <I> the method's input proto-type * @param <O> the method's output proto-type */ private <I extends Message, O extends Message> ListenableFuture<JsonRpcResponse> invoke( ServerMethod<I, O> method, JsonObject parameter, JsonElement id) { I request; try { request = (I) Messages.fromJson(method.inputBuilder(), parameter); } catch (Exception e) { serverLogger.logServerFailure(method, e); SettableFuture<JsonRpcResponse> future = SettableFuture.create(); future.setException(e); return future; } ListenableFuture<O> response = method.invoke(request); return Futures.transform(response, new JsonConverter(id), TRANSFORM_EXECUTOR); }
From source file:org.opendaylight.netconf.topology.singleton.impl.ProxyDOMRpcService.java
@Nonnull @Override/*from w w w .j a v a2 s .c o m*/ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) { LOG.trace("{}: Rpc operation invoked with schema type: {} and node: {}.", id, type, input); final NormalizedNodeMessage normalizedNodeMessage = new NormalizedNodeMessage(YangInstanceIdentifier.EMPTY, input); final Future<Object> scalaFuture = Patterns.ask(masterActorRef, new InvokeRpcMessage(new SchemaPathMessage(type), normalizedNodeMessage), actorResponseWaitTime); final SettableFuture<DOMRpcResult> settableFuture = SettableFuture.create(); final CheckedFuture<DOMRpcResult, DOMRpcException> checkedFuture = Futures.makeChecked(settableFuture, new Function<Exception, DOMRpcException>() { @Nullable @Override public DOMRpcException apply(@Nullable final Exception exception) { return new ClusteringRpcException(id + ": Exception during remote rpc invocation.", exception); } }); scalaFuture.onComplete(new OnComplete<Object>() { @Override public void onComplete(final Throwable failure, final Object success) throws Throwable { if (failure != null) { settableFuture.setException(failure); return; } if (success instanceof Throwable) { settableFuture.setException((Throwable) success); return; } if (success instanceof EmptyResultResponse || success == null) { settableFuture.set(null); return; } final Collection<RpcError> errors = ((InvokeRpcMessageReply) success).getRpcErrors(); final NormalizedNodeMessage normalizedNodeMessageResult = ((InvokeRpcMessageReply) success) .getNormalizedNodeMessage(); final DOMRpcResult result; if (normalizedNodeMessageResult == null) { result = new DefaultDOMRpcResult(errors); } else { if (errors == null) { result = new DefaultDOMRpcResult(normalizedNodeMessageResult.getNode()); } else { result = new DefaultDOMRpcResult(normalizedNodeMessageResult.getNode(), errors); } } settableFuture.set(result); } }, actorSystem.dispatcher()); return checkedFuture; }