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:com.android.camera.one.v2.initialization.CaptureSessionCreator.java

/**
 * Asynchronously creates a capture session, returning a future to it.
 *
 * @param surfaces The set of output surfaces for the camera capture
 *            session./* ww w  .j ava2  s  .co m*/
 * @return A Future for the camera capture session.
 */
public ListenableFuture<CameraCaptureSessionProxy> createCaptureSession(List<Surface> surfaces) {
    final SettableFuture<CameraCaptureSessionProxy> sessionFuture = SettableFuture.create();
    try {
        mDevice.createCaptureSession(surfaces, new CameraCaptureSessionProxy.StateCallback() {
            @Override
            public void onActive(CameraCaptureSessionProxy session) {
                // Ignore.
            }

            @Override
            public void onConfigureFailed(CameraCaptureSessionProxy session) {
                sessionFuture.cancel(true);
                session.close();
            }

            @Override
            public void onConfigured(CameraCaptureSessionProxy session) {
                boolean valueSet = sessionFuture.set(session);
                if (!valueSet) {
                    // If the future was already marked with cancellation or
                    // an exception, close the session.
                    session.close();
                }
            }

            @Override
            public void onReady(CameraCaptureSessionProxy session) {
                // Ignore.
            }

            @Override
            public void onClosed(CameraCaptureSessionProxy session) {
                sessionFuture.cancel(true);
                session.close();
            }
        }, mCameraHandler);
    } catch (CameraAccessException e) {
        sessionFuture.setException(e);
    }
    return sessionFuture;
}

From source file:org.apache.bookkeeper.bookie.LedgerDescriptorImpl.java

/**
 * Log the fence ledger entry in Journal so that we can rebuild the state.
 * @param journal log the fence entry in the Journal
 * @return A future which will be satisfied when add entry to journal complete
 *//*from ww  w . jav  a  2 s  .  com*/
private SettableFuture<Boolean> logFenceEntryInJournal(Journal journal) {
    SettableFuture<Boolean> result;
    synchronized (this) {
        result = logFenceResult = SettableFuture.create();
    }
    ByteBuf entry = createLedgerFenceEntry(ledgerId);
    try {
        journal.logAddEntry(entry, false /* ackBeforeSync */, (rc, ledgerId, entryId, addr, ctx) -> {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Record fenced state for ledger {} in journal with rc {}", ledgerId,
                        BKException.codeLogger(rc));
            }
            if (rc == 0) {
                fenceEntryPersisted.compareAndSet(false, true);
                result.set(true);
            } else {
                result.set(false);
            }
        }, null);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        result.setException(e);
    }
    return result;
}

From source file:com.datastax.driver.core.PerHostPercentileTracker.java

/**
 * @return null if no histogram is available yet (no entries recorded, or not for long enough)
 *//*from   w ww.j a  v  a  2  s. co  m*/
private Histogram getLastIntervalHistogram(Host host) {
    try {
        while (true) {
            CachedHistogram entry = cachedHistograms.get(host);
            if (entry == null)
                return null;

            long age = System.currentTimeMillis() - entry.timestamp;
            if (age < intervalMs) { // current histogram is recent enough
                return entry.histogram.get();
            } else { // need to refresh
                Recorder recorder = recorders.get(host);
                // intervalMs should be much larger than the time it takes to replace a histogram, so this future should never block
                Histogram staleHistogram = entry.histogram.get(0, MILLISECONDS);
                SettableFuture<Histogram> future = SettableFuture.create();
                CachedHistogram newEntry = new CachedHistogram(future);
                if (cachedHistograms.replace(host, entry, newEntry)) {
                    // Only get the new histogram if we successfully replaced the cache entry.
                    // This ensures that only one thread will do it.
                    Histogram newHistogram = recorder.getIntervalHistogram(staleHistogram);
                    future.set(newHistogram);
                    return newHistogram;
                }
                // If we couldn't replace the entry it means we raced, so loop to try again
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return null;
    } catch (ExecutionException e) {
        throw new DriverInternalError("Unexpected error", e.getCause());
    } catch (TimeoutException e) {
        throw new DriverInternalError("Unexpected timeout while getting histogram", e);
    }
}

From source file:org.opendaylight.distributed.tx.impl.DTXTestTransaction.java

@Override
public <T extends DataObject> CheckedFuture<Optional<T>, ReadFailedException> read(
        LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<T> instanceIdentifier) {
    T obj = null;//from   w w  w.j av a  2 s. com

    if (txDataMap.get(instanceIdentifier).size() > 0)
        obj = (T) txDataMap.get(instanceIdentifier).getFirst();

    final Optional<T> retOpt = Optional.fromNullable(obj);

    final SettableFuture<Optional<T>> retFuture = SettableFuture.create();
    Runnable readResult = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(delayTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            boolean readException = getAndResetExceptionWithInstanceIdentifier(readExceptionMap,
                    instanceIdentifier);
            if (readException == false) {
                retFuture.set(retOpt);
            } else {
                retFuture.setException(new Throwable("Read error"));
            }
            retFuture.notifyAll();
        }
    };

    new Thread(readResult).start();

    Function<Exception, ReadFailedException> f = new Function<Exception, ReadFailedException>() {
        @Nullable
        @Override
        public ReadFailedException apply(@Nullable Exception e) {
            return new ReadFailedException("Read failed", e);
        }
    };

    return Futures.makeChecked(retFuture, f);
}

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(//www .  ja  v  a  2 s.  c  o m
                    new ConnectionClosedException("The driver socket was closed (" + f.getStatusCode() + ")"));
        }

    } 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:edu.umich.si.inteco.minuku.dao.NoteDataRecordDAO.java

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

    noteListRef.addValueEventListener(new ValueEventListener() {
        @Override/*w ww. j a  v  a2  s .  c o m*/
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, NoteDataRecord> noteListMap = (HashMap<String, NoteDataRecord>) dataSnapshot.getValue();
            List<NoteDataRecord> values = (List) noteListMap.values();
            settableFuture.set(values);
        }

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

From source file:org.opendaylight.openflowplugin.impl.services.SalExperimenterMpMessageServiceImpl.java

@Override
public Future<RpcResult<SendExperimenterMpRequestOutput>> sendExperimenterMpRequest(
        SendExperimenterMpRequestInput input) {
    final ListenableFuture<RpcResult<List<MultipartReply>>> multipartFuture = handleServiceCall(input);
    final SettableFuture<RpcResult<SendExperimenterMpRequestOutput>> finalFuture = SettableFuture.create();

    class CallBackImpl implements FutureCallback<RpcResult<List<MultipartReply>>> {
        @Override//from w  w  w .j a  v  a 2s. c  o  m
        public void onSuccess(final RpcResult<List<MultipartReply>> result) {
            if (result.isSuccessful()) {
                final List<MultipartReply> multipartReplies = result.getResult();
                if (multipartReplies.isEmpty()) {
                    LOG.warn("Multipart reply to Experimenter-Mp request shouldn't be empty list.");
                    finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed()
                            .withError(ErrorType.RPC, "Multipart reply list is empty.").build());
                } else {
                    LOG.debug(
                            "OnSuccess, rpc result successful, multipart response for rpc sendExperimenterMpRequest with xid {} obtained.",
                            multipartReplies.get(0).getXid());
                    final SendExperimenterMpRequestOutputBuilder sendExpMpReqOutputBuilder = new SendExperimenterMpRequestOutputBuilder();
                    final List<ExperimenterCoreMessageItem> expCoreMessageItem = new ArrayList<>();
                    for (MultipartReply multipartReply : multipartReplies) {
                        final MultipartReplyExperimenterCase caseBody = (MultipartReplyExperimenterCase) multipartReply
                                .getMultipartReplyBody();
                        final MultipartReplyExperimenter replyBody = caseBody.getMultipartReplyExperimenter();
                        final ExperimenterDataOfChoice vendorData = replyBody.getExperimenterDataOfChoice();
                        final MessageTypeKey<? extends ExperimenterDataOfChoice> key = new MessageTypeKey<>(
                                getVersion(), (Class<? extends ExperimenterDataOfChoice>) vendorData
                                        .getImplementedInterface());
                        final ConvertorMessageFromOFJava<ExperimenterDataOfChoice, MessagePath> messageConverter = extensionConverterProvider
                                .getMessageConverter(key);
                        if (messageConverter == null) {
                            LOG.warn("Custom converter for {}[OF:{}] not found",
                                    vendorData.getImplementedInterface(), getVersion());
                            finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed()
                                    .withError(ErrorType.RPC, "Custom converter not found.").build());
                            return;
                        }
                        try {
                            final ExperimenterMessageOfChoice messageOfChoice = messageConverter
                                    .convert(vendorData, MessagePath.MPMESSAGE_RPC_OUTPUT);
                            final ExperimenterCoreMessageItemBuilder expCoreMessageItemBuilder = new ExperimenterCoreMessageItemBuilder();
                            expCoreMessageItemBuilder.setExperimenterMessageOfChoice(messageOfChoice);
                            expCoreMessageItem.add(expCoreMessageItemBuilder.build());
                        } catch (final ConversionException e) {
                            LOG.error("Conversion of experimenter message reply failed. Exception: {}", e);
                            finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed()
                                    .withError(ErrorType.RPC, "Conversion of experimenter rpc output failed.")
                                    .build());
                            return;
                        }
                    }
                    sendExpMpReqOutputBuilder.setExperimenterCoreMessageItem(expCoreMessageItem);
                    finalFuture.set(RpcResultBuilder.success(sendExpMpReqOutputBuilder.build()).build());
                }
            } else {
                LOG.warn(
                        "OnSuccess, rpc result unsuccessful, multipart response for rpc sendExperimenterMpRequest was unsuccessful.");
                finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed()
                        .withRpcErrors(result.getErrors()).build());
            }
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.warn("Failure multipart response for Experimenter-Mp request. Exception: {}", t);
            finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed()
                    .withError(ErrorType.RPC, "Future error", t).build());
        }
    }

    Futures.addCallback(multipartFuture, new CallBackImpl());

    return finalFuture;
}

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

private final void getLastNValues(final int N, final String userEmail, final Date someDate,
        final List<SemanticLocationDataRecord> synchronizedListOfRecords, final SettableFuture settableFuture) {
    Firebase firebaseRef = new Firebase(Constants.getInstance().getFirebaseUrlForSemanticLocation())
            .child(userEmail).child(new SimpleDateFormat("MMddyyyy").format(someDate).toString());

    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;//  ww  w . j av a2s.c  om
    }

    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()) {
                /* 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;
            }

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

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            /* 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);

            // 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.centinel.impl.subscribe.SubscriberImpl.java

@Override
public Future<RpcResult<SubscribeDeleteOutput>> subscribeDelete(SubscribeDeleteInput input) {
    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    final SettableFuture<RpcResult<SubscribeDeleteOutput>> futureResult = SettableFuture.create();
    final SubscribeDeleteOutputBuilder subscribeDeleteOutputBuilder = new SubscribeDeleteOutputBuilder();
    Subscriptions subscriptiontodelete = new SubscriptionsBuilder().setSubscribeID(input.getSubscribeID())
            .build();/*from   w w  w . j a v a 2 s.  c o  m*/

    try {
        tx.delete(LogicalDatastoreType.OPERATIONAL,
                SUBSCRIPTION_ID.child(Subscriptions.class, subscriptiontodelete.getKey()));
        tx.submit();

        subscribeDeleteOutputBuilder.setStatus("SUCCESS");
        futureResult.set(
                RpcResultBuilder.<SubscribeDeleteOutput>success(subscribeDeleteOutputBuilder.build()).build());

        LOG.info("Subscription deleted:" + input.getSubscribeID());
    } catch (Exception ex) {
        LOG.error("Exception in Subscription deleted:" + input.getSubscribeID() + ":ErrorMessage:"
                + ex.getMessage(), ex);
        ErrorType errorType = ErrorType.APPLICATION;
        futureResult.set(RpcResultBuilder.<SubscribeDeleteOutput>failed()
                .withError(errorType, "Exception Caught at widget deletion:" + ex.getMessage())

                .build());
    }
    return futureResult;

}

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

private final void getLastNValues(final int N, final String userEmail, final Date someDate,
        final List<LocationDataRecord> synchronizedListOfRecords, final SettableFuture settableFuture) {
    String firebaseUrlForLocation = Constants.getInstance().getFirebaseUrlForLocation();
    Firebase firebaseRef = new Firebase(firebaseUrlForLocation).child(userEmail)
            .child(new SimpleDateFormat("MMddyyyy").format(someDate).toString());

    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;//from   www  . j  a va  2 s  .c  om
    }

    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()) {
                /* 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;
            }

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

        @Override
        public void onCancelled(FirebaseError firebaseError) {

            /* 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);

            // 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);
        }
    });
}