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:io.crate.jobs.JobContextService.java

/**
 * kills all contexts which are active at the time of the call of this method.
 *
 * @return a future holding the number of contexts kill was called on, the future is finished when all contexts
 * are completed and never fails.//from  w  w w.  j ava 2 s . co m
 */
public ListenableFuture<Integer> killAll() {
    long now = System.nanoTime();
    for (KillAllListener killAllListener : killAllListeners) {
        try {
            killAllListener.killAllJobs(now);
        } catch (Throwable t) {
            logger.error("Failed to call killAllJobs on listener {}", t, killAllListener);
        }
    }
    Collection<UUID> toKill = ImmutableList.copyOf(activeContexts.keySet());
    if (toKill.isEmpty()) {
        return Futures.immediateFuture(0);
    }
    return killContexts(toKill);
}

From source file:producerstest.SimpleProducerModule.java

@Produces
@IntoSet/*from   w  ww  .j  ava 2  s .c o  m*/
@SuppressWarnings("unused") // unthrown exception for test, unused parameter for test
static ListenableFuture<String> setOfStrFutureElementWithArgThrowingException(int i) throws IOException {
    return Futures.immediateFuture("set of str element with arg throwing exception");
}

From source file:utils.teamcity.wallt.controller.api.ApiController.java

@Override
public ListenableFuture<Void> loadBuildTypeList() {
    if (!getApiVersion().isSupported(ApiFeature.BUILD_TYPE_STATUS))
        return Futures.immediateFuture(null);

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

    runInWorkerThread(() -> {/*from  w  w w  . j  av  a 2 s  .c  o  m*/
        final ListenableFuture<BuildTypeList> buildListFuture = _apiRequestController
                .sendRequest(getApiVersion(), "buildTypes", BuildTypeList.class);
        addCallback(buildListFuture, new FutureCallback<BuildTypeList>() {
            @Override
            public void onSuccess(final BuildTypeList result) {
                final List<BuildTypeData> buildTypes = result.getBuildTypes().stream()
                        .map((btype) -> _buildTypeProvider.get(getApiVersion()).apply(btype))
                        .collect(Collectors.toList());
                _buildManager.registerBuildTypes(buildTypes);
                _eventBus.post(_buildManager);

                for (final BuildTypeData buildType : _buildManager.getBuildTypes()) {
                    final Optional<ProjectData> project = _projectManager.getProject(buildType.getProjectId());
                    if (project.isPresent()) {
                        project.get().registerBuildType(buildType);
                        _eventBus.post(project.get());
                    }
                    LOGGER.info("Discovering build type " + buildType.getId() + " (" + buildType.getName()
                            + ") on project " + buildType.getProjectId() + " (" + buildType.getProjectName()
                            + ")");
                }

                ackFuture.set(null);
            }

            @Override
            public void onFailure(final Throwable t) {
                LOGGER.error("Error during loading build type list:", t);
                ackFuture.setException(t);
            }
        });
    });

    return ackFuture;
}

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

public ListenableFuture<Path.Capture> loadCapture(String path) {
    LOG.log(FINE, "RPC->loadCapture({0})", path);
    return Futures.transformAsync(client.loadCapture(LoadCaptureRequest.newBuilder().setPath(path).build()),
            in -> Futures.immediateFuture(throwIfError(in.getCapture(), in.getError())));
}

From source file:org.opendaylight.controller.clustering.it.provider.CarProvider.java

@Override
public Future<RpcResult<Void>> stressTest(StressTestInput input) {
    final int inputRate;
    final long inputCount;

    // If rate is not provided, or given as zero, then just return.
    if ((input.getRate() == null) || (input.getRate() == 0)) {
        log.info("Exiting stress test as no rate is given.");
        return Futures.immediateFuture(
                RpcResultBuilder.<Void>failed().withError(ErrorType.PROTOCOL, "invalid rate").build());
    } else {/*from w  w  w  .  j  a v  a 2 s  .com*/
        inputRate = input.getRate();
    }

    if (input.getCount() != null) {
        inputCount = input.getCount();
    } else {
        inputCount = 0;
    }

    log.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);

    stopThread();
    // clear counters
    succcessCounter.set(0);
    failureCounter.set(0);

    WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
    InstanceIdentifier<Cars> carsId = InstanceIdentifier.<Cars>builder(Cars.class).build();
    tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
    try {
        tx.submit().checkedGet(5, TimeUnit.SECONDS);
    } catch (TransactionCommitFailedException | TimeoutException e) {
        log.error("Put Cars failed", e);
        return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
    }

    stopThread = false;
    final long sleep = TimeUnit.NANOSECONDS.convert(1000, TimeUnit.MILLISECONDS) / inputRate;
    final Stopwatch sw = Stopwatch.createUnstarted();
    testThread = new Thread() {
        @Override
        public void run() {
            sw.start();
            AtomicLong count = new AtomicLong();
            while (!stopThread) {
                long id = count.incrementAndGet();
                WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
                CarEntry car = new CarEntryBuilder().setId(new CarId("car" + id)).build();
                tx.put(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.<Cars>builder(Cars.class)
                        .child(CarEntry.class, car.getKey()).build(), car);
                CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
                Futures.addCallback(future, new FutureCallback<Void>() {

                    @Override
                    public void onSuccess(final Void result) {
                        // Transaction succeeded
                        succcessCounter.getAndIncrement();
                    }

                    @Override
                    public void onFailure(final Throwable t) {
                        // Transaction failed
                        failureCounter.getAndIncrement();
                        LOG.error("Put Cars failed", t);
                    }
                });
                try {
                    TimeUnit.NANOSECONDS.sleep(sleep);
                } catch (InterruptedException e) {
                    break;
                }

                if ((count.get() % 1000) == 0) {
                    log.info("Cars created {}, time: {}", count.get(), sw.elapsed(TimeUnit.SECONDS));
                }

                // Check if a count is specified in input and we have created that many cars.
                if ((inputCount != 0) && (count.get() >= inputCount)) {
                    stopThread = true;
                }
            }

            log.info("Stress test thread stopping after creating {} cars.", count.get());
        }
    };
    testThread.start();

    return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
}

From source file:io.v.android.apps.reader.db.FakeDB.java

@Override
public ListenableFuture<Void> onInitialized() {
    return Futures.immediateFuture(null);
}

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

@Override
public <T> Future<Set<T>> putAll(Map<T, ?> values, Expiration expires, SetPolicy policy) {
    return Futures.immediateFuture(memcacheService.putAll(values, expires, policy));
}

From source file:org.opendaylight.vpnservice.itm.rpc.ItmManagerRpcService.java

@Override
public Future<RpcResult<GetTunnelInterfaceNameOutput>> getTunnelInterfaceName(
        GetTunnelInterfaceNameInput input) {
    RpcResultBuilder<GetTunnelInterfaceNameOutput> resultBld = null;
    BigInteger sourceDpn = input.getSourceDpid();
    BigInteger destinationDpn = input.getDestinationDpid();
    InstanceIdentifier<InternalTunnel> path = InstanceIdentifier.create(TunnelList.class).child(
            InternalTunnel.class, new InternalTunnelKey(destinationDpn, sourceDpn, input.getTunnelType()));

    Optional<InternalTunnel> tnl = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);

    if (tnl != null && tnl.isPresent()) {
        InternalTunnel tunnel = tnl.get();
        GetTunnelInterfaceNameOutputBuilder output = new GetTunnelInterfaceNameOutputBuilder();
        output.setInterfaceName(tunnel.getTunnelInterfaceName());
        resultBld = RpcResultBuilder.success();
        resultBld.withResult(output.build());
    } else {/*from  w  ww  .  ja v  a 2s  .c  om*/
        resultBld = RpcResultBuilder.failed();
    }

    return Futures.immediateFuture(resultBld.build());
}

From source file:org.cloudifysource.rest.events.cache.EventsCacheLoader.java

@Override
public ListenableFuture<EventsCacheValue> reload(final EventsCacheKey key, final EventsCacheValue oldValue)
        throws Exception {

    logger.fine(EventsUtils.getThreadId() + "Reloading events cache entry for key " + key);

    // pickup any new containers along with the old ones
    Set<GridServiceContainer> containersForDeployment = new HashSet<GridServiceContainer>();

    containersForDeployment.addAll(containerProvider.getContainersForDeployment(key.getDeploymentId()));

    if (containersForDeployment.isEmpty()) {
        // get containers by the deployment id
        containersForDeployment = containerProvider.getContainersForDeployment(key.getDeploymentId());
    }//from w ww .j  a v a  2 s . c  o  m
    if (!containersForDeployment.isEmpty()) {
        int index = oldValue.getLastEventIndex() + 1;
        for (GridServiceContainer container : containersForDeployment) {

            // this will give us just the new logs.
            LogEntryMatcherProviderKey logEntryMatcherProviderKey = createKey(container, key);
            LogEntryMatcher matcher = matcherProvider.get(logEntryMatcherProviderKey);
            LogEntries logEntries = container.logEntries(matcher);

            for (LogEntry logEntry : logEntries) {
                if (logEntry.isLog()) {
                    DeploymentEvent event = EventsUtils.logToEvent(logEntry, logEntries.getHostName(),
                            logEntries.getHostAddress());
                    event.setIndex(index++);
                    oldValue.getEvents().getEvents().add(event);
                }
            }
        }

        // update refresh time.
        oldValue.setLastRefreshedTimestamp(System.currentTimeMillis());
        oldValue.setLastEventIndex(index - 1);
    }
    return Futures.immediateFuture(oldValue);
}

From source file:ch.vorburger.osgi.builder.internal.SourceInstallServiceImpl.java

@Override
public ListenableFuture<Bundle> installSourceBundle(File projectDirectoryOrBundleJAR) {
    SettableFuture<Bundle> installFuture = SettableFuture.create();
    BuildServiceSingleFileOutputListener listener = singleProducedFile -> {
        try (InputStream inputStream = new FileInputStream(singleProducedFile)) {
            String location = getBundleLocation(projectDirectoryOrBundleJAR);
            Bundle bundle = bundleContext.getBundle(location);
            if (bundle == null) {
                LOG.info("Installing Bundle from {}", location);
                bundle = bundleContext.installBundle(location, inputStream);
                bundle.start();/*w w w. j  ava  2s  . co m*/
            } else {
                LOG.info("Updating Bundle from {}", location);
                bundle.update(inputStream);
                // We (possibly "re")-start here, because it's possible that
                // an initial (or previous) start() failed due to some bug in the bundle
                // and that could have meanwhile be fixed, but OSGi won't re-try starting
                // a bundle an update if we don't tell it to...
                bundle.start();
            }
            installFuture.set(bundle);
        } catch (BundleException | IOException e) {
            LOG.error("Problem reading/installing bundle JAR: {}", singleProducedFile, e);
            installFuture.setException(e);
        }
    };

    ListenableFuture<Void> buildFuture;
    if (new File(projectDirectoryOrBundleJAR, "pom.xml").exists()) {
        LOG.info("Found a POM in directory, will continously build with Maven: {}",
                projectDirectoryOrBundleJAR);
        buildFuture = mavenBuildService.buildContinously(projectDirectoryOrBundleJAR, "install", listener);
    } else if (projectDirectoryOrBundleJAR.isDirectory()) {
        LOG.info("Found directory (but no POM), will continously build with Gradle: {}",
                projectDirectoryOrBundleJAR);
        buildFuture = gradleBuildService.buildContinously(projectDirectoryOrBundleJAR, "build", listener);
    } else if (projectDirectoryOrBundleJAR.isFile() && projectDirectoryOrBundleJAR.getName().endsWith(".jar")) {
        LOG.info("Found JAR, will install and update on update: {}", projectDirectoryOrBundleJAR);
        // The JAR is already ready now, and can be started by caller:
        try {
            // NB: The default quietPeriod of 100ms is often not enough while Gradle updates the JAR and leads to ZipException, so 500ms:
            bundleFileWatcher = new FileWatcherBuilder().path(projectDirectoryOrBundleJAR).quietPeriodInMS(500)
                    .listener((path, changeKind) -> {
                        switch (changeKind) {
                        case MODIFIED:
                            // NB: FileWatcherBuilder invoked the listener once on start, and then on subsequent changes
                            listener.buildSucceeded(projectDirectoryOrBundleJAR);
                            break;

                        case DELETED:
                            String location = getBundleLocation(projectDirectoryOrBundleJAR);
                            LOG.info("Uninstalling Bundle from {}", location);
                            bundleContext.getBundle(location).uninstall();
                            break;

                        default:
                            LOG.error("Unsupported file watcher change kind, ignored: {}", changeKind);
                            break;
                        }

                        System.out.println(changeKind.name() + " " + path.toString());
                    }).build();
            buildFuture = Futures.immediateFuture(null);
        } catch (IOException e) {
            buildFuture = Futures.immediateFailedFuture(e);
        }
        // But we make sure than upon changes it gets reloaded:
        // TODO!!!!
    } else {
        buildFuture = Futures.immediateFailedFuture(
                new IllegalArgumentException("Neither a directory (with or w.o. pom.xml) nor a JAR, "
                        + "how I am supposed to (build and) install this as an OSGi bundle: "
                        + projectDirectoryOrBundleJAR));
    }

    Futures.addCallback(buildFuture, new FutureCallback<Void>() {

        @Override
        public void onFailure(Throwable throwable) {
            // If this happens, then the listener above will never get invoked
            // because the (first, as it's continous) build failed before, so:
            installFuture.setException(throwable);
        }

        @Override
        public void onSuccess(Void nothing) {
        }
    });
    return installFuture;
}