List of usage examples for com.google.common.util.concurrent SettableFuture set
@Override public boolean set(@Nullable V value)
From source file:com.facebook.buck.distributed.ServerContentsProvider.java
/** Blocking call */ private int processFileBuffer(boolean onlyIfBufferIsFull) { Set<String> hashCodes; SettableFuture<Map<String, byte[]>> resultFuture; synchronized (multiFetchLock) { if (onlyIfBufferIsFull && hashCodesToFetch.size() < multiFetchBufferMaxSize) { return 0; }//from ww w .ja v a 2s.co m if (hashCodesToFetch.isEmpty()) { return 0; } hashCodes = hashCodesToFetch; hashCodesToFetch = new HashSet<>(); resultFuture = multiFetchFuture; multiFetchFuture = SettableFuture.create(); } try { LOG.info("Fetching [%d] source files from the CAS (%s).", hashCodes.size(), onlyIfBufferIsFull ? "buffer was full" : "scheduled"); resultFuture.set(service.multiFetchSourceFiles(hashCodes)); } catch (IOException e) { LOG.error(e); resultFuture.setException(e); return 0; } return hashCodes.size(); }
From source file:com.twitter.heron.statemgr.zookeeper.curator.CuratorStateManager.java
protected <M extends Message> ListenableFuture<M> getNodeData(WatchCallback watcher, String path, final Message.Builder builder) { final SettableFuture<M> future = SettableFuture.create(); Watcher wc = ZkWatcherCallback.makeZkWatcher(watcher); BackgroundCallback cb = new BackgroundCallback() { @Override/*from w w w .ja v a2s . c o m*/ @SuppressWarnings("unchecked") // we don't know what M is until runtime public void processResult(CuratorFramework aClient, CuratorEvent event) throws Exception { byte[] data; if (event != null & (data = event.getData()) != null) { builder.mergeFrom(data); future.set((M) builder.build()); } else { future.setException(new RuntimeException("Failed to fetch data from path: " + event.getPath())); } } }; try { client.getData().usingWatcher(wc).inBackground(cb).forPath(path); // Suppress it since forPath() throws Exception // SUPPRESS CHECKSTYLE IllegalCatch } catch (Exception e) { future.setException(new RuntimeException("Could not getData", e)); } return future; }
From source file:org.opendaylight.controller.cluster.datastore.admin.ClusterAdminRpcService.java
@Override public Future<RpcResult<Void>> changeMemberVotingStatesForShard(ChangeMemberVotingStatesForShardInput input) { final String shardName = input.getShardName(); if (Strings.isNullOrEmpty(shardName)) { return newFailedRpcResultFuture("A valid shard name must be specified"); }//w w w. j a v a 2 s . c o m DataStoreType dataStoreType = input.getDataStoreType(); if (dataStoreType == null) { return newFailedRpcResultFuture("A valid DataStoreType must be specified"); } List<MemberVotingState> memberVotingStates = input.getMemberVotingState(); if (memberVotingStates == null || memberVotingStates.isEmpty()) { return newFailedRpcResultFuture("No member voting state input was specified"); } ChangeShardMembersVotingStatus changeVotingStatus = toChangeShardMembersVotingStatus(shardName, memberVotingStates); LOG.info("Change member voting states for shard {}: {}", shardName, changeVotingStatus.getMeberVotingStatusMap()); final SettableFuture<RpcResult<Void>> returnFuture = SettableFuture.create(); ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType, changeVotingStatus); Futures.addCallback(future, new FutureCallback<Success>() { @Override public void onSuccess(Success success) { LOG.info("Successfully changed member voting states for shard {}", shardName); returnFuture.set(newSuccessfulResult()); } @Override public void onFailure(Throwable failure) { onMessageFailure(String.format("Failed to change member voting states for shard %s", shardName), returnFuture, failure); } }); return returnFuture; }
From source file:de.uniluebeck.itm.coapserver.NotObservableOverviewWebservice.java
private void processGet(SettableFuture<CoapResponse> responseFuture, CoapRequest request) throws InvalidHeaderException { Set<Long> acceptOptions = request.getAcceptedContentFormats(); try {/*from www.ja v a 2 s . c om*/ //If accept option is not set in the request, use the default (TEXT_PLAIN) if (acceptOptions.isEmpty()) { Log.d(TAG, "accept optioon is empty"); CoapResponse response = new CoapResponse(request.getMessageTypeName(), MessageCode.Name.CONTENT_205); response.setContent(createPayloadFromAcutualStatus(ContentFormat.TEXT_PLAIN_UTF8), ContentFormat.TEXT_PLAIN_UTF8); responseFuture.set(response); } for (long option : acceptOptions) { long acceptedMediaType = option; Log.d(TAG, "Try to create payload for accepted mediatype " + acceptedMediaType); byte[] payload = createPayloadFromAcutualStatus(acceptedMediaType); //the requested mediatype is supported if (payload != null) { CoapResponse response = new CoapResponse(request.getMessageTypeName(), MessageCode.Name.CONTENT_205); response.setContent(payload, acceptedMediaType); responseFuture.set(response); } } } catch (Exception e) { Log.d(TAG, "Exception at process get "); } //This is only reached if all accepted mediatypes are not supported! CoapResponse response = new CoapResponse(request.getMessageTypeName(), MessageCode.Name.UNSUPPORTED_CONTENT_FORMAT_415); responseFuture.set(response); }
From source file:com.android.tools.idea.avdmanager.AvdManagerConnection.java
/** * Handle the {@link AccelerationErrorCode} found when attempting to start an AVD. * @param project//from www.ja va2s .co m * @param error * @return a future with a device that was launched delayed, or null if startAvd should proceed to start the AVD. */ @Nullable private ListenableFuture<IDevice> handleAccelerationError(@Nullable final Project project, @NotNull final AvdInfo info, @NotNull AccelerationErrorCode error) { switch (error) { case ALREADY_INSTALLED: return null; case TOOLS_UPDATE_REQUIRED: case PLATFORM_TOOLS_UPDATE_ADVISED: case SYSTEM_IMAGE_UPDATE_ADVISED: // Do not block emulator from running if we need updates (run with degradated performance): return null; case NO_EMULATOR_INSTALLED: // report this error below break; default: Abi abi = Abi.getEnum(info.getAbiType()); boolean isAvdIntel = abi == Abi.X86 || abi == Abi.X86_64; if (!isAvdIntel) { // Do not block Arm and Mips emulators from running without an accelerator: return null; } // report all other errors break; } String accelerator = SystemInfo.isLinux ? "KVM" : "Intel HAXM"; int result = Messages.showOkCancelDialog(project, String.format("%1$s is required to run this AVD.\n%2$s\n\n%3$s\n", accelerator, error.getProblem(), error.getSolutionMessage()), error.getSolution().getDescription(), AllIcons.General.WarningDialog); if (result != Messages.OK || error.getSolution() == AccelerationErrorSolution.SolutionCode.NONE) { return Futures.immediateFailedFuture(new RuntimeException("Could not start AVD")); } final SettableFuture<ListenableFuture<IDevice>> future = SettableFuture.create(); Runnable retry = () -> future.set(startAvd(project, info)); Runnable cancel = () -> future.setException(new RuntimeException("Retry after fixing problem by hand")); Runnable action = AccelerationErrorSolution.getActionForFix(error, project, retry, cancel); ApplicationManager.getApplication().invokeLater(action); return Futures.dereference(future); }
From source file:com.continuuity.weave.internal.ZKWeaveController.java
@Override public ListenableFuture<State> stop() { final SettableFuture<State> result = SettableFuture.create(); final ListenableFuture<State> future = super.stop(); future.addListener(new Runnable() { @Override// w w w.ja v a 2 s .co m public void run() { logPoller.interrupt(); try { logPoller.join(); } catch (InterruptedException e) { LOG.warn("Joining of log poller thread interrupted.", e); } Futures.addCallback(kafkaClient.stop(), new FutureCallback<Service.State>() { @Override public void onSuccess(Service.State state) { try { future.get(); result.set(State.TERMINATED); } catch (Exception e) { LOG.error("Failed when stopping local services", e); result.setException(e); } } @Override public void onFailure(Throwable t) { result.setException(t); } }); } }, Threads.SAME_THREAD_EXECUTOR); return result; }
From source file:org.opendaylight.vpnservice.itm.rpc.ItmManagerRpcService.java
@Override public Future<RpcResult<Void>> addExternalTunnelEndpoint(AddExternalTunnelEndpointInput input) { // TODO Auto-generated method stub //Ignore the Futures for now final SettableFuture<RpcResult<Void>> result = SettableFuture.create(); List<DPNTEPsInfo> meshedDpnList = ItmUtils.getTunnelMeshInfo(dataBroker); ItmExternalTunnelAddWorker.buildTunnelsToExternalEndPoint(dataBroker, idManagerService, meshedDpnList, input.getDestinationIp(), input.getTunnelType()); result.set(RpcResultBuilder.<Void>success().build()); return result; }
From source file:org.opendaylight.vpnservice.itm.rpc.ItmManagerRpcService.java
@Override public Future<RpcResult<Void>> removeExternalTunnelFromDpns(RemoveExternalTunnelFromDpnsInput input) { //Ignore the Futures for now final SettableFuture<RpcResult<Void>> result = SettableFuture.create(); List<DPNTEPsInfo> cfgDpnList = ItmUtils.getDPNTEPListFromDPNId(dataBroker, input.getDpnId()); ItmExternalTunnelDeleteWorker.deleteTunnels(dataBroker, idManagerService, cfgDpnList, input.getDestinationIp(), input.getTunnelType()); result.set(RpcResultBuilder.<Void>success().build()); return result; }
From source file:io.crate.operation.qtf.QueryThenFetchOperation.java
public ListenableFuture<QueryThenFetchContext> execute(QueryThenFetchNode searchNode, List<Reference> outputs, Optional<PageInfo> pageInfo) { SettableFuture<QueryThenFetchContext> future = SettableFuture.create(); // do stuff//from www . j a v a2 s . c o m QueryThenFetchContext ctx = new QueryThenFetchContext(bigArrays, searchNode, outputs, pageInfo); prepareRequests(ctx); if (!searchNode.routing().hasLocations() || ctx.requests.size() == 0) { future.set(ctx); } ClusterState state = clusterService.state(); state.blocks().globalBlockedRaiseException(ClusterBlockLevel.READ); AtomicInteger totalOps = new AtomicInteger(0); int requestIdx = -1; for (Tuple<String, QueryShardRequest> requestTuple : ctx.requests) { requestIdx++; state.blocks().indexBlockedRaiseException(ClusterBlockLevel.READ, requestTuple.v2().index()); transportQueryShardAction.executeQuery(requestTuple.v1(), requestTuple.v2(), new QueryShardResponseListener(requestIdx, totalOps, ctx, future)); } return future; }