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

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

Introduction

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

Prototype

@Override
    public boolean set(@Nullable V value) 

Source Link

Usage

From source file:org.copperengine.core.persistent.cassandra.CassandraStorage.java

private SettableFuture<Void> createSettableFuture(final ResultSetFuture rsf, final String mpId,
        final long startTsNanos) {
    final SettableFuture<Void> rv = SettableFuture.create();
    rsf.addListener(new Runnable() {
        @Override/* w  w w .  j  a  v  a  2  s . com*/
        public void run() {
            try {
                runtimeStatisticsCollector.submit(mpId, 1, System.nanoTime() - startTsNanos,
                        TimeUnit.NANOSECONDS);
                rsf.get();
                rv.set(null);
            } catch (InterruptedException e) {
                rv.setException(e);
            } catch (ExecutionException e) {
                rv.setException(e.getCause());
            }

        }
    }, executor);
    return rv;
}

From source file:edu.umich.si.inteco.minuku.dao.AnnotatedImageDataRecordDAO.java

public final void getLastNValues(final int N, final String userEmail, final Date someDate,
        final List<T> synchronizedListOfRecords, final SettableFuture settableFuture,
        final String databaseURL) {
    Firebase firebaseRef = new Firebase(databaseURL).child(userEmail)
            .child(new SimpleDateFormat("MMddyyyy").format(someDate).toString()).child(imageType);

    Log.d(TAG, "Checking the value of N " + N);

    if (N <= 0) {
        /* TODO(neerajkumar): Get this f***up fixed! */
        // The first element in the list is actually the last in the database.
        // Reverse the list before setting the future with a result.
        Collections.reverse(synchronizedListOfRecords);

        settableFuture.set(synchronizedListOfRecords);
        return;// w  ww . j  a  v  a2s.c  o  m
    }

    firebaseRef.limitToLast(N).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int newN = N;

            // dataSnapshot.exists returns false when the
            // <root>/<datarecord>/<userEmail>/<date> location does not exist.
            // What it means is that no entries were added for this date, i.e.
            // all the historic information has been exhausted.
            if (!dataSnapshot.exists()) {
                // The first element in the list is actually the last in the database.
                // Reverse the list before setting the future with a result.
                Collections.reverse(synchronizedListOfRecords);

                settableFuture.set(synchronizedListOfRecords);
                return;
            }

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                synchronizedListOfRecords.add(snapshot.getValue(mDataRecordType));
                newN--;
            }
            Date newDate = new Date(someDate.getTime() - 26 * 60 * 60 * 1000); /* -1 Day */
            getLastNValues(newN, userEmail, newDate, synchronizedListOfRecords, settableFuture, databaseURL);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

            // The first element in the list is actually the last in the database.
            // Reverse the list before setting the future with a result.
            Collections.reverse(synchronizedListOfRecords);

            // This would mean that the firebase ref does not exist thereby meaning that
            // the number of entries for all dates are over before we could get the last N
            // results
            settableFuture.set(synchronizedListOfRecords);
        }
    });
}

From source file:org.opendaylight.netvirt.vpnmanager.VpnRpcServiceImpl.java

@SuppressWarnings("checkstyle:IllegalCatch")
@Override// ww  w  .  j a  v a  2 s .  c o m
public Future<RpcResult<AddStaticRouteOutput>> addStaticRoute(AddStaticRouteInput input) {

    SettableFuture<RpcResult<AddStaticRouteOutput>> result = SettableFuture.create();
    String destination = input.getDestination();
    String vpnInstanceName = input.getVpnInstanceName();
    String nexthop = input.getNexthop();
    Long label = input.getLabel();
    LOG.info("Adding static route for Vpn {} with destination {}, nexthop {} and label {}", vpnInstanceName,
            destination, nexthop, label);

    Collection<RpcError> rpcErrors = validateAddStaticRouteInput(input);
    if (!rpcErrors.isEmpty()) {
        result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withRpcErrors(rpcErrors).build());
        return result;
    }

    if (label == null || label == 0) {
        label = (long) VpnUtil.getUniqueId(idManager, VpnConstants.VPN_IDPOOL_NAME,
                VpnUtil.getNextHopLabelKey(vpnInstanceName, destination));
        if (label == 0) {
            String message = "Unable to retrieve a new Label for the new Route";
            result.set(RpcResultBuilder.<AddStaticRouteOutput>failed()
                    .withError(RpcError.ErrorType.APPLICATION, message).build());
            return result;
        }
    }

    String vpnRd = VpnUtil.getVpnRd(dataBroker, input.getVpnInstanceName());
    VpnInstanceOpDataEntry vpnOpEntry = VpnUtil.getVpnInstanceOpData(dataBroker, vpnRd);
    Boolean isVxlan = VpnUtil.isL3VpnOverVxLan(vpnOpEntry.getL3vni());
    VrfEntry.EncapType encapType = VpnUtil.getEncapType(isVxlan);
    if (vpnRd == null) {
        String message = "Could not find Route-Distinguisher for VpnName " + vpnInstanceName;
        result.set(RpcResultBuilder.<AddStaticRouteOutput>failed()
                .withError(RpcError.ErrorType.APPLICATION, message).build());
        return result;
    }

    Optional<InterVpnLinkDataComposite> optIVpnLink = InterVpnLinkCache.getInterVpnLinkByEndpoint(nexthop);
    if (optIVpnLink.isPresent()) {
        try {
            InterVpnLinkUtil.handleStaticRoute(optIVpnLink.get(), vpnInstanceName, destination, nexthop,
                    label.intValue(), dataBroker, fibManager, bgpManager);
        } catch (Exception e) {
            String errMsg = "Could not advertise route [vpn=" + vpnRd + ", prefix=" + destination + ", label="
                    + label + ", nexthop=" + nexthop + ", ] to BGP. Reason: " + e.getMessage();
            LOG.warn(errMsg, e);
            result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(ErrorType.APPLICATION, errMsg)
                    .build());
            return result;
        }
    } else {
        vpnInterfaceMgr.addExtraRoute(vpnInstanceName, destination, nexthop, vpnRd, null /* routerId */,
                label.intValue(), vpnOpEntry.getL3vni(), RouteOrigin.STATIC, null /* intfName */,
                null /*Adjacency*/, encapType, null);
    }

    AddStaticRouteOutput labelOutput = new AddStaticRouteOutputBuilder().setLabel(label).build();
    result.set(RpcResultBuilder.success(labelOutput).build());
    return result;
}

From source file:com.spotify.futures.ConcurrencyLimiter.java

private void invoke(final SettableFuture<T> response, Callable<? extends ListenableFuture<T>> callable) {
    final ListenableFuture<T> future;
    try {//from ww w . j av  a2  s.c  o  m
        future = callable.call();
        if (future == null) {
            limit.release();
            response.setException(new NullPointerException());
            return;
        }
    } catch (Throwable e) {
        limit.release();
        response.setException(e);
        return;
    }

    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            limit.release();
            response.set(result);
            pump();
        }

        @Override
        public void onFailure(Throwable t) {
            limit.release();
            response.setException(t);
            pump();
        }
    });
}

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

private void setException(SettableFuture<Long> result, Throwable e, CreateTableAnalyzedStatement statement) {
    e = Exceptions.unwrap(e);// ww  w .ja  v  a2s.co m
    String message = e.getMessage();
    if ("mapping [default]".equals(message) && e.getCause() != null) {
        // this is a generic mapping parse exception,
        // the cause has usually a better more detailed error message
        result.setException(e.getCause());
    } else if (statement.ifNotExists() && (e instanceof IndexAlreadyExistsException
            || (e instanceof IndexTemplateAlreadyExistsException && statement.templateName() != null))) {
        result.set(null);
    } else {
        result.setException(e);
    }
}

From source file:edu.umich.si.inteco.minuku.dao.ImageDataRecordDAO.java

@Override
public Future<List<ImageDataRecord>> getAll() throws DAOException {
    final SettableFuture<List<ImageDataRecord>> settableFuture = SettableFuture.create();
    Firebase imageListRef = new Firebase(Constants.getInstance().getFirebaseUrlForImages()).child(myUserEmail)
            .child(new SimpleDateFormat("MMddyyyy").format(new Date()).toString());

    imageListRef.addValueEventListener(new ValueEventListener() {
        @Override//from w w w .ja  v  a  2s . c o m
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, ImageDataRecord> imageListMap = (HashMap<String, ImageDataRecord>) dataSnapshot
                    .getValue();
            List<ImageDataRecord> values = (List) imageListMap.values();
            settableFuture.set(values);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            settableFuture.set(null);
        }
    });
    return settableFuture;
}

From source file:c5db.replication.ReplicatorService.java

@Override
public ListenableFuture<Replicator> createReplicator(final String quorumId, final Collection<Long> peers) {
    final SettableFuture<Replicator> future = SettableFuture.create();

    ListenableFuture<ReplicatorLog> logFuture = logModule.getReplicatorLog(quorumId);

    C5Futures.addCallback(logFuture, (ReplicatorLog log) -> {
        Replicator replicator = createReplicatorWithLog(log, quorumId, peers);
        future.set(replicator);
    }, future::setException, fiber);/* w  w w  .  j ava  2  s  .c o  m*/

    return future;
}

From source file:org.opendaylight.netconf.topology.singleton.impl.tx.NetconfReadOnlyTransaction.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {

    LOG.trace("{}: Exists {} via NETCONF: {}", id, store, path);

    final Future<Boolean> existsFuture = delegate.exists(store, path);
    final SettableFuture<Boolean> settableFuture = SettableFuture.create();
    final CheckedFuture<Boolean, ReadFailedException> checkedFuture;
    checkedFuture = Futures.makeChecked(settableFuture, new Function<Exception, ReadFailedException>() {
        @Nullable//from w w  w. ja va 2 s  .  c  o  m
        @Override
        public ReadFailedException apply(Exception cause) {
            return new ReadFailedException("Read from transaction failed", cause);
        }
    });
    existsFuture.onComplete(new OnComplete<Boolean>() {
        @Override
        public void onComplete(final Throwable throwable, final Boolean result) throws Throwable {
            if (throwable == null) {
                settableFuture.set(result);
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}

From source file:eu.esdihumboldt.hale.common.headless.transform.Transformation.java

private static void failure(SettableFuture<Boolean> result, IJobChangeEvent event) {
    // signal if was canceled
    /*/*from w w  w  .j  av a  2s. com*/
     * XXX disabled as the transform job will cancel the export job if it
     * fails
     */
    //      if (event.getResult().matches(IStatus.CANCEL)) {
    //         result.cancel(false);
    //      }

    String jobName = event.getJob() != null ? event.getJob().getName() : "unknown";
    String msg = "Error occured in job \"" + jobName + "\"";
    if (event.getResult() != null && event.getResult().getMessage() != null) {
        msg = msg + ": " + event.getResult().getMessage();
    }

    // try setting exception
    if (event.getResult() != null && event.getResult().getException() != null) {
        log.error(msg, event.getResult().getException());

        if (!result.setException(event.getResult().getException())) {
            log.error("Exception could not be set on future (already completed or cancelled)");
        }
        return;
    }

    log.error(msg);

    // in case there was no exception or setting it failed, just state that
    // execution was not successful
    if (!result.set(false)) {
        log.error("Failure could not be set on future (already completed or cancelled)");
    }
}

From source file:com.google.cloud.dataflow.sdk.runners.worker.WindmillStateReader.java

private <T> void consumeTagList(TagList tagList, StateTag stateTag) {
    boolean shouldRemove;
    if (stateTag.requestToken == null) {
        // This is the response for the first page.
        // Leave the future in the cache so subsequent requests for the first page
        // can return immediately.
        shouldRemove = false;/*from   ww w.j a  v a  2s  .c o  m*/
    } else {
        // This is a response for a subsequent page.
        // Don't cache the future since we may need to make multiple requests with different
        // continuation tokens.
        shouldRemove = true;
    }
    CoderAndFuture<T, ValuesAndContToken<T>> coderAndFuture = getWaiting(stateTag, shouldRemove);
    SettableFuture<ValuesAndContToken<T>> future = coderAndFuture.getNonDoneFuture(stateTag);
    Coder<T> coder = coderAndFuture.getAndClearCoder();
    List<T> values = this.<T>tagListPageValues(tagList, coder);
    future.set(new ValuesAndContToken<T>(values,
            tagList.hasContinuationToken() ? tagList.getContinuationToken() : null));
}