Example usage for com.google.common.util.concurrent SettableFuture setException

List of usage examples for com.google.common.util.concurrent SettableFuture setException

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SettableFuture setException.

Prototype

@Override
    public boolean setException(Throwable throwable) 

Source Link

Usage

From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java

/**
 * Registers the client for template notifications with the specified tags
 *
 * @param pnsHandle    PNS specific identifier
 * @param templateName The template name
 * @param template     The template body
 * @param tags         The tags to use in the registration
 * @return Future with TemplateRegistration Information
 */// ww w. j a v  a2 s  .co  m
public ListenableFuture<TemplateRegistration> registerTemplate(String pnsHandle, String templateName,
        String template, String[] tags) {

    final SettableFuture<TemplateRegistration> resultFuture = SettableFuture.create();

    if (isNullOrWhiteSpace(pnsHandle)) {
        resultFuture.setException(new IllegalArgumentException("pnsHandle"));
        return resultFuture;
    }

    if (isNullOrWhiteSpace(templateName)) {
        resultFuture.setException(new IllegalArgumentException("templateName"));
        return resultFuture;
    }

    if (isNullOrWhiteSpace(template)) {
        resultFuture.setException(new IllegalArgumentException("template"));
        return resultFuture;
    }

    final TemplateRegistration registration = mPnsSpecificRegistrationFactory.createTemplateRegistration();
    registration.setPNSHandle(pnsHandle);
    registration.setName(templateName);
    registration.setTemplateBody(template);
    registration.addTags(tags);

    ListenableFuture<String> registerInternalFuture = registerInternal(registration);

    Futures.addCallback(registerInternalFuture, new FutureCallback<String>() {
        @Override
        public void onFailure(Throwable exception) {
            resultFuture.setException(exception);
        }

        @Override
        public void onSuccess(String v) {
            resultFuture.set(registration);
        }
    });

    return resultFuture;
}

From source file:com.continuuity.loom.common.zookeeper.LeaderElection.java

private void doDeleteNode(final SettableFuture<String> completion) {
    if (zkNodePath == null) {
        completion.set(null);//from  w  ww  .  j  a v a2  s. com
    }
    try {
        Futures.addCallback(zkClient.delete(zkNodePath), new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LOG.debug("Node deleted: {}", result);
                completion.set(result);
            }

            @Override
            public void onFailure(Throwable t) {
                LOG.warn("Fail to delete node: {}", zkNodePath);
                if (!(t instanceof KeeperException.NoNodeException)) {
                    LOG.debug("Retry delete node: {}", zkNodePath);
                    doDeleteNode(completion);
                } else {
                    completion.setException(t);
                }
            }
        }, executor);
    } catch (Throwable t) {
        // If any exception happens when calling delete, treats it as completed with failure.
        completion.setException(t);
    }
}

From source file:org.waveprotocol.box.server.waveserver.RemoteWaveletContainerImpl.java

private void internalUpdate(final List<ByteString> deltas, final String domain,
        final WaveletFederationProvider federationProvider, final CertificateManager certificateManager,
        final SettableFuture<Void> futureResult) {
    // Turn raw serialised ByteStrings in to a more useful representation
    final List<ByteStringMessage<ProtocolAppliedWaveletDelta>> appliedDeltas = Lists.newArrayList();
    for (ByteString delta : deltas) {
        try {//from  w w  w  .  ja va2 s . co m
            appliedDeltas.add(ByteStringMessage.parseProtocolAppliedWaveletDelta(delta));
        } catch (InvalidProtocolBufferException e) {
            LOG.info("Invalid applied delta protobuf for incoming " + getWaveletName(), e);
            acquireWriteLock();
            try {
                markStateCorrupted();
            } finally {
                releaseWriteLock();
            }
            futureResult.setException(new FederationException(
                    FederationErrors.badRequest("Invalid applied delta protocol buffer")));
            return;
        }
    }
    LOG.info("Got update: " + appliedDeltas);

    // Fetch any signer info that we don't already have and then run internalUpdate
    final AtomicInteger numSignerInfoPrefetched = new AtomicInteger(1); // extra 1 for sentinel
    final Runnable countDown = new Runnable() {
        @Override
        public void run() {
            if (numSignerInfoPrefetched.decrementAndGet() == 0) {
                internalUpdateAfterSignerInfoRetrieval(appliedDeltas, domain, federationProvider,
                        certificateManager, futureResult);
            }
        }
    };
    SignerInfoPrefetchResultListener prefetchListener = new SignerInfoPrefetchResultListener() {
        @Override
        public void onFailure(FederationError error) {
            LOG.warning("Signer info prefetch failed: " + error);
            countDown.run();
        }

        @Override
        public void onSuccess(ProtocolSignerInfo signerInfo) {
            LOG.info("Signer info prefetch success for " + signerInfo.getDomain());
            countDown.run();
        }
    };
    for (ByteStringMessage<ProtocolAppliedWaveletDelta> appliedDelta : appliedDeltas) {
        ProtocolSignedDelta toVerify = appliedDelta.getMessage().getSignedOriginalDelta();
        HashedVersion deltaEndVersion;
        try {
            deltaEndVersion = AppliedDeltaUtil.calculateResultingHashedVersion(appliedDelta);
        } catch (InvalidProtocolBufferException e) {
            LOG.warning("Skipping illformed applied delta " + appliedDelta, e);
            continue;
        }
        for (ProtocolSignature sig : toVerify.getSignatureList()) {
            if (certificateManager.retrieveSignerInfo(sig.getSignerId()) == null) {
                LOG.info("Fetching signer info " + Base64.encodeBase64(sig.getSignerId().toByteArray()));
                numSignerInfoPrefetched.incrementAndGet();
                certificateManager.prefetchDeltaSignerInfo(federationProvider, sig.getSignerId(),
                        getWaveletName(), deltaEndVersion, prefetchListener);
            }
        }
    }
    // If we didn't fetch any signer info, run internalUpdate immediately
    countDown.run();
}

From source file:io.viewserver.client.ViewServerClient.java

protected ListenableFuture<Boolean> sendCommand(Command command, boolean requireAuthentication) {
    SettableFuture<Boolean> future = SettableFuture.create();
    if (command.getMessage() != null) {
        command.getMessage().retain();/*from   ww w . j a  v  a2s . c o  m*/
    }
    reactor.addCallback(requireAuthentication ? authenticateFuture : connectFuture,
            new FutureCallback<IPeerSession>() {
                @Override
                public void onSuccess(IPeerSession peerSession) {
                    ICommandResultListener originalListener = command.getCommandResultListener();
                    command.setCommandResultListener((result) -> {
                        if (result.isSuccess()) {
                            future.set(true);
                        } else {
                            future.setException(new ViewServerClientException(result.getMessage()));
                        }
                        if (originalListener != null) {
                            originalListener.onResult(result);
                        }
                    });
                    peerSession.sendCommand(command);
                    command.getMessage().release();
                }

                @Override
                public void onFailure(Throwable t) {
                    future.setException(t);
                }
            });
    return future;
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTable.java

/**
 * Looks up a row in the table.// w ww .j av a  2s.c  o  m
 *
 * @param id         The id of the row
 * @param parameters A list of user-defined parameters and values to include in the
 *                   request URI query string
 */
public ListenableFuture<E> lookUp(Object id, List<Pair<String, String>> parameters) {
    final SettableFuture<E> future = SettableFuture.create();

    ListenableFuture<JsonObject> internalFuture = mInternalTable.lookUp(id, parameters);
    Futures.addCallback(internalFuture, new FutureCallback<JsonElement>() {
        @Override
        public void onFailure(Throwable exc) {
            future.setException(transformToTypedException(exc));
        }

        @Override
        public void onSuccess(JsonElement result) {
            try {
                future.set(parseResults(result).get(0));
            } catch (Exception e) {
                future.setException(e);
            }
        }
    });

    return future;
}

From source file:com.google.cloud.pubsub.v1.MessageDispatcher.java

public void processOutstandingBatches() {
    while (true) {
        boolean batchDone = false;
        Runnable batchCallback = null;
        OutstandingMessage outstandingMessage;
        synchronized (outstandingMessageBatches) {
            OutstandingMessageBatch nextBatch = outstandingMessageBatches.peek();
            if (nextBatch == null) {
                return;
            }//  w  ww.j  ava  2 s .  c  om
            outstandingMessage = nextBatch.messages.peek();
            if (outstandingMessage == null) {
                return;
            }
            try {
                // This is a non-blocking flow controller.
                flowController.reserve(1,
                        outstandingMessage.receivedMessage().getMessage().getSerializedSize());
            } catch (FlowController.MaxOutstandingElementCountReachedException
                    | FlowController.MaxOutstandingRequestBytesReachedException flowControlException) {
                return;
            } catch (FlowControlException unexpectedException) {
                throw new IllegalStateException("Flow control unexpected exception", unexpectedException);
            }
            nextBatch.messages.poll(); // We got a hold to the message already.
            batchDone = nextBatch.messages.isEmpty();
            if (batchDone) {
                outstandingMessageBatches.poll();
                batchCallback = nextBatch.doneCallback;
            }
        }

        final PubsubMessage message = outstandingMessage.receivedMessage().getMessage();
        final AckHandler ackHandler = outstandingMessage.ackHandler();
        final SettableFuture<AckReply> response = SettableFuture.create();
        final AckReplyConsumer consumer = new AckReplyConsumer() {
            @Override
            public void ack() {
                response.set(AckReply.ACK);
            }

            @Override
            public void nack() {
                response.set(AckReply.NACK);
            }
        };
        Futures.addCallback(response, ackHandler);
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    receiver.receiveMessage(message, consumer);
                } catch (Exception e) {
                    response.setException(e);
                }
            }
        });
        if (batchDone) {
            batchCallback.run();
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTable.java

/**
 * Executes a query to retrieve all the table rows
 *
 * @param query The Query instance to execute
 *///from   w w  w. j a  v  a2s.c om
public ListenableFuture<MobileServiceList<E>> execute(Query query) {
    final SettableFuture<MobileServiceList<E>> future = SettableFuture.create();
    ListenableFuture<JsonElement> internalFuture = mInternalTable.execute(query);
    Futures.addCallback(internalFuture, new FutureCallback<JsonElement>() {
        @Override
        public void onFailure(Throwable exc) {
            future.setException(exc);
        }

        @Override
        public void onSuccess(JsonElement result) {
            processQueryResults(result, future);
        }
    });

    return future;
}

From source file:io.crate.executor.transport.RepositoryService.java

public ListenableFuture<Long> execute(CreateRepositoryAnalyzedStatement statement) {
    final SettableFuture<Long> result = SettableFuture.create();
    final String repoName = statement.repositoryName();

    PutRepositoryRequest request = new PutRepositoryRequest(repoName);
    request.type(statement.repositoryType());
    request.settings(statement.settings());
    putRepositoryAction.execute(request, new ActionListener<PutRepositoryResponse>() {
        @Override//from w  w  w .  j  a v a2 s.  com
        public void onResponse(PutRepositoryResponse putRepositoryResponse) {
            result.set(1L);
        }

        @Override
        public void onFailure(Throwable e) {
            final Throwable t = convertRepositoryException(e);

            // in case the put repo action fails in the verificationPhase the repository got already created
            // but an exception is raised anyway.
            // --> remove the repo and then return the exception to the user
            dropIfExists(repoName, new Runnable() {
                @Override
                public void run() {
                    result.setException(t);
                }
            });
        }
    });
    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java

private ListenableFuture<ArrayList<Registration>> getFullRegistrationInformation(String pnsHandle) {
    final SettableFuture<ArrayList<Registration>> resultFuture = SettableFuture.create();

    if (isNullOrWhiteSpace(pnsHandle)) {
        resultFuture.setException(new IllegalArgumentException("pnsHandle"));
        return resultFuture;
    }//from w w  w.j  ava 2s. c  o m

    // get existing registrations
    String path = PNS_API_URL + "/registrations/";

    List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>();
    List<Pair<String, String>> parameters = new ArrayList<Pair<String, String>>();
    parameters.add(new Pair<String, String>("platform", mPnsSpecificRegistrationFactory.getPlatform()));
    parameters.add(new Pair<String, String>("deviceId", pnsHandle));
    requestHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE));

    ListenableFuture<ServiceFilterResponse> serviceFilterFuture = mHttpClient.request(path, null, "GET",
            requestHeaders, parameters);

    Futures.addCallback(serviceFilterFuture, new FutureCallback<ServiceFilterResponse>() {
        @Override
        public void onFailure(Throwable exception) {
            resultFuture.setException(exception);
        }

        @Override
        public void onSuccess(ServiceFilterResponse response) {
            ArrayList<Registration> registrationsList = new ArrayList<Registration>();

            JsonArray registrations = new JsonParser().parse(response.getContent()).getAsJsonArray();

            for (JsonElement registrationJson : registrations) {
                Registration registration = null;
                if (registrationJson.getAsJsonObject().has("templateName")) {
                    registration = mPnsSpecificRegistrationFactory
                            .parseTemplateRegistration(registrationJson.getAsJsonObject());
                } else {
                    registration = mPnsSpecificRegistrationFactory
                            .parseNativeRegistration(registrationJson.getAsJsonObject());
                }

                registrationsList.add(registration);
            }

            resultFuture.set(registrationsList);
        }
    });

    return resultFuture;
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTable.java

/**
 * Executes a Next Link to retrieve all the table rows
 *
 * @param nextLink The next link with the page information
 *///from www.ja  v a  2 s . c  om
public ListenableFuture<MobileServiceList<E>> execute(String nextLink) {
    final SettableFuture<MobileServiceList<E>> future = SettableFuture.create();
    ListenableFuture<JsonElement> internalFuture = mInternalTable.execute(nextLink);
    Futures.addCallback(internalFuture, new FutureCallback<JsonElement>() {
        @Override
        public void onFailure(Throwable exc) {
            future.setException(exc);
        }

        @Override
        public void onSuccess(JsonElement result) {
            processQueryResults(result, future);
        }
    });

    return future;
}