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:com.joyveb.dbpimpl.cass.prepare.schema.AbstractQueryOperation.java

protected CassandraFuture<List<ResultSet>> doExecuteAsync(Iterator<Statement> queryIterator) {

    if (!queryIterator.hasNext()) {
        ListenableFuture<List<ResultSet>> emptyResultFuture = Futures
                .immediateFuture(Collections.<ResultSet>emptyList());
        CassandraFuture<List<ResultSet>> wrappedFuture = new CassandraFuture<List<ResultSet>>(emptyResultFuture,
                CassandraUtils.EXCEPTION_TRANSLATOR);
        return wrappedFuture;
    }//from   ww w .  j a  v  a  2 s .co m
    final Iterator<ListenableFuture<ResultSet>> resultSetFutures = Iterators.transform(queryIterator,
            new Function<Statement, ListenableFuture<ResultSet>>() {

                @Override
                public ListenableFuture<ResultSet> apply(Statement query) {
                    return doExecuteAsync(query);
                }

            });
    ListenableFuture<List<ResultSet>> allResultSetFuture = Futures
            .successfulAsList(new Iterable<ListenableFuture<ResultSet>>() {

                @Override
                public Iterator<ListenableFuture<ResultSet>> iterator() {
                    return resultSetFutures;
                }

            });

    CassandraFuture<List<ResultSet>> wrappedFuture = new CassandraFuture<List<ResultSet>>(allResultSetFuture,
            CassandraUtils.EXCEPTION_TRANSLATOR);

    return wrappedFuture;
}

From source file:org.lealone.cluster.streaming.ConnectionHandler.java

@SuppressWarnings("unchecked")
public ListenableFuture<?> close() {
    logger.debug("[Stream #{}] Closing stream connection handler on {}", session.planId(), session.peer);

    ListenableFuture<?> inClosed = incoming == null ? Futures.immediateFuture(null) : incoming.close();
    ListenableFuture<?> outClosed = outgoing == null ? Futures.immediateFuture(null) : outgoing.close();

    return Futures.allAsList(inClosed, outClosed);
}

From source file:com.google.api.server.spi.config.datastore.testing.FakeAsyncMemcacheService.java

@Override
public <T> Future<Map<T, Long>> incrementAll(Map<T, Long> offsets) {
    return Futures.immediateFuture(memcacheService.incrementAll(offsets));
}

From source file:com.facebook.buck.artifact_cache.AbstractNetworkCache.java

@Override
public ListenableFuture<Void> store(final ArtifactInfo info, final BorrowablePath output) {
    if (!isStoreSupported()) {
        return Futures.immediateFuture(null);
    }//ww w .  j a v  a2s. c o m

    final HttpArtifactCacheEvent.Scheduled scheduled = HttpArtifactCacheEvent
            .newStoreScheduledEvent(ArtifactCacheEvent.getTarget(info.getMetadata()), info.getRuleKeys());
    buckEventBus.post(scheduled);

    final Path tmp;
    try {
        tmp = getPathForArtifact(output);
    } catch (IOException e) {
        LOG.error(e, "Failed to store artifact in temp file: " + output.getPath().toString());
        return Futures.immediateFuture(null);
    }

    // HTTP Store operations are asynchronous.
    return httpWriteExecutorService.submit(() -> {
        HttpArtifactCacheEvent.Started startedEvent = HttpArtifactCacheEvent.newStoreStartedEvent(scheduled);
        buckEventBus.post(startedEvent);
        HttpArtifactCacheEvent.Finished.Builder finishedEventBuilder = HttpArtifactCacheEvent
                .newFinishedEventBuilder(startedEvent);
        finishedEventBuilder.getStoreBuilder().setRuleKeys(info.getRuleKeys());

        try {

            long artifactSizeBytes = projectFilesystem.getFileSize(tmp);
            finishedEventBuilder.getStoreBuilder().setArtifactSizeBytes(artifactSizeBytes)
                    .setRuleKeys(info.getRuleKeys());
            if (!isArtefactTooBigToBeStored(artifactSizeBytes, maxStoreSize)) {
                storeImpl(info, tmp, finishedEventBuilder);
            } else {
                LOG.info("Artifact too big so not storing it in the distributed cache. "
                        + "file=[%s] buildTarget=[%s]", tmp, info.getBuildTarget());
            }
            buckEventBus.post(finishedEventBuilder.build());

        } catch (IOException e) {
            reportFailure(e, "store(%s): %s: %s", info.getRuleKeys(), e.getClass().getName(), e.getMessage());
            finishedEventBuilder.getStoreBuilder().setWasStoreSuccessful(false).setErrorMessage(e.toString());
            buckEventBus.post(finishedEventBuilder.build());
        }
        try {
            projectFilesystem.deleteFileAtPathIfExists(tmp);
        } catch (IOException e) {
            LOG.warn(e, "Failed to delete file %s", tmp);
        }
    }, /* result */ null);
}

From source file:org.opendaylight.vbd.impl.TopologyMonitor.java

@Override
public synchronized void onDataTreeChanged(
        @Nonnull final Collection<DataTreeModification<VbridgeTopology>> changes) {
    for (DataTreeModification<VbridgeTopology> c : changes) {
        @SuppressWarnings("unchecked")
        final KeyedInstanceIdentifier<Topology, TopologyKey> topology = (KeyedInstanceIdentifier<Topology, TopologyKey>) c
                .getRootPath().getRootIdentifier().firstIdentifierOf(Topology.class);

        Preconditions.checkArgument(!topology.isWildcarded(), "Wildcard topology %s is not supported",
                topology);/*from   www  .ja v a2s . c  om*/

        final DataObjectModification<VbridgeTopology> mod = c.getRootNode();
        ListenableFuture<Void> processionState = Futures.immediateFuture(null);
        switch (mod.getModificationType()) {
        case DELETE:
            LOG.debug("Topology {} removed", PPrint.topology(topology));
            processionState = stopDomain(topology);
            break;
        case WRITE:
            LOG.debug("Topology {} added", PPrint.topology(topology));
            processionState = startDomain(topology, BD_RESTART_COUNTER);
            break;
        default:
            LOG.warn("Ignoring unhandled modification type {}", mod.getModificationType());
            break;
        }
        Futures.addCallback(processionState, new FutureCallback<Void>() {
            @Override
            public void onSuccess(@Nullable Void aVoid) {
                LOG.info("VBridge topology {} {} procession completed", PPrint.topology(topology),
                        mod.getModificationType());
            }

            @Override
            public void onFailure(@Nullable Throwable throwable) {
                LOG.warn("VBridge topology {} {} procession failed", PPrint.topology(topology),
                        mod.getModificationType());
            }
        });
    }
}

From source file:io.v.example.vbeam.vbeamexample.MainActivity.java

@Override
public ListenableFuture<Pair<String, byte[]>> createIntent(VContext context, ServerCall call) {
    String blessing = "anonymous";
    String[] names = VSecurity.getRemoteBlessingNames(ctx, call.security());
    if (names.length > 0) {
        blessing = names[0];/*from www. ja  va  2  s  .com*/
    }
    byte[] payload = ("Hello " + blessing).getBytes(Charset.forName("utf-8"));
    Intent intent = new Intent(this, GotBeamActivity.class);
    intent.setPackage(getApplicationContext().getPackageName());
    System.out.println("APP_SCHEME: " + intent.toUri(Intent.URI_ANDROID_APP_SCHEME));
    System.out.println("INTENT_SCHEME: " + intent.toUri(Intent.URI_INTENT_SCHEME));
    return Futures.immediateFuture(new Pair<>(intent.toUri(Intent.URI_INTENT_SCHEME), payload));
}

From source file:org.prebake.service.bake.ExecFn.java

public Object apply(Object[] args) {
    Iterator<String> argvIt = JsOperatingSystemEnv.stringsIn(args).iterator();
    if (!argvIt.hasNext()) {
        throw new IllegalArgumentException("No command specified");
    }// w  ww  .  j av  a2s  . co m
    final String cmd = argvIt.next();
    List<String> argv = Lists.newArrayList();
    while (argvIt.hasNext()) {
        try {
            argv.add(checker.check(argvIt.next()));
        } catch (IllegalArgumentException ex) {
            logger.log(Level.WARNING, "Possible attempt to touch client dir", ex);
            throw ex;
        }
    }
    String[] argvArr = argv.toArray(new String[argv.size()]);
    final InVmProcess ivp = InVmProcess.Lookup.forCommand(cmd);
    OsProcess p;
    if (ivp == null) {
        p = os.run(workingDir, cmd, argvArr);
    } else {
        p = new OsProcess(os, workingDir, cmd, argvArr) {
            private Future<Byte> f;
            private Path cwd;
            private String[] argv;
            private boolean combined;

            @Override
            protected void combineStdoutAndStderr() {
                combined = true;
            }

            @Override
            protected boolean hasStartedRunning() {
                return f != null;
            }

            @Override
            protected void preemptivelyKill() {
                if (f != null) {
                    f.cancel(true);
                }
                f = Futures.immediateFuture((byte) -1);
            }

            @Override
            protected void setWorkdirAndCommand(Path cwd, String cmd, String... argv) {
                this.cwd = cwd;
                this.argv = argv;
            }

            @Override
            protected Process startRunning(boolean inheritOutput, boolean closeInput, Path outFile,
                    boolean truncateOutput, Path inFile, ImmutableMap<String, String> environment,
                    boolean inheritEnvironment) {
                if (f == null) { // Not preemptively killed.
                    f = execer.submit(new Callable<Byte>() {
                        public Byte call() throws Exception {
                            return ivp.run(cwd, argv);
                        }
                    });
                }
                return new Process() {
                    @Override
                    public void destroy() {
                        if (f != null && !f.isDone()) {
                            f.cancel(true);
                        }
                    }

                    @Override
                    public int exitValue() {
                        if (!f.isDone()) {
                            throw new IllegalStateException();
                        }
                        try {
                            return waitFor();
                        } catch (InterruptedException ex) {
                            logger.log(Level.WARNING, "Aborted " + cmd, ex);
                            return -1;
                        }
                    }

                    InputStream in = new NullInputStream();
                    InputStream err = combined ? in : new NullInputStream();
                    OutputStream out = new NullOutputStream();

                    @Override
                    public InputStream getErrorStream() {
                        return err;
                    }

                    @Override
                    public InputStream getInputStream() {
                        return in;
                    }

                    @Override
                    public OutputStream getOutputStream() {
                        return out;
                    }

                    @Override
                    public int waitFor() throws InterruptedException {
                        try {
                            return f.get();
                        } catch (ExecutionException ex) {
                            logger.log(Level.WARNING, "Failed to execute " + cmd, ex);
                        }
                        return -1;
                    }
                };
            }
        };
    }
    return makeJsProcessObj(p);
}

From source file:de.dfki.kiara.Util.java

public static ClassAndConverters getSerializationTypeAndCreateConverters(java.lang.reflect.Type type) {
    if (type == null) {
        throw new NullPointerException("type");
    }/*from ww w . ja v a 2 s .  co  m*/
    boolean isFuture = futureTok.isAssignableFrom(type);
    if (!(type instanceof ParameterizedType) || !isFuture) {
        return new ClassAndConverters(TypeToken.of(type), new Function<Object, Object>() {

            @Override
            public Object apply(Object input) {
                return Futures.immediateFuture(input);
            }

        }, null);
    }

    TypeToken<?> typeToken = TypeToken.of(type);
    if (typeToken != null) {
        ClassAndConverters conv;
        synchronized (convCache) {
            conv = convCache.get(typeToken);
        }
        if (conv != null) {
            return conv;
        }
    }

    java.lang.reflect.Type paramType = ((ParameterizedType) type).getActualTypeArguments()[0];

    boolean isListenableFuture = listenableFutureTok.isAssignableFrom(type);
    Function<Object, Object> paramConverter = null;
    Function<Object, Object> serializationToParamConverter = null;
    if (!isListenableFuture) {
        // rule ListenableFuture<X> -> Future<X>
        paramConverter = new ConvertFutureToListenableFuture();
    }
    if (isFuture) {
        // rule X -> ListenableFuture<X>
        serializationToParamConverter = new ConvertTypeToListenableFuture();
    }
    while (isFuture) {
        isFuture = futureTok.isAssignableFrom(paramType);
        if (isFuture) {
            paramType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
            isListenableFuture = listenableFutureTok.isAssignableFrom(paramType);
            if (!isListenableFuture) {
                Function<Object, Object> tmp = getFutureToListenableFutureConverter();
                if (paramConverter == null) {
                    paramConverter = tmp;
                } else {
                    paramConverter = Functions.compose(tmp, paramConverter);
                }
            }
            Function<Object, Object> tmp = new ConvertTypeToListenableFuture();
            if (serializationToParamConverter == null) {
                serializationToParamConverter = tmp;
            } else {
                serializationToParamConverter = Functions.compose(tmp, serializationToParamConverter);
            }
        }
    }

    ClassAndConverters conv = new ClassAndConverters(TypeToken.of(paramType),
            paramConverter == null ? Functions.<Object>identity() : paramConverter,
            serializationToParamConverter);
    if (typeToken != null) {
        synchronized (convCache) {
            convCache.put(typeToken, conv);
        }
    }
    return conv;
}

From source file:org.thingsboard.rule.engine.metadata.TbAbstractGetAttributesNode.java

private ListenableFuture<Void> putLatestTelemetry(TbContext ctx, EntityId entityId, TbMsg msg,
        List<String> keys) {
    if (CollectionUtils.isEmpty(keys)) {
        return Futures.immediateFuture(null);
    }//from   ww w .  ja v a 2s  .  c o  m
    ListenableFuture<List<TsKvEntry>> latest = ctx.getTimeseriesService().findLatest(ctx.getTenantId(),
            entityId, keys);
    return Futures.transform(latest, l -> {
        l.forEach(r -> {
            if (r.getValue() != null) {
                msg.getMetaData().putValue(r.getKey(), r.getValueAsString());
            } else {
                throw new RuntimeException("[" + r.getKey() + "] telemetry value is not present in the DB!");
            }
        });
        return null;
    });
}

From source file:org.pentaho.di.trans.dataservice.optimization.pushdown.ParameterPushdown.java

@Override
public ListenableFuture<Boolean> activate(DataServiceExecutor executor, PushDownOptimizationMeta meta) {
    Map<String, String> parameterValues = captureParameterValues(executor.getSql());

    executor.getParameters().putAll(parameterValues);
    return Futures.immediateFuture(!parameterValues.isEmpty());
}