List of usage examples for com.google.common.util.concurrent SettableFuture setException
@Override public boolean setException(Throwable throwable)
From source file:co.cask.cdap.common.zookeeper.ZKExtOperations.java
/** * Sets the content of a ZK node. Depends on the {@code createFirst} value, * either {@link ZKClient#create(String, byte[], org.apache.zookeeper.CreateMode)} or * {@link ZKClient#setData(String, byte[])} wil be called first. * * @param zkClient The ZKClient to perform the operations. * @param path The path in ZK./* w ww .j a v a 2s . c om*/ * @param data The content of the ZK node. * @param result The result that will be set into the result future when completed successfully. * @param maxFailure Maximum number of times to try to create/set the content. * @param createFirst If true, create is called first, otherwise setData is called first. * @param <V> Type of the result. * @return A {@link ListenableFuture} that will be completed when node is created or data is set. The future will * fail if failed to create and to set the data. Calling {@link ListenableFuture#cancel(boolean)} has * no effect. */ private static <V> ListenableFuture<V> setContent(final ZKClient zkClient, final String path, final byte[] data, final V result, final int maxFailure, boolean createFirst, final List<ACL> createAcls) { final SettableFuture<V> resultFuture = SettableFuture.create(); final AtomicInteger failureCount = new AtomicInteger(0); OperationFuture<?> operationFuture; if (createFirst) { if (createAcls != null) { operationFuture = zkClient.create(path, data, CreateMode.PERSISTENT, createAcls); } else { operationFuture = zkClient.create(path, data, CreateMode.PERSISTENT); } } else { operationFuture = zkClient.setData(path, data); } Futures.addCallback(operationFuture, new FutureCallback<Object>() { @Override public void onSuccess(Object zkResult) { resultFuture.set(result); } @Override public void onFailure(Throwable t) { if (failureCount.getAndIncrement() > maxFailure) { resultFuture.setException(new Exception("Failed more than " + maxFailure + "times", t)); } else if (t instanceof KeeperException.NoNodeException) { // If node not exists, create it with the data OperationFuture<?> createFuture; if (createAcls != null) { createFuture = zkClient.create(path, data, CreateMode.PERSISTENT, createAcls); } else { createFuture = zkClient.create(path, data, CreateMode.PERSISTENT); } Futures.addCallback(createFuture, this, Threads.SAME_THREAD_EXECUTOR); } else if (t instanceof KeeperException.NodeExistsException) { // If the node exists when trying to create, set data. Futures.addCallback(zkClient.setData(path, data), this, Threads.SAME_THREAD_EXECUTOR); } else { resultFuture.setException(t); } } }, Threads.SAME_THREAD_EXECUTOR); return resultFuture; }
From source file:com.google.caliper.runner.server.ServerSocketService.java
@Override protected void shutDown() throws Exception { serverSocket.close();/*w w w.j a v a 2 s . c om*/ // Now we have either been asked to stop or have failed with some kind of exception, we want to // notify all pending requests, so if there are any references outside of this class they will // notice. lock.lock(); try { for (SettableFuture<Socket> future : halfFinishedConnections.values()) { future.setException(new Exception("The socket has been closed")); } halfFinishedConnections.clear(); connectionState.clear(); } finally { lock.unlock(); } }
From source file:org.openqa.selenium.safari.WebSocketConnection.java
private void handleWebSocketFrame(WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { SettableFuture<String> response = pendingResponse.getAndSet(null); if (null != response) { CloseWebSocketFrame f = (CloseWebSocketFrame) frame; response.setException( new ConnectionClosedException("The driver socket was closed (" + f.getStatusCode() + ")")); }/*w w w . ja va 2 s.c om*/ } else if (frame instanceof PingWebSocketFrame) { channel.write(new PongWebSocketFrame(frame.getBinaryData())); } else if (frame instanceof TextWebSocketFrame) { SettableFuture<String> response = pendingResponse.getAndSet(null); if (null != response) { response.set(((TextWebSocketFrame) frame).getText()); } else { log.warning("Unexpected message: " + ((TextWebSocketFrame) frame).getText()); } } else { log.fine("Unexpected frame type: " + frame.getClass().getName()); } }
From source file:org.apache.jackrabbit.oak.plugins.document.BatchCommit.java
void executeIndividually() { DocumentStore store = queue.getStore(); for (UpdateOp op : ops) { SettableFuture<NodeDocument> result = SettableFuture.create(); try {//from w ww . j a v a 2s . c om result.set(store.findAndUpdate(NODES, op)); } catch (Throwable t) { result.setException(t); } results.add(result); } }
From source file:com.tinspx.util.net.Requests.java
/** * Wraps {@code delegate} in a {@code RequestContext} that will convert * successful responses that satisfy {@code failPredicate} to an error. Note * that converting the response to a failure only affects the status of the * response {@code ListenableFuture}, and has <i>no</i> effect on the * {@link RequestCallback} callback methods. *//*from ww w . j av a 2 s . com*/ public static RequestContext toFailure(final @NonNull AsyncFunction<? super Request, Response> delegate, final @NonNull Predicate<? super Response> failPredicate) { return new RequestContext() { @Override public ListenableFuture<Response> apply(Request request) throws Exception { ListenableFuture<Response> delegateFuture = delegate.apply(request); final SettableFuture<Response> future = SettableFuture.create(); Futures.addCallback(delegateFuture, new FutureCallback<Response>() { @Override public void onSuccess(Response result) { try { if (failPredicate.apply(result)) { result.onError(Errors.message("predicate failure: %s", failPredicate)); future.setException(new RequestException(result)); } else { future.set(result); } } catch (Throwable t) { //have to ensure the returned future always completes //even if the predicate or onError throws future.setException(new RequestException(result, t)); //guava Futures should log this throw Throwables.propagate(t); } } @Override public void onFailure(Throwable t) { future.setException(t); } }); FutureUtils.linkFailure(future, delegateFuture, false); return future; } }; }
From source file:org.pentaho.di.core.KettleEnvironment.java
public static void init(List<PluginTypeInterface> pluginClasses, boolean simpleJndi) throws KettleException { SettableFuture<Boolean> ready; if (initialized.compareAndSet(null, ready = SettableFuture.create())) { try {//from w w w.j a v a 2 s .c om // This creates .kettle and kettle.properties... // if (!KettleClientEnvironment.isInitialized()) { KettleClientEnvironment.init(); } // Configure Simple JNDI when we run in stand-alone mode (spoon, pan, kitchen, carte, ... NOT on the platform // if (simpleJndi) { JndiUtil.initJNDI(); } // Register the native types and the plugins for the various plugin types... // pluginClasses.forEach(PluginRegistry::addPluginType); PluginRegistry.init(); // Also read the list of variables. // KettleVariablesList.init(); // Initialize the Lifecycle Listeners // initLifecycleListeners(); ready.set(true); } catch (Throwable t) { ready.setException(t); // If it's a KettleException, throw it, otherwise wrap it in a KettleException throw ((t instanceof KettleException) ? (KettleException) t : new KettleException(t)); } } else { // A different thread is initializing ready = initialized.get(); // Block until environment is initialized try { ready.get(); } catch (Throwable t) { // If it's a KettleException, throw it, otherwise wrap it in a KettleException throw ((t instanceof KettleException) ? (KettleException) t : new KettleException(t)); } } }
From source file:org.opendaylight.openflowjava.protocol.impl.core.SwitchConnectionProviderImpl.java
@Override public ListenableFuture<Boolean> startup() { LOG.debug("Startup summoned"); ListenableFuture<Boolean> result = null; try {// w w w . j a va2 s.c om serverFacade = createAndConfigureServer(); if (switchConnectionHandler == null) { throw new IllegalStateException("SwitchConnectionHandler is not set"); } new Thread(serverFacade).start(); result = serverFacade.getIsOnlineFuture(); } catch (final Exception e) { final SettableFuture<Boolean> exResult = SettableFuture.create(); exResult.setException(e); result = exResult; } return result; }
From source file:org.opendaylight.controller.cluster.datastore.messages.ReadData.java
@Override public void processResponse(Object readResponse, SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) { if (ReadDataReply.isSerializedType(readResponse)) { ReadDataReply reply = ReadDataReply.fromSerializable(readResponse); returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode())); } else {/*from ww w .j a v a2s. c o m*/ returnFuture .setException(new ReadFailedException("Invalid response reading data for path " + getPath())); } }
From source file:org.anhonesteffort.chnlbrkr.chnlzr.IdleChnlzrConnection.java
protected IdleChnlzrConnection(SettableFuture<IdleChnlzrConnection> future, String id, long timeoutMs) { this.future = future; this.id = id; this.timeoutMs = timeoutMs; timeoutTask = new TimerTask() { @Override/*from w ww .ja va 2s . c o m*/ public void run() { if (future.setException(new TimeoutException("chnlzr capabilities receive timeout exceeded"))) { context.close(); } } }; }
From source file:co.cask.cdap.data2.transaction.queue.leveldb.LevelDBQueueEvictor.java
@Override public ListenableFuture<Integer> evict(final Transaction transaction) { final SettableFuture<Integer> result = SettableFuture.create(); executor.execute(new Runnable() { @Override/*from w ww .j ava 2s . c o m*/ public void run() { try { result.set(doEvict(transaction)); } catch (Throwable t) { result.setException(t); } } }); return result; }