Example usage for com.google.common.util.concurrent Futures immediateFuture

List of usage examples for com.google.common.util.concurrent Futures immediateFuture

Introduction

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

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) 

Source Link

Document

Creates a ListenableFuture which has its value set immediately upon construction.

Usage

From source file:org.opendaylight.bgpcep.pcep.tunnel.provider.TunnelProgramming.java

@Override
public ListenableFuture<RpcResult<PcepUpdateTunnelOutput>> pcepUpdateTunnel(
        final PcepUpdateTunnelInput updateTunnelInput) {
    final PcepUpdateTunnelOutputBuilder b = new PcepUpdateTunnelOutputBuilder();
    b.setResult(AbstractInstructionExecutor.schedule(this.scheduler, new UpdateTunnelInstructionExecutor(
            updateTunnelInput, TunnelProgramming.this.dataProvider, this.topologyService)));

    final RpcResult<PcepUpdateTunnelOutput> res = SuccessfulRpcResult.create(b.build());
    return Futures.immediateFuture(res);
}

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

@StateTransition(currentState = { State.ACTIVE, State.STOPPED, State.ERRORED }, desiredState = State.DELETED)
private ListenableFuture<Void> doDelete() {
    final ListenableFuture<Void> future = Futures.immediateFuture(null);
    final RedirectingVirtualHostImpl virtualHost = _virtualHost;
    if (virtualHost != null) {
        return doAfter(virtualHost.closeAsync(), new Callable<ListenableFuture<Void>>() {
            @Override/*from   w ww  . j av a 2s.  c om*/
            public ListenableFuture<Void> call() throws Exception {
                _virtualHost = null;
                deleted();
                setState(State.DELETED);
                return future;
            }
        });
    } else {
        setState(State.DELETED);
        deleted();
        return future;
    }
}

From source file:gobblin.eventhub.writer.EventhubBatchAccumulator.java

/**
 * Add a data to internal deque data structure
 *///from   w w  w.  j a  v  a  2 s  .  c o  m
public final Future<RecordMetadata> enqueue(String record, WriteCallback callback) throws InterruptedException {
    final ReentrantLock lock = this.dqLock;
    lock.lock();
    try {
        EventhubBatch last = dq.peekLast();
        if (last != null) {
            Future<RecordMetadata> future = last.tryAppend(record, callback);
            if (future != null) {
                return future;
            }
        }

        // Create a new batch because previous one has no space
        EventhubBatch batch = new EventhubBatch(this.memSizeLimit, this.expireInMilliSecond);
        LOG.debug("Batch " + batch.getId() + " is generated");
        Future<RecordMetadata> future = batch.tryAppend(record, callback);

        // Even single record can exceed the batch size limit
        // Ignore the record because Eventhub can only accept payload less than 256KB
        if (future == null) {
            LOG.error("Batch " + batch.getId() + " is marked as complete because it contains a huge record: "
                    + record);
            future = Futures.immediateFuture(new RecordMetadata(0));
            callback.onSuccess(WriteResponse.EMPTY);
            return future;
        }

        // if queue is full, we should not add more
        while (dq.size() >= this.capacity) {
            this.notFull.await();
        }
        dq.addLast(batch);
        incomplete.add(batch);
        this.notEmpty.signal();
        return future;

    } finally {
        lock.unlock();
    }
}

From source file:com.facebook.buck.remoteexecution.util.LocalContentAddressedStorage.java

public LocalContentAddressedStorage(Path cacheDir, Protocol protocol) {
    this.cacheDir = cacheDir;
    this.protocol = protocol;
    ExecutorService uploadService = MostExecutors.newMultiThreadExecutor("local-cas-write", 4);
    this.uploader = new MultiThreadedBlobUploader(MISSING_CHECK_LIMIT, UPLOAD_SIZE_LIMIT, uploadService,
            new CasBlobUploader() {
                @Override//  w w  w  .  jav a 2 s  .c  o m
                public ImmutableList<UploadResult> batchUpdateBlobs(ImmutableList<UploadData> blobData) {
                    return LocalContentAddressedStorage.this.batchUpdateBlobs(blobData);
                }

                @Override
                public ImmutableSet<String> getMissingHashes(List<Protocol.Digest> requiredDigests) {
                    return findMissing(requiredDigests).map(Protocol.Digest::getHash)
                            .collect(ImmutableSet.toImmutableSet());
                }
            });
    AsyncBlobFetcher fetcher = new AsyncBlobFetcher() {
        @Override
        public ListenableFuture<ByteBuffer> fetch(Protocol.Digest digest) {
            try (InputStream stream = getData(digest)) {
                return Futures.immediateFuture(ByteBuffer.wrap(ByteStreams.toByteArray(stream)));
            } catch (IOException e) {
                return Futures.immediateFailedFuture(e);
            }
        }

        @Override
        public ListenableFuture<Void> fetchToStream(Digest digest, OutputStream outputStream) {
            try (InputStream stream = getData(digest)) {
                ByteStreams.copy(stream, outputStream);
                return Futures.immediateFuture(null);
            } catch (IOException e) {
                return Futures.immediateFailedFuture(e);
            }
        }
    };
    this.outputsMaterializer = new OutputsMaterializer(fetcher, protocol);
    this.inputsMaterializer = new InputsMaterializer(protocol, new InputsMaterializer.Delegate() {
        @Override
        public void materializeFile(Path root, FileNode file) throws IOException {
            Path path = getPath(file.getDigest().getHash());
            Preconditions.checkState(Files.exists(path), "Path %s doesn't exist.", path);
            // As this file could potentially be materialized as both executable and
            // non-executable, and
            // links share that, we need two concrete versions of the file.
            if (file.getIsExecutable()) {
                Path exePath = path.getParent().resolve(path.getFileName() + ".x");
                if (!Files.exists(exePath)) {
                    try (AutoUnlocker ignored = fileLock.writeLock(exePath.toString())) {
                        if (!Files.exists(exePath)) {
                            Path tempPath = path.getParent().resolve(path.getFileName() + ".x.tmp");
                            Files.copy(path, tempPath);
                            Preconditions.checkState(tempPath.toFile().setExecutable(true));
                            Files.move(tempPath, exePath);
                        }
                    }
                }
                path = exePath;
            }
            Path target = root.resolve(file.getName());
            Path normalized = target.normalize();
            Preconditions.checkState(normalized.startsWith(root), "%s doesn't start with %s.", normalized,
                    root);
            Files.createLink(target, path);
        }

        @Override
        public InputStream getData(Protocol.Digest digest) throws IOException {
            return LocalContentAddressedStorage.this.getData(digest);
        }
    });
}

From source file:com.microsoftopentechnologies.wacommon.adauth.BrowserLauncherEclipse.java

@Override
public ListenableFuture<Void> browseAsync(final String url, final String redirectUri, final String callbackUrl,
        final String windowTitle, final boolean noShell) {
    try {/*from w  ww .j a va2  s  .  c o m*/
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                // get the display from Eclipse
                Display display = PlatformUI.getWorkbench().getDisplay();
                Shell shell = (parentShell != null)
                        ? new Shell(parentShell, SWT.PRIMARY_MODAL | SWT.CLOSE | SWT.TITLE | SWT.BORDER)
                        : new Shell(display, SWT.APPLICATION_MODAL | SWT.CLOSE | SWT.TITLE | SWT.BORDER);
                shell.setText(windowTitle);
                Browser browser;
                ADAuthCodeCallback authCodeCallback = new ADAuthCodeCallback(display, shell, callbackUrl);
                shell.setLayout(new FillLayout());
                Monitor monitor = display.getPrimaryMonitor();
                Rectangle bounds = monitor.getBounds();
                Dimension size = new Dimension((int) (bounds.width * 0.40), (int) (bounds.height * 0.70));
                shell.setSize(size.width, size.height);
                shell.setLocation((bounds.width - size.width) / 2, (bounds.height - size.height) / 2);
                shell.setActive();

                try {
                    browser = new org.eclipse.swt.browser.Browser(shell, SWT.NONE);
                } catch (SWTError err) {
                    authCodeCallback.onFailed(Messages.browserErr + " \n" + err.getMessage());
                    throw err;
                }

                BrowserLocationListener locationListener = new BrowserLocationListener(redirectUri,
                        authCodeCallback);
                browser.addLocationListener(locationListener);

                if (noShell) {
                    BrowserSilentProgressListener progressListener = new BrowserSilentProgressListener(
                            authCodeCallback);
                    browser.addProgressListener(progressListener);
                }

                browser.setUrl(url);

                if (!noShell) {
                    shell.open();
                }

                while (!shell.isDisposed()) {
                    if (!display.readAndDispatch()) {
                        display.sleep();
                    }
                }
            }
        });
    } catch (SWTError ex) {
        return Futures.immediateFuture(null);
    }
    // notify the caller that the window was closed
    try {
        httpRequest(new URI(callbackUrl).resolve("closed").toURL());
    } catch (IOException e) {
        return Futures.immediateFailedFuture(e);
    } catch (URISyntaxException e) {
        return Futures.immediateFailedFuture(e);
    }

    return Futures.immediateFuture(null);
}

From source file:io.v.android.security.BlessingsManager.java

/**
 * Returns {@link Blessings} found in {@link SharedPreferences} under the given key.
 * <p>/*from  w  w  w.j av a2 s  .c  o  m*/
 * Unlike {@link #getBlessings}, if no {@link Blessings} are found this method won't mint a new
 * set of {@link Blessings}; instead, {@code null} value is returned.
 *
 * @param context         Vanadium context
 * @param androidContext  android {@link Context} requesting blessings
 * @param key             a key under which the blessings are stored
 * @param setAsDefault    if true, the returned {@link Blessings}, if non-{@code null}, will be
 *                        set as default blessings for the app
 * @return                {@link Blessings} found in {@link SharedPreferences} under the given
 *                        key or {@code null} if no blessings are found
 * @throws VException     if the blessings are found in {@link SharedPreferences} but they
 *                        are invalid
 */
public static Blessings readBlessings(VContext context, Context androidContext, String key,
        boolean setAsDefault) throws VException {
    String blessingsVom = PreferenceManager.getDefaultSharedPreferences(androidContext).getString(key, "");
    if (blessingsVom == null || blessingsVom.isEmpty()) {
        return null;
    }
    Blessings blessings = (Blessings) VomUtil.decodeFromString(blessingsVom, Blessings.class);
    if (blessings == null) {
        throw new VException("Couldn't decode blessings: got null blessings");
    }
    // TODO(spetrovic): validate the blessings and fail if they aren't valid
    return setAsDefault
            ? VFutures.sync(wrapWithSetAsDefault(context, androidContext, Futures.immediateFuture(blessings)))
            : blessings;
}

From source file:com.rhythm.louie.util.FutureList.java

@Override
public void add(int index, E element) {
    futures.add(index, Futures.immediateFuture(element));
}

From source file:org.apache.shindig.social.websockbackend.spi.WsNativeGraphSPI.java

private Future<RestfulCollection<Person>> convertRequested(IQueryCallback result, final Set<String> fields,
        final SecurityToken token) throws ProtocolException {
    final List<Person> dtos = new ArrayList<Person>();

    ListResult resultList = null;/*from w ww  .java 2s.  c om*/
    try {
        resultList = (ListResult) result.get();
    } catch (final Exception e) {
        e.printStackTrace();
        this.fLogger.log(Level.SEVERE, "server error", e);
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not retrieve results",
                e);
    }

    @SuppressWarnings("unchecked")
    final List<Map<String, Object>> mapList = (List<Map<String, Object>>) resultList.getResults();

    // convert the items received
    if (mapList != null) {
        String id = null;
        PersonDTO tmpPerson = null;
        for (final Map<String, Object> personMap : mapList) {
            tmpPerson = new PersonDTO(personMap);
            id = tmpPerson.getId();

            // determine whether the person is viewer or owner
            if (token != null) {
                if (id.equals(token.getViewerId())) {
                    tmpPerson.setIsViewer(true);
                }
                if (id.equals(token.getOwnerId())) {
                    tmpPerson.setIsOwner(true);
                }
            }

            // TODO: generate profile URLs?

            dtos.add(tmpPerson);
        }
    }

    final RestfulCollection<Person> peopleColl = new RestfulCollection<Person>(dtos);
    peopleColl.setItemsPerPage(resultList.getMax());
    peopleColl.setStartIndex(resultList.getFirst());
    peopleColl.setTotalResults(resultList.getTotal());
    return Futures.immediateFuture(peopleColl);
}

From source file:com.google.gapid.server.Client.java

public ListenableFuture<List<Stringtable.Info>> getAvailableStringTables() {
    LOG.log(FINE, "RPC->getAvailableStringTables()");
    return Futures.transformAsync(
            client.getAvailableStringTables(GetAvailableStringTablesRequest.newBuilder().build()),
            in -> Futures.immediateFuture(throwIfError(in.getTables(), in.getError()).getListList()));
}

From source file:gobblin.writer.SequentialBasedBatchAccumulator.java

/**
 * Add a data to internal deque data structure
 *//*w w  w.j av  a  2  s .  co  m*/
public final Future<RecordMetadata> enqueue(D record, WriteCallback callback) throws InterruptedException {
    final ReentrantLock lock = this.dqLock;
    lock.lock();
    try {
        BytesBoundedBatch last = dq.peekLast();
        if (last != null) {
            Future<RecordMetadata> future = last.tryAppend(record, callback);
            if (future != null) {
                return future;
            }
        }

        // Create a new batch because previous one has no space
        BytesBoundedBatch batch = new BytesBoundedBatch(this.memSizeLimit, this.expireInMilliSecond);
        LOG.debug("Batch " + batch.getId() + " is generated");
        Future<RecordMetadata> future = batch.tryAppend(record, callback);

        // Even single record can exceed the batch size limit
        // Ignore the record because Eventhub can only accept payload less than 256KB
        if (future == null) {
            LOG.error("Batch " + batch.getId() + " is marked as complete because it contains a huge record: "
                    + record);
            future = Futures.immediateFuture(new RecordMetadata(0));
            callback.onSuccess(WriteResponse.EMPTY);
            return future;
        }

        // if queue is full, we should not add more
        while (dq.size() >= this.capacity) {
            this.notFull.await();
        }
        dq.addLast(batch);
        incomplete.add(batch);
        this.notEmpty.signal();
        return future;

    } finally {
        lock.unlock();
    }
}