List of usage examples for com.google.common.util.concurrent SettableFuture setException
@Override public boolean setException(Throwable throwable)
From source file:ohmdb.flease.FleaseLease.java
private void checkReadReplies(List<IncomingRpcReply> replies, SettableFuture<LeaseValue> future) { try {/*from w w w. j a v a2 s . com*/ // every reply should be a ackREAD. BallotNumber largest = null; LeaseValue v = null; for (IncomingRpcReply reply : replies) { // if kPrime > largest BallotNumber kPrime = reply.getKPrime(); if (kPrime.compareTo(largest) > 0) { largest = kPrime; v = reply.getLease(); } } if (!future.set(v)) { LOG.warn("{} checkReadReplies, unable to set future for {}", getId(), v); } } catch (Throwable e) { if (!future.setException(e)) { LOG.warn("{} checkReadReplies, unable to set exception future, {}", (Object) e); } } }
From source file:org.opendaylight.openflowplugin.impl.services.RoleService.java
public Future<BigInteger> getGenerationIdFromDevice(Short version) throws RoleChangeException { final NodeId nodeId = deviceContext.getPrimaryConnectionContext().getNodeId(); LOG.info("getGenerationIdFromDevice called for device:{}", nodeId.getValue()); // send a dummy no-change role request to get the generation-id of the switch final RoleRequestInputBuilder roleRequestInputBuilder = new RoleRequestInputBuilder(); roleRequestInputBuilder.setRole(toOFJavaRole(OfpRole.NOCHANGE)); roleRequestInputBuilder.setVersion(version); roleRequestInputBuilder.setGenerationId(BigInteger.ZERO); final SettableFuture<BigInteger> finalFuture = SettableFuture.create(); ListenableFuture<RpcResult<RoleRequestOutput>> genIdListenableFuture = handleServiceCall( roleRequestInputBuilder);/*from w w w . j a v a 2s .c o m*/ Futures.addCallback(genIdListenableFuture, new FutureCallback<RpcResult<RoleRequestOutput>>() { @Override public void onSuccess(RpcResult<RoleRequestOutput> roleRequestOutputRpcResult) { if (roleRequestOutputRpcResult.isSuccessful()) { RoleRequestOutput roleRequestOutput = roleRequestOutputRpcResult.getResult(); if (roleRequestOutput != null) { LOG.debug("roleRequestOutput.getGenerationId()={}", roleRequestOutput.getGenerationId()); finalFuture.set(roleRequestOutput.getGenerationId()); } else { LOG.info("roleRequestOutput is null in getGenerationIdFromDevice"); finalFuture.setException(new RoleChangeException( "Exception in getting generationId for device:" + nodeId.getValue())); } } else { LOG.error("getGenerationIdFromDevice RPC error " + roleRequestOutputRpcResult.getErrors().iterator().next().getInfo()); } } @Override public void onFailure(Throwable throwable) { LOG.info("onFailure - getGenerationIdFromDevice RPC error {}", throwable); finalFuture.setException(new ExecutionException(throwable)); } }); return finalFuture; }
From source file:org.dcm4che3.conf.core.adapters.ReflectiveAdapter.java
@Override public T fromConfigNode(Map<String, Object> configNode, ConfigProperty property, LoadingContext ctx, Object parent) throws ConfigurationException { if (configNode == null) return null; Class<T> clazz = (Class<T>) property.getType(); if (!Map.class.isAssignableFrom(configNode.getClass())) throw new ConfigurationException( "Provided configuration node is not a map (type " + clazz.getName() + ")"); // figure out UUID String uuid;/* w w w . j av a 2 s . c o m*/ try { uuid = (String) configNode.get(Configuration.UUID_KEY); } catch (RuntimeException e) { throw new ConfigurationException("UUID is malformed: " + configNode.get(Configuration.UUID_KEY)); } // if the object is provided - just populate and return if (providedConfObj != null) { populate(configNode, ctx, clazz, providedConfObj, parent, uuid); return providedConfObj; } // if uuid not present - simply create new instance if (uuid == null) { T confObj = ctx.getVitalizer().newInstance(clazz); populate(configNode, ctx, clazz, confObj, parent, uuid); return confObj; } //// uuid present - need to coordinate with the context // first check the context Referable existingReferable = ctx.getReferable(uuid); if (existingReferable != null) { // TODO: proper cast! return (T) existingReferable.getConfObject(); } SettableFuture<Object> confObjFuture = SettableFuture.create(); T confObj = ctx.getVitalizer().newInstance(clazz); Referable createdReferable = new Referable(confObjFuture, confObj); // cover non-atomicity above Referable suddenlyExistingReferable = ctx.registerReferableIfAbsent(uuid, createdReferable); if (suddenlyExistingReferable != null) { // TODO: proper cast! return (T) suddenlyExistingReferable.getConfObject(); } // now it's for sure me who is responsible for loading this object try { populate(configNode, ctx, clazz, confObj, parent, uuid); confObjFuture.set(confObj); return confObj; } catch (RuntimeException e) { confObjFuture.setException(e); throw e; } catch (Error e) { confObjFuture.setException(e); throw e; } }
From source file:org.waveprotocol.box.server.waveletstate.block.BlockWaveletStateImpl.java
@Override public ListenableFuture<Map<String, Block>> readBlocks(final Set<String> blockIds) throws WaveletStateException { checkOpened();/* ww w . j a va 2s. com*/ final Map<String, Block> blocks = new ConcurrentHashMap<>(); Set<String> missingBlockIds = CollectionUtils.newHashSet(); List<ListenableFuture<Block>> blockFutures = CollectionUtils.newLinkedList(); for (String blockId : blockIds) { Block block = blockCache.getBlock(blockId); if (block != null) { blocks.put(block.getBlockId(), block); } else { ListenableFuture<Block> blockFuture = readBlocksFutures.get(blockId); if (blockFuture != null) { blockFutures.add(blockFuture); } else { missingBlockIds.add(blockId); } } } if (!missingBlockIds.isEmpty()) { blockFutures.addAll(executeReadBlocksRequest(missingBlockIds)); } final SettableFuture<Map<String, Block>> future = SettableFuture.create(); if (!blockFutures.isEmpty()) { for (final ListenableFuture<Block> blockFuture : blockFutures) { blockFuture.addListener(new Runnable() { @Override public void run() { try { blocks.put(blockFuture.get().getBlockId(), blockFuture.get()); if (blocks.keySet().containsAll(blockIds)) { future.set(blocks); } } catch (InterruptedException | ExecutionException ex) { future.setException(ex); } } }, MoreExecutors.sameThreadExecutor()); } } else { future.set(blocks); } return future; }
From source file:com.microsoft.office365.connect.DiscoveryController.java
/** * Provides information about the service that corresponds to the provided * capability.//from www.j ava 2s .c om * @param capability A string that contains the capability of the service that * is going to be discovered. * @return A signal to wait on before continuing execution. The signal contains the * ServiceInfo object with extra information about discovered service. */ public SettableFuture<ServiceInfo> getServiceInfo(final String capability) { final SettableFuture<ServiceInfo> result = SettableFuture.create(); // First, look in the locally cached services. if (mServices != null) { boolean serviceFound = false; for (ServiceInfo service : mServices) { if (service.getcapability().equals(capability)) { Log.i(TAG, "getServiceInfo - " + service.getserviceName() + " service for " + capability + " was found in local cached services"); result.set(service); serviceFound = true; break; } } if (!serviceFound) { NoSuchElementException noSuchElementException = new NoSuchElementException( "The " + capability + " capability was not found in the local cached services."); Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage()); result.setException(noSuchElementException); } } else { // The services have not been cached yet. Go ask the discovery service. AuthenticationManager.getInstance().setResourceId(Constants.DISCOVERY_RESOURCE_ID); ADALDependencyResolver dependencyResolver = (ADALDependencyResolver) AuthenticationManager.getInstance() .getDependencyResolver(); DiscoveryClient discoveryClient = new DiscoveryClient(Constants.DISCOVERY_RESOURCE_URL, dependencyResolver); try { ListenableFuture<List<ServiceInfo>> future = discoveryClient.getservices().read(); Futures.addCallback(future, new FutureCallback<List<ServiceInfo>>() { @Override public void onSuccess(final List<ServiceInfo> services) { Log.i(TAG, "getServiceInfo - Services discovered\n"); // Save the discovered services to serve further requests from the local cache. mServices = services; boolean serviceFound = false; for (ServiceInfo service : services) { if (service.getcapability().equals(capability)) { Log.i(TAG, "getServiceInfo - " + service.getserviceName() + " service for " + capability + " was found in services retrieved from discovery"); result.set(service); serviceFound = true; break; } } if (!serviceFound) { NoSuchElementException noSuchElementException = new NoSuchElementException( "The " + capability + " capability was not found in the user services."); Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage()); result.setException(noSuchElementException); } } @Override public void onFailure(Throwable t) { Log.e(TAG, "getServiceInfo - " + t.getMessage()); result.setException(t); } }); } catch (Exception e) { Log.e(TAG, "getServiceInfo - " + e.getMessage()); result.setException(e); } } return result; }
From source file:com.microsoft.office365.snippetapp.helpers.DiscoveryController.java
/** * Provides information about the service that corresponds to the provided * capability.// w w w . j a v a 2s .c o m * * @param capability A string that contains the capability of the service that * is going to be discovered. * @return A signal to wait on before continuing execution. The signal contains the * ServiceInfo object with extra information about discovered service. */ public SettableFuture<ServiceInfo> getServiceInfo(final String capability) { final SettableFuture<ServiceInfo> result = SettableFuture.create(); // First, look in the locally cached services. if (mServices != null) { boolean serviceFound = false; for (ServiceInfo service : mServices) { if (service.getcapability().equals(capability)) { Log.i(TAG, "getServiceInfo - " + service.getserviceName() + " service for " + capability + " was found in local cached services"); result.set(service); serviceFound = true; break; } } if (!serviceFound) { NoSuchElementException noSuchElementException = new NoSuchElementException( "The " + capability + " capability was not found in the local cached services."); Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage()); result.setException(noSuchElementException); } } else { // The services have not been cached yet. Go ask the discovery service. AuthenticationController.getInstance().setResourceId(Constants.DISCOVERY_RESOURCE_ID); ADALDependencyResolver dependencyResolver = (ADALDependencyResolver) AuthenticationController .getInstance().getDependencyResolver(); DiscoveryClient discoveryClient = new DiscoveryClient(Constants.DISCOVERY_RESOURCE_URL, dependencyResolver); try { ListenableFuture<List<ServiceInfo>> future = discoveryClient.getservices() .select("serviceResourceId,serviceEndpointUri,capability").read(); Futures.addCallback(future, new FutureCallback<List<ServiceInfo>>() { @Override public void onSuccess(final List<ServiceInfo> services) { Log.i(TAG, "getServiceInfo - Services discovered\n"); // Save the discovered services to serve further requests from the local cache. mServices = services; boolean serviceFound = false; for (ServiceInfo service : services) { if (service.getcapability().equals(capability)) { Log.i(TAG, "getServiceInfo - " + service.getserviceName() + " service for " + capability + " was found in services retrieved from discovery"); result.set(service); serviceFound = true; break; } } if (!serviceFound) { NoSuchElementException noSuchElementException = new NoSuchElementException( "The " + capability + " capability was not found in the user services."); Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage()); result.setException(noSuchElementException); } } @Override public void onFailure(Throwable t) { Log.e(TAG, "getServiceInfo - " + t.getMessage()); result.setException(t); } }); } catch (Exception e) { Log.e(TAG, "getServiceInfo - " + e.getMessage()); result.setException(e); } } return result; }
From source file:org.dcache.xdr.RpcCall.java
private <T extends XdrAble> Future<T> getCallFuture(int procedure, XdrAble args, final T result, long timeoutValue, TimeUnit timeoutUnits, RpcAuth auth) throws IOException { final SettableFuture<T> future = SettableFuture.create(); CompletionHandler<RpcReply, XdrTransport> callback = new CompletionHandler<RpcReply, XdrTransport>() { @Override// ww w . j a v a2 s . c om public void completed(RpcReply reply, XdrTransport attachment) { try { reply.getReplyResult(result); future.set(result); } catch (IOException e) { failed(e, attachment); } } @Override public void failed(Throwable exc, XdrTransport attachment) { future.setException(exc); } }; int xid = callInternal(procedure, args, callback, timeoutValue, timeoutUnits, auth); //wrap the future if no timeout provided up-front to properly un-register //the handler if a timeout is later provided to Future.get() return timeoutValue > 0 ? future : new TimeoutAwareFuture<>(future, xid); }
From source file:com.github.jsdossier.RenderTaskExecutor.java
/** * Signals that no further tasks will be submitted and the executor should wait for existing tasks * to complete.//from w w w.j a va2s. c om * * @return a future that will resolve to a list of all rendered files. */ public ListenableFuture<List<Path>> awaitTermination() { executorService.shutdown(); final SettableFuture<List<Path>> completedTasks = SettableFuture.create(); final int numTasks = submittedTasks.size(); FutureCallback<Path> callback = new FutureCallback<Path>() { private final AtomicBoolean loggedError = new AtomicBoolean(false); private final List<Path> completed = new ArrayList<>(); @Override public synchronized void onSuccess(Path result) { completed.add(result); if (completed.size() >= numTasks) { completedTasks.set(completed); } } @Override public void onFailure(Throwable t) { // Only log an error once since the hard shutdown will likely cause other failures. if (loggedError.compareAndSet(false, true)) { logger.log(Level.SEVERE, "An error occurred", t); completedTasks.setException(t); } executorService.shutdownNow(); } }; for (ListenableFuture<Path> task : submittedTasks) { Futures.addCallback(task, callback); } return transformAsync(completedTasks, new AsyncFunction<List<Path>, List<Path>>() { @Override public ListenableFuture<List<Path>> apply(@Nonnull List<Path> input) throws IOException { input.add(typeIndexTask.call()); return Futures.immediateFuture(input); } }, directExecutor()); }
From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTable.java
/** * Delete an entity from a Mobile Service Table * * @param element The entity to Undelete * @param parameters A list of user-defined parameters and values to include in the * request URI query string *//* w ww.j ava 2 s .com*/ public ListenableFuture<Void> delete(E element, List<Pair<String, String>> parameters) { validateId(element); final SettableFuture<Void> future = SettableFuture.create(); JsonObject json = null; try { json = mClient.getGsonBuilder().create().toJsonTree(element).getAsJsonObject(); } catch (IllegalArgumentException e) { future.setException(e); return future; } ListenableFuture<Void> internalFuture = mInternalTable.delete(json, parameters); Futures.addCallback(internalFuture, new FutureCallback<Void>() { @Override public void onFailure(Throwable exc) { future.setException(transformToTypedException(exc)); } @Override public void onSuccess(Void v) { future.set(null); } }); return future; }
From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTable.java
/** * Updates an entity from a Mobile Service Table * * @param element The entity to update * @param parameters A list of user-defined parameters and values to include in the * request URI query string * @param callback Callback to invoke when the operation is completed *//*from w w w . ja va 2s.co m*/ public ListenableFuture<E> update(final E element, final List<Pair<String, String>> parameters) { final SettableFuture<E> future = SettableFuture.create(); JsonObject json = null; try { json = mClient.getGsonBuilder().create().toJsonTree(element).getAsJsonObject(); } catch (IllegalArgumentException e) { future.setException(e); return future; } ListenableFuture<JsonObject> internalFuture = mInternalTable.update(json, parameters); Futures.addCallback(internalFuture, new FutureCallback<JsonElement>() { @Override public void onFailure(Throwable exc) { future.setException(transformToTypedException(exc)); } @Override public void onSuccess(JsonElement result) { E entity = null; try { entity = parseResults(result).get(0); if (entity != null && element != null) { copyFields(entity, element); entity = element; } future.set(entity); } catch (Exception e) { future.setException(e); } } }); return future; }