List of usage examples for com.google.common.util.concurrent SettableFuture create
public static <V> SettableFuture<V> create()
From source file:com.vmware.photon.controller.common.zookeeper.AbstractServiceNode.java
/** * Joins a cluster defined by child nodes of a Zookeeper znode. Returns a promise that gets fulfilled * when this node has finished joining the cluster. The promise returns a Lease object that client code * can use to get expiration promise (the one that gets fulfilled when this particular membership gets * recalled b/c of ZK connection loss).// w w w.j a v a 2 s.c o m */ @Override public synchronized ListenableFuture<Lease> join() { logger.debug("Attempting to join cluster: {}", this); if (state == State.JOINED) { return Futures.immediateFailedFuture(new IllegalStateException("Node has already joined")); } final SettableFuture<Lease> leasePromise = SettableFuture.create(); try { Futures.addCallback(joinCondition(), new FutureCallback<Void>() { @Override public void onSuccess(Void result) { state = State.JOINED; handleSuccessfulJoinCondition(leasePromise); } @Override public void onFailure(Throwable t) { leasePromise.setException(t); } }); } catch (Exception e) { leasePromise.setException(e); } return leasePromise; }
From source file:org.opendaylight.netconf.topology.singleton.impl.tx.NetconfReadOnlyTransaction.java
@Override public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) { LOG.trace("{}: Exists {} via NETCONF: {}", id, store, path); final Future<Boolean> existsFuture = delegate.exists(store, path); final SettableFuture<Boolean> settableFuture = SettableFuture.create(); final CheckedFuture<Boolean, ReadFailedException> checkedFuture; checkedFuture = Futures.makeChecked(settableFuture, new Function<Exception, ReadFailedException>() { @Nullable//from www . j av a 2s . c o m @Override public ReadFailedException apply(Exception cause) { return new ReadFailedException("Read from transaction failed", cause); } }); existsFuture.onComplete(new OnComplete<Boolean>() { @Override public void onComplete(final Throwable throwable, final Boolean result) throws Throwable { if (throwable == null) { settableFuture.set(result); } else { settableFuture.setException(throwable); } } }, actorSystem.dispatcher()); return checkedFuture; }
From source file:edu.umich.si.inteco.minuku.dao.MoodDataRecordDAO.java
@Override public Future<List<MoodDataRecord>> getLast(final int N) throws DAOException { final SettableFuture<List<MoodDataRecord>> settableFuture = SettableFuture.create(); final Date today = new Date(); final List<MoodDataRecord> lastNRecords = new ArrayList<MoodDataRecord>(); getLastNValues(N, myUserEmail, today, lastNRecords, settableFuture); return settableFuture; }
From source file:org.thingsboard.server.dao.nosql.CassandraBufferedRateExecutor.java
@Override protected SettableFuture<ResultSet> create() { return SettableFuture.create(); }
From source file:com.microsoft.sharepointservices.DocLibClient.java
/** * Get a FileSystemItem from a path in a document library * /*from ww w . ja va 2s . c o m*/ * @param library * the document library * @param path * the path * @return OfficeFuture<List<FileSystemItem>> */ public ListenableFuture<FileSystemItem> getFileSystemItem(String path, final String library) { final SettableFuture<FileSystemItem> files = SettableFuture.create(); String getFilesUrl; if (library != null) { getFilesUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/files(%s)"; getFilesUrl = String.format(getFilesUrl, urlEncode(library), getUrlPath(path)); } else { getFilesUrl = getSiteUrl() + String.format("_api/files(%s)", getUrlPath(path)); } try { ListenableFuture<JSONObject> request = executeRequestJson(getFilesUrl, "GET"); Futures.addCallback(request, new FutureCallback<JSONObject>() { @Override public void onFailure(Throwable t) { files.setException(t); } @Override public void onSuccess(JSONObject json) { try { FileSystemItem item = new FileSystemItem(); item.loadFromJson(json); files.set(item); } catch (Throwable e) { files.setException(e); } } }); } catch (Throwable t) { files.setException(t); } return files; }
From source file:org.opendaylight.distributed.tx.impl.DTXTestTransaction.java
@Override public <T extends DataObject> CheckedFuture<Optional<T>, ReadFailedException> read( LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<T> instanceIdentifier) { T obj = null;//w w w . ja va2 s . com if (txDataMap.get(instanceIdentifier).size() > 0) obj = (T) txDataMap.get(instanceIdentifier).getFirst(); final Optional<T> retOpt = Optional.fromNullable(obj); final SettableFuture<Optional<T>> retFuture = SettableFuture.create(); Runnable readResult = new Runnable() { @Override public void run() { try { Thread.sleep(delayTime); } catch (InterruptedException e) { e.printStackTrace(); } boolean readException = getAndResetExceptionWithInstanceIdentifier(readExceptionMap, instanceIdentifier); if (readException == false) { retFuture.set(retOpt); } else { retFuture.setException(new Throwable("Read error")); } retFuture.notifyAll(); } }; new Thread(readResult).start(); Function<Exception, ReadFailedException> f = new Function<Exception, ReadFailedException>() { @Nullable @Override public ReadFailedException apply(@Nullable Exception e) { return new ReadFailedException("Read failed", e); } }; return Futures.makeChecked(retFuture, f); }
From source file:co.cask.cdap.common.resource.ResourceBalancerService.java
/** * Creates instance of {@link ResourceBalancerService}. * @param serviceName name of the service * @param partitionCount number of partitions of the resource to balance * @param zkClient ZooKeeper place to keep metadata for sync; will be further namespaced with service name * @param discoveryService discovery service to register this service * @param discoveryServiceClient discovery service client to discover other instances of this service *///from w w w .j av a 2 s . c o m protected ResourceBalancerService(String serviceName, int partitionCount, ZKClientService zkClient, DiscoveryService discoveryService, final DiscoveryServiceClient discoveryServiceClient) { this.serviceName = serviceName; this.partitionCount = partitionCount; this.discoveryService = discoveryService; final ZKClient zk = ZKClients.namespace(zkClient, "/" + serviceName); this.election = new LeaderElection(zk, serviceName, new ElectionHandler() { private ResourceCoordinator coordinator; @Override public void leader() { coordinator = new ResourceCoordinator(zk, discoveryServiceClient, new BalancedAssignmentStrategy()); coordinator.startAndWait(); } @Override public void follower() { if (coordinator != null) { coordinator.stopAndWait(); coordinator = null; } } }); this.resourceClient = new ResourceCoordinatorClient(zk); this.completion = SettableFuture.create(); }
From source file:com.twitter.heron.statemgr.localfs.LocalFileSystemStateManager.java
@SuppressWarnings("unchecked") // we don't know what M is until runtime protected <M extends Message> ListenableFuture<M> getData(String path, Message.Builder builder) { final SettableFuture<M> future = SettableFuture.create(); byte[] data = FileUtils.readFromFile(path); if (data.length == 0) { future.set(null);//from ww w. j a v a 2s . c om return future; } try { builder.mergeFrom(data); future.set((M) builder.build()); } catch (InvalidProtocolBufferException e) { future.setException(new RuntimeException("Could not parse " + Message.Builder.class, e)); } return future; }
From source file:com.facebook.presto.operator.exchange.LocalExchangeSource.java
public ListenableFuture<?> waitForReading() { checkNotHoldsLock();//from w ww . j a va 2 s . com synchronized (lock) { // if we need to block readers, and the current future is complete, create a new one if (!finishing && buffer.isEmpty() && notEmptyFuture.isDone()) { notEmptyFuture = SettableFuture.create(); } return notEmptyFuture; } }
From source file:org.whispersystems.gcm.server.Sender.java
/** * Asynchronously send a message with a context to be passed in the future result. * * @param message The message to send.//from ww w .j a v a 2s . co m * @param requestContext An opaque context to include the future result. * @return The future. */ public ListenableFuture<Result> send(final Message message, final Object requestContext) { return executor.getFutureWithRetry(new RetryCallable<ListenableFuture<Result>>() { @Override public ListenableFuture<Result> call(RetryContext context) throws Exception { SettableFuture<Result> future = SettableFuture.create(); HttpPost request = new HttpPost(url); request.setHeader("Authorization", authorizationHeader); request.setEntity(new StringEntity(message.serialize(), ContentType.parse("application/json"))); client.execute(request, new ResponseHandler(future, requestContext)); return future; } }); }