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.table.MobileServiceTable.java

/**
 * Undelete 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
 *///from w w w .j  ava 2 s . com
public ListenableFuture<E> undelete(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.undelete(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;
}

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

/**
 * Inserts an entity into a Mobile Service Table
 *
 * @param element    The entity to insert
 * @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  .j  a  v a2 s  .co m
public ListenableFuture<E> insert(final E element, 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;
    }

    Class<?> idClazz = getIdPropertyClass(element.getClass());

    if (idClazz != null && !isIntegerClass(idClazz)) {
        json = removeSystemProperties(json);
    }

    ListenableFuture<JsonObject> internalFuture = mInternalTable.insert(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 {

                if (result != null) {
                    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;
}

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

@Override
public void start() {
    FluentIterable<NodeOperation> nodeOperations = FluentIterable.from(nodeOperationTrees)
            .transformAndConcat(new Function<NodeOperationTree, Iterable<? extends NodeOperation>>() {
                @Nullable/*from  w  ww  .ja  va 2 s  .c om*/
                @Override
                public Iterable<? extends NodeOperation> apply(NodeOperationTree input) {
                    return input.nodeOperations();
                }
            });

    Map<String, Collection<NodeOperation>> operationByServer = NodeOperationGrouper
            .groupByServer(nodeOperations);
    List<PageDownstreamContext> pageDownstreamContexts = new ArrayList<>(nodeOperationTrees.size());
    List<Tuple<ExecutionPhase, RowReceiver>> handlerPhases = new ArrayList<>(nodeOperationTrees.size());

    if (operationType == OperationType.BULK || nodeOperationTrees.size() > 1) {
        // bulk Operation with rowCountResult
        for (int i = 0; i < nodeOperationTrees.size(); i++) {
            SettableFuture<TaskResult> result = results.get(i);
            RowCountResultRowDownstream rowDownstream = new RowCountResultRowDownstream(result);
            handlerPhases.add(
                    new Tuple<ExecutionPhase, RowReceiver>(nodeOperationTrees.get(i).leaf(), rowDownstream));
        }
    } else {
        SettableFuture<TaskResult> result = Iterables.getOnlyElement(results);
        QueryResultRowDownstream downstream = new QueryResultRowDownstream(result);
        handlerPhases.add(new Tuple<ExecutionPhase, RowReceiver>(
                Iterables.getOnlyElement(nodeOperationTrees).leaf(), downstream));
    }

    try {
        setupContext(operationByServer, pageDownstreamContexts, handlerPhases);
    } catch (Throwable throwable) {
        for (SettableFuture<TaskResult> result : results) {
            result.setException(throwable);
        }
    }
    if (operationByServer.isEmpty()) {
        return;
    }
    sendJobRequests(pageDownstreamContexts, operationByServer);
}

From source file:org.opendaylight.openflowplugin.impl.statistics.StatisticsContextImpl.java

void statChainFuture(final Iterator<MultipartType> iterator, final SettableFuture<Boolean> resultFuture) {
    if (!iterator.hasNext()) {
        resultFuture.set(Boolean.TRUE);
        LOG.debug("Stats collection successfully finished for node {}",
                deviceContext.getDeviceState().getNodeId());
        return;/*  w  ww  .ja  v a 2 s . com*/
    }

    final MultipartType nextType = iterator.next();
    LOG.debug("Stats iterating to next type for node {} of type {}", deviceContext.getDeviceState().getNodeId(),
            nextType);

    final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = chooseStat(nextType);
    Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
        @Override
        public void onSuccess(final Boolean result) {
            statChainFuture(iterator, resultFuture);
        }

        @Override
        public void onFailure(final Throwable t) {
            resultFuture.setException(t);
        }
    });
}

From source file:com.microsoft.windowsazure.mobileservices.http.MobileServiceConnection.java

/**
 * Execute a request-response operation with a Mobile Service
 *
 * @param request          The request to execute
 * @param responseCallback Callback to invoke after the request is executed
 *//*w w w  . j a  v a 2  s  .com*/
public ListenableFuture<ServiceFilterResponse> start(final ServiceFilterRequest request) {
    if (request == null) {
        throw new IllegalArgumentException("Request can not be null");
    }

    ServiceFilter filter = mClient.getServiceFilter();
    // Set the request's headers
    configureHeadersOnRequest(request);
    return filter.handleRequest(request, new NextServiceFilterCallback() {

        @Override
        public ListenableFuture<ServiceFilterResponse> onNext(ServiceFilterRequest request) {
            SettableFuture<ServiceFilterResponse> future = SettableFuture.create();
            ServiceFilterResponse response = null;

            try {
                response = request.execute();
                int statusCode = response.getStatus().getStatusCode();

                // If the response has error throw exception
                if (statusCode < 200 || statusCode >= 300) {
                    String responseContent = response.getContent();
                    if (responseContent != null && !responseContent.trim().equals("")) {
                        throw new MobileServiceException(responseContent, response);
                    } else {
                        throw new MobileServiceException(String.format("{'code': %d}", statusCode), response);
                    }
                }

                future.set(response);
            } catch (MobileServiceException e) {
                future.setException(e);
            } catch (Exception e) {
                future.setException(new MobileServiceException("Error while processing request.", e, response));
            }

            return future;
        }
    });
}

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

/**
 * Registers the client for native notifications with the specified tags
 *
 * @param pnsHandle PNS specific identifier
 * @param tags      Tags to use in the registration
 * @return Future with Registration Information
 *//*www.  ja  v a  2 s  . com*/
public ListenableFuture<Registration> register(String pnsHandle, String[] tags) {

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

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

    final Registration registration = mPnsSpecificRegistrationFactory.createNativeRegistration();
    registration.setPNSHandle(pnsHandle);
    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:org.opendaylight.netconf.topology.util.BaseTopologyManager.java

@Override
public void notifyNodeStatusChange(final NodeId nodeId) {
    LOG.debug("Connection status has changed on node {}", nodeId.getValue());
    if (isMaster) {
        // grab status from all peers and aggregate
        final ArrayList<ListenableFuture<Node>> futures = new ArrayList<>();
        futures.add(delegateTopologyHandler.getCurrentStatusForNode(nodeId));
        // only master should call connect on peers and aggregate futures
        for (TopologyManager topologyManager : peers.values()) {
            // add a future into our futures that gets its completion status from the converted scala future
            final SettableFuture<Node> settableFuture = SettableFuture.create();
            futures.add(settableFuture);
            final Future<NormalizedNodeMessage> scalaFuture = topologyManager
                    .remoteGetCurrentStatusForNode(nodeId);
            scalaFuture.onComplete(new OnComplete<NormalizedNodeMessage>() {
                @Override//from  w w  w .ja  va  2 s.co  m
                public void onComplete(Throwable failure, NormalizedNodeMessage success) throws Throwable {
                    if (failure != null) {
                        settableFuture.setException(failure);
                        return;
                    }
                    final Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode = codecRegistry
                            .fromNormalizedNode(success.getIdentifier(), success.getNode());
                    final Node value = (Node) fromNormalizedNode.getValue();

                    settableFuture.set(value);
                }
            }, TypedActor.context().dispatcher());
        }

        final ListenableFuture<Node> aggregatedFuture = aggregator.combineUpdateAttempts(futures);
        Futures.addCallback(aggregatedFuture, new FutureCallback<Node>() {
            @Override
            public void onSuccess(final Node result) {
                LOG.debug("Futures aggregated succesfully");
                naSalNodeWriter.update(nodeId, result);
            }

            @Override
            public void onFailure(final Throwable t) {
                // If the combined connection attempt failed, set the node to connection failed
                LOG.debug("Futures aggregation failed");
                naSalNodeWriter.update(nodeId, delegateTopologyHandler.getFailedState(nodeId, null));
            }
        });
        return;
    }
    LOG.debug("Not master, forwarding..");
    for (final TopologyManager manager : peers.values()) {
        // asynchronously find out which peer is master
        final Future<Boolean> future = manager.isMaster();
        future.onComplete(new OnComplete<Boolean>() {
            @Override
            public void onComplete(Throwable failure, Boolean success) throws Throwable {
                if (failure == null && success) {
                    LOG.debug("Found master peer");
                    // forward to master
                    manager.notifyNodeStatusChange(nodeId);
                    return;
                }
                if (failure != null) {
                    LOG.debug("Retrieving master peer failed, {}", failure);
                }
            }
        }, TypedActor.context().dispatcher());
    }
}

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

private ListenableFuture<Void> refreshRegistrationInformation(String pnsHandle) {

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

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

    // delete old registration information
    Editor editor = mSharedPreferences.edit();
    Set<String> keys = mSharedPreferences.getAll().keySet();
    for (String key : keys) {
        if (key.startsWith(STORAGE_PREFIX + REGISTRATION_NAME_STORAGE_KEY)) {
            editor.remove(key);
        }
    }

    editor.commit();

    ListenableFuture<ArrayList<Registration>> getFullRegistrationInformationFuture = getFullRegistrationInformation(
            pnsHandle);

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

        @Override
        public void onSuccess(ArrayList<Registration> registrations) {
            for (Registration registration : registrations) {

                try {
                    storeRegistrationId(registration.getName(), registration.getRegistrationId(),
                            registration.getPNSHandle());
                } catch (Exception e) {
                    resultFuture.setException(e);

                    return;
                }
            }

            mIsRefreshNeeded = false;

            resultFuture.set(null);
        }
    });

    return resultFuture;
}

From source file:org.apache.qpid.server.virtualhostnode.AbstractVirtualHostNode.java

@StateTransition(currentState = { State.ACTIVE, State.STOPPED, State.ERRORED }, desiredState = State.DELETED)
protected ListenableFuture<Void> doDelete() {
    final SettableFuture<Void> futureResult = SettableFuture.create();

    // Delete the node only if deletion of the virtualhost succeeds.
    addFutureCallback(deleteVirtualHostIfExists(), new FutureCallback<Void>() {
        @Override/*w  w  w. ja  v a 2  s  . com*/
        public void onSuccess(final Void result) {
            addFutureCallback(closeAsync(), new FutureCallback<Void>() {
                @Override
                public void onSuccess(final Void result) {
                    try {
                        delete();
                        futureResult.set(null);
                    } catch (Throwable t) {
                        futureResult.setException(t);
                    }
                }

                @Override
                public void onFailure(final Throwable t) {
                    try {
                        delete();
                    } finally {
                        futureResult.setException(t);
                    }
                }

                private void delete() {
                    deleted();
                    setState(State.DELETED);
                    DurableConfigurationStore configurationStore = getConfigurationStore();
                    if (configurationStore != null) {
                        configurationStore.onDelete(AbstractVirtualHostNode.this);
                    }
                }
            }, getTaskExecutor());
        }

        @Override
        public void onFailure(final Throwable t) {
            futureResult.setException(t);
        }
    }, getTaskExecutor());

    return futureResult;
}

From source file:io.crate.executor.transport.task.UpsertByIdTask.java

private List<SettableFuture<Long>> initializeBulkShardProcessor(Settings settings) {
    assert upsertById.updateColumns() != null || upsertById.insertColumns() != null;
    ShardUpsertRequest.Builder builder = new ShardUpsertRequest.Builder(
            CrateSettings.BULK_REQUEST_TIMEOUT.extractTimeValue(settings), false, // do not overwrite duplicates
            upsertById.numBulkResponses() > 0 || upsertById.items().size() > 1
                    || upsertById.updateColumns() != null, // continue on error on bulk, on multiple values and/or update
            upsertById.updateColumns(), upsertById.insertColumns(), jobId(), false);
    BulkShardProcessor<ShardUpsertRequest> bulkShardProcessor = new BulkShardProcessor<>(clusterService,
            transportBulkCreateIndicesAction, indexNameExpressionResolver, settings, bulkRetryCoordinatorPool,
            upsertById.isPartitionedTable(), upsertById.items().size(), builder,
            transportShardUpsertActionDelegate, jobId());
    bulkShardProcessorContext = new BulkShardProcessorContext(upsertById.executionPhaseId(),
            bulkShardProcessor);//ww  w .  ja v a 2 s . co m

    if (upsertById.numBulkResponses() == 0) {
        final SettableFuture<Long> futureResult = SettableFuture.create();
        List<SettableFuture<Long>> resultList = new ArrayList<>(1);
        resultList.add(futureResult);
        Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
            @Override
            public void onSuccess(@Nullable BitSet result) {
                if (result == null) {
                    // unknown rowcount
                    futureResult.set(Executor.ROWCOUNT_UNKNOWN);
                } else {
                    futureResult.set((long) result.cardinality());
                }
                bulkShardProcessorContext.close();
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                futureResult.setException(t);
                bulkShardProcessorContext.close();
            }
        });
        return resultList;
    } else {
        final int numResults = upsertById.numBulkResponses();
        final Integer[] resultsRowCount = new Integer[numResults];
        final List<SettableFuture<Long>> resultList = new ArrayList<>(numResults);
        for (int i = 0; i < numResults; i++) {
            resultList.add(SettableFuture.<Long>create());
        }

        Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
            @Override
            public void onSuccess(@Nullable BitSet result) {
                if (result == null) {
                    setAllToFailed(null);
                    return;
                }

                for (int i = 0; i < result.length(); i++) {
                    int resultIdx = upsertById.bulkIndices().get(i);

                    if (resultsRowCount[resultIdx] == null) {
                        resultsRowCount[resultIdx] = result.get(i) ? 1 : -2;
                    } else if (resultsRowCount[resultIdx] >= 0 && result.get(i)) {
                        resultsRowCount[resultIdx]++;
                    }
                }

                for (int i = 0; i < numResults; i++) {
                    SettableFuture<Long> future = resultList.get(i);
                    Integer rowCount = resultsRowCount[i];
                    if (rowCount != null && rowCount >= 0) {
                        future.set((long) rowCount);
                    } else {
                        // failure
                        future.set(Executor.ROWCOUNT_ERROR);
                    }
                }

                bulkShardProcessorContext.close();
            }

            private void setAllToFailed(@Nullable Throwable throwable) {
                if (throwable == null) {
                    for (SettableFuture<Long> future : resultList) {
                        future.set(Executor.ROWCOUNT_ERROR);
                    }
                } else {
                    for (SettableFuture<Long> future : resultList) {
                        future.setException(throwable);
                    }
                }
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                setAllToFailed(t);
                bulkShardProcessorContext.close();
            }
        });
        return resultList;
    }
}