List of usage examples for com.google.common.util.concurrent SettableFuture setException
@Override public boolean setException(Throwable throwable)
From source file:org.opendaylight.netconf.topology.singleton.impl.tx.NetconfReadOnlyTransaction.java
@Override public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) { LOG.trace("{}: Read {} via NETCONF: {}", id, store, path); final Future<Optional<NormalizedNodeMessage>> future = delegate.read(store, path); final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create(); final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> checkedFuture; checkedFuture = Futures.makeChecked(settableFuture, new Function<Exception, ReadFailedException>() { @Nullable/*from www .j a va 2 s . co m*/ @Override public ReadFailedException apply(Exception cause) { return new ReadFailedException("Read from transaction failed", cause); } }); future.onComplete(new OnComplete<Optional<NormalizedNodeMessage>>() { @Override public void onComplete(final Throwable throwable, final Optional<NormalizedNodeMessage> normalizedNodeMessage) throws Throwable { if (throwable == null) { if (normalizedNodeMessage.isPresent()) { settableFuture.set(normalizedNodeMessage .transform(new Function<NormalizedNodeMessage, NormalizedNode<?, ?>>() { @Nullable @Override public NormalizedNode<?, ?> apply(final NormalizedNodeMessage input) { return input.getNode(); } })); } else { settableFuture.set(Optional.absent()); } } else { settableFuture.setException(throwable); } } }, actorSystem.dispatcher()); return checkedFuture; }
From source file:org.opendaylight.distributed.tx.impl.DtxImpl.java
@Override public CheckedFuture<Void, DTxException> deleteAndRollbackOnFailure( DTXLogicalTXProviderType logicalTXProviderType, LogicalDatastoreType logicalDatastoreType, InstanceIdentifier<?> instanceIdentifier, InstanceIdentifier<?> nodeId) { Preconditions.checkArgument(containsIid(nodeId), "Unknown node: %s. Not in transaction", nodeId); final DTXReadWriteTransaction transaction = this.perNodeTransactionsbyLogicalType.get(logicalTXProviderType) .get(nodeId);// w w w .j av a2s. co m CheckedFuture<Void, DTxException> deleteFuture = transaction.asyncDelete(logicalDatastoreType, instanceIdentifier); final SettableFuture<Void> retFuture = SettableFuture.create(); Futures.addCallback(deleteFuture, new FutureCallback<Void>() { @Override public void onSuccess(@Nullable Void aVoid) { retFuture.set(null); } @Override public void onFailure(Throwable throwable) { Runnable runnable = new Runnable() { @Override public void run() { CheckedFuture<Void, DTxException.RollbackFailedException> rollExcept = rollback(); Futures.addCallback(rollExcept, new FutureCallback<Void>() { @Override public void onSuccess(@Nullable Void aVoid) { dtxReleaseDevices(); retFuture.setException(new DTxException.EditFailedException( "Failed to delete but succeed to rollback")); } @Override public void onFailure(Throwable throwable) { dtxReleaseDevices(); retFuture.setException(new DTxException.RollbackFailedException(throwable)); } }); } }; new Thread(runnable).start(); } }); return Futures.makeChecked(retFuture, new Function<Exception, DTxException>() { @Nullable @Override public DTxException apply(@Nullable Exception e) { e = (Exception) e.getCause(); return e instanceof DTxException ? (DTxException) e : new DTxException("delete failed and rollback failure", e); } }); }
From source file:org.opendaylight.netconf.topology.pipeline.tx.ProxyReadOnlyTransaction.java
@Override public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) { final Future<Optional<NormalizedNodeMessage>> future = delegate.read(store, path); final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create(); final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> checkedFuture = Futures .makeChecked(settableFuture, new Function<Exception, ReadFailedException>() { @Nullable// w ww .j a v a2s .com @Override public ReadFailedException apply(Exception cause) { return new ReadFailedException("Read from transaction failed", cause); } }); future.onComplete(new OnComplete<Optional<NormalizedNodeMessage>>() { @Override public void onComplete(Throwable throwable, Optional<NormalizedNodeMessage> normalizedNodeMessage) throws Throwable { if (throwable == null) { if (normalizedNodeMessage.isPresent()) { settableFuture.set(normalizedNodeMessage .transform(new Function<NormalizedNodeMessage, NormalizedNode<?, ?>>() { @Nullable @Override public NormalizedNode<?, ?> apply(NormalizedNodeMessage input) { return input.getNode(); } })); } else { settableFuture.set(Optional.absent()); } } else { settableFuture.setException(throwable); } } }, actorSystem.dispatcher()); return checkedFuture; }
From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java
/** * Updates a registration// w w w . ja va2 s . c o m * * @param registration The registration to update * @param callback The operation callback * @throws java.io.UnsupportedEncodingException * @throws Exception */ private ListenableFuture<Void> upsertRegistrationInternal(final Registration registration) { final SettableFuture<Void> resultFuture = SettableFuture.create(); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder = gsonBuilder.excludeFieldsWithoutExposeAnnotation(); Gson gson = gsonBuilder.create(); String resource = registration.getURI(); String path = PNS_API_URL + resource; JsonElement json = gson.toJsonTree(registration); String body = json.toString(); byte[] content; try { content = body.getBytes(MobileServiceClient.UTF8_ENCODING); } catch (UnsupportedEncodingException e) { resultFuture.setException(e); return resultFuture; } List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>(); requestHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE)); ListenableFuture<ServiceFilterResponse> serviceFilterFuture = mHttpClient.request(path, content, "PUT", requestHeaders, null); Futures.addCallback(serviceFilterFuture, new FutureCallback<ServiceFilterResponse>() { @Override public void onFailure(Throwable exception) { resultFuture.setException(exception); } @Override public void onSuccess(ServiceFilterResponse response) { resultFuture.set(null); } }); return resultFuture; }
From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java
/** * Creates a new registration in the server. If it exists, updates its * information/* w ww . j a v a 2 s . co m*/ * * @param registration The registration to create * @param callback The operation callback */ private ListenableFuture<String> registerInternal(final Registration registration) { final SettableFuture<String> resultFuture = SettableFuture.create(); String pNSHandle = mSharedPreferences.getString(STORAGE_PREFIX + PNS_HANDLE_KEY, ""); if (isNullOrWhiteSpace(pNSHandle)) { pNSHandle = registration.getPNSHandle(); } ListenableFuture<Void> refreshRegistrationInformationIfNeededFuture = refreshRegistrationInformationIfNeeded( pNSHandle); Futures.addCallback(refreshRegistrationInformationIfNeededFuture, new FutureCallback<Void>() { @Override public void onFailure(Throwable exception) { resultFuture.setException(exception); } @Override public void onSuccess(Void v) { Futures.addCallback(createRegistrationId(registration), new FutureCallback<String>() { @Override public void onFailure(Throwable exception) { resultFuture.setException(exception); } @Override public void onSuccess(String registrationId) { resultFuture.set(registrationId); } }); } }); return resultFuture; }
From source file:com.kixeye.kixmpp.client.KixmppClient.java
/** * Connects to the hostname and port./* ww w.j av a 2 s . co m*/ * * @param hostname * @param port */ public ListenableFuture<KixmppClient> connect(String hostname, int port, String domain) { checkAndSetState(State.CONNECTING, State.DISCONNECTED); this.jid = new KixmppJid(domain); try { this.handshaker = WebSocketClientHandshakerFactory.newHandshaker( new URI("ws://" + hostname + ":" + port), WebSocketVersion.V13, null, false, new DefaultHttpHeaders()); } catch (Exception e) { throw new RuntimeException("Unable to set up handshaker.", e); } setUp(); // set this in case we get disconnected deferredDisconnect = SettableFuture.create(); deferredLogin = SettableFuture.create(); final SettableFuture<KixmppClient> responseFuture = SettableFuture.create(); connectListener.set(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { if (future.isSuccess()) { if (state.compareAndSet(State.CONNECTING, State.CONNECTED)) { logger.info("Kixmpp Client connected to [{}]", ((ChannelFuture) future).channel().remoteAddress()); channel.set(((ChannelFuture) future).channel()); responseFuture.set(KixmppClient.this); } } else { state.set(State.DISCONNECTED); responseFuture.setException(future.cause()); } } }); ChannelFuture future = bootstrap.connect(hostname, port); switch (type) { case TCP: future.addListener(connectListener.get()); break; case WEBSOCKET: future.addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { if (!future.isSuccess()) { state.set(State.DISCONNECTED); responseFuture.setException(future.cause()); } } }); break; } return responseFuture; }
From source file:org.litecoinj.protocols.channels.PaymentChannelServerState.java
/** * Called when the client provides the multi-sig contract. Checks that the previously-provided refund transaction * spends this transaction (because we will use it as a base to create payment transactions) as well as output value * and form (ie it is a 2-of-2 multisig to the correct keys). * * @param contract The provided multisig contract. Do not mutate this object after this call. * @return A future which completes when the provided multisig contract successfully broadcasts, or throws if the broadcast fails for some reason * Note that if the network simply rejects the transaction, this future will never complete, a timeout should be used. * @throws VerificationException If the provided multisig contract is not well-formed or does not meet previously-specified parameters *//*from ww w. j a va 2 s. com*/ public synchronized ListenableFuture<PaymentChannelServerState> provideContract(final Transaction contract) throws VerificationException { checkNotNull(contract); stateMachine.checkState(State.WAITING_FOR_MULTISIG_CONTRACT); try { contract.verify(); this.contract = contract; verifyContract(contract); // Check that contract's first output is a 2-of-2 multisig to the correct pubkeys in the correct order final Script expectedScript = createOutputScript(); if (!Arrays.equals(getContractScript().getProgram(), expectedScript.getProgram())) throw new VerificationException(getMajorVersion() == 1 ? "Contract's first output was not a standard 2-of-2 multisig to client and server in that order." : "Contract was not a P2SH script of a CLTV redeem script to client and server"); if (getTotalValue().signum() <= 0) throw new VerificationException("Not accepting an attempt to open a contract with zero value."); } catch (VerificationException e) { // We couldn't parse the multisig transaction or its output. log.error("Provided multisig contract did not verify: {}", contract.toString()); throw e; } log.info("Broadcasting multisig contract: {}", contract); wallet.addWatchedScripts(ImmutableList.of(contract.getOutput(0).getScriptPubKey())); stateMachine.transition(State.WAITING_FOR_MULTISIG_ACCEPTANCE); final SettableFuture<PaymentChannelServerState> future = SettableFuture.create(); Futures.addCallback(broadcaster.broadcastTransaction(contract).future(), new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction transaction) { log.info("Successfully broadcast multisig contract {}. Channel now open.", transaction.getHashAsString()); try { // Manually add the contract to the wallet, overriding the isRelevant checks so we can track // it and check for double-spends later wallet.receivePending(contract, null, true); } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen, we already called contract.verify() } stateMachine.transition(State.READY); future.set(PaymentChannelServerState.this); } @Override public void onFailure(Throwable throwable) { // Couldn't broadcast the transaction for some reason. log.error("Failed to broadcast contract", throwable); stateMachine.transition(State.ERROR); future.setException(throwable); } }); return future; }
From source file:io.crate.action.sql.DDLAnalysisDispatcher.java
private void mergeMappingAndUpdateTemplate(final SettableFuture<Long> result, final Map<String, Object> mapping, final IndexTemplateMetaData templateMetaData, final AtomicInteger operations) { Map<String, Object> mergedMapping = mergeMapping(templateMetaData, mapping); PutIndexTemplateRequest updateTemplateRequest = new PutIndexTemplateRequest(templateMetaData.name()) .create(false).mapping(Constants.DEFAULT_MAPPING_TYPE, mergedMapping) .settings(templateMetaData.settings()).template(templateMetaData.template()); for (ObjectObjectCursor<String, AliasMetaData> container : templateMetaData.aliases()) { Alias alias = new Alias(container.key); updateTemplateRequest.alias(alias); }//from w ww . ja va 2 s. c om transportPutIndexTemplateAction.execute(updateTemplateRequest, new ActionListener<PutIndexTemplateResponse>() { @Override public void onResponse(PutIndexTemplateResponse putIndexTemplateResponse) { if (operations.decrementAndGet() == 0) { result.set(1L); } } @Override public void onFailure(Throwable e) { result.setException(e); } }); }
From source file:com.twitter.distributedlog.auditor.DLAuditor.java
/** * Find leak ledgers phase 1: collect ledgers set. */// ww w. j a v a 2 s. co m private Set<Long> collectLedgersFromBK(BookKeeperClient bkc, final ExecutorService executorService) throws IOException { LedgerManager lm = BookKeeperAccessor.getLedgerManager(bkc.get()); final Set<Long> ledgers = new HashSet<Long>(); final SettableFuture<Void> doneFuture = SettableFuture.create(); BookkeeperInternalCallbacks.Processor<Long> collector = new BookkeeperInternalCallbacks.Processor<Long>() { @Override public void process(Long lid, final AsyncCallback.VoidCallback cb) { synchronized (ledgers) { ledgers.add(lid); if (0 == ledgers.size() % 1000) { logger.info("Collected {} ledgers", ledgers.size()); } } executorService.submit(new Runnable() { @Override public void run() { cb.processResult(BKException.Code.OK, null, null); } }); } }; AsyncCallback.VoidCallback finalCb = new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { if (BKException.Code.OK == rc) { doneFuture.set(null); } else { doneFuture.setException(BKException.create(rc)); } } }; lm.asyncProcessLedgers(collector, finalCb, null, BKException.Code.OK, BKException.Code.ZKException); try { doneFuture.get(); logger.info("Collected total {} ledgers", ledgers.size()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new DLInterruptedException("Interrupted on collecting ledgers : ", e); } catch (ExecutionException e) { if (e.getCause() instanceof IOException) { throw (IOException) (e.getCause()); } else { throw new IOException("Failed to collect ledgers : ", e.getCause()); } } return ledgers; }
From source file:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java
/** * Invokes a custom API/*from www. j a v a 2 s . c o m*/ * * @param apiName The API name * @param content The byte array to send as the request body * @param httpMethod The HTTP Method used to invoke the API * @param requestHeaders The extra headers to send in the request * @param parameters The query string parameters sent in the request * @param features The SDK features used in the request */ private ListenableFuture<ServiceFilterResponse> invokeApiInternal(String apiName, byte[] content, String httpMethod, List<Pair<String, String>> requestHeaders, List<Pair<String, String>> parameters, EnumSet<MobileServiceFeatures> features) { final SettableFuture<ServiceFilterResponse> future = SettableFuture.create(); if (apiName == null || apiName.trim().equals("")) { future.setException(new IllegalArgumentException("apiName cannot be null")); return future; } MobileServiceHttpClient httpClient = new MobileServiceHttpClient(this); return httpClient.request(CUSTOM_API_URL + apiName, content, httpMethod, requestHeaders, parameters, features); }