Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

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

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:org.opendaylight.l2switch.hosttracker.plugin.internal.HostTrackerImpl.java

public void packetReceived(Addresses addrs, InstanceIdentifier<?> ii) {
    InstanceIdentifier<NodeConnector> iinc = ii.firstIdentifierOf(NodeConnector.class);
    InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> iin//
            = ii.firstIdentifierOf(//from  w w  w.  ja va2s  .c o  m
                    org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class);

    ListenableFuture<Optional<NodeConnector>> futureNodeConnector;
    ListenableFuture<Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node>> futureNode;
    try (ReadOnlyTransaction readTx = dataService.newReadOnlyTransaction()) {
        futureNodeConnector = readTx.read(LogicalDatastoreType.OPERATIONAL, iinc);
        futureNode = readTx.read(LogicalDatastoreType.OPERATIONAL, iin);
        readTx.close();
    }
    Optional<NodeConnector> opNodeConnector = null;
    Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> opNode = null;
    try {
        opNodeConnector = futureNodeConnector.get();
        opNode = futureNode.get();
    } catch (ExecutionException | InterruptedException ex) {
        log.warn(ex.getLocalizedMessage());
    }
    if (opNode != null && opNode.isPresent() && opNodeConnector != null && opNodeConnector.isPresent()) {
        processHost(opNode.get(), opNodeConnector.get(), addrs);
    }
}

From source file:com.facebook.buck.distributed.build_client.BuildPhase.java

@Nonnull
private Set<String> checkForRuleKeyMismatches(DistLocalBuildMode distLocalBuildMode,
        ListenableFuture<List<Pair<BuildRule, RuleKey>>> ruleKeyPairsFutureFuture)
        throws ExecutionException, InterruptedException {
    Set<String> mismatchingBuildTargets = new HashSet<>();
    if (!distLocalBuildMode.equals(DistLocalBuildMode.RULE_KEY_DIVERGENCE_CHECK)) {
        return mismatchingBuildTargets;
    }/*from ww w  .ja v a 2s  .  c  o m*/
    List<Pair<BuildRule, RuleKey>> localRuleKeyPairs = ruleKeyPairsFutureFuture.get();
    List<RuleKeyCalculatedEvent> remoteRuleKeys = buildRuleEventManager.getRuleKeyCalculatedEvents();

    Map<String, String> localRulesToKeys = new HashMap<>();

    for (Pair<BuildRule, RuleKey> localRuleKeyPair : localRuleKeyPairs) {
        localRulesToKeys.put(localRuleKeyPair.getFirst().getFullyQualifiedName(),
                localRuleKeyPair.getSecond().getHashCode().toString());
    }

    Set<String> remoteBuildTargets = new HashSet<>();
    for (RuleKeyCalculatedEvent remoteRuleAndKey : remoteRuleKeys) {
        String remoteBuildTarget = remoteRuleAndKey.getBuildTarget();
        remoteBuildTargets.add(remoteBuildTarget);
        if (localRulesToKeys.containsKey(remoteBuildTarget)
                && !localRulesToKeys.get(remoteBuildTarget).equals(remoteRuleAndKey.getDefaultRuleKey())) {
            LOG.warn("Rule key for [%s] mismatched locally and remotely. Local [%s]. Remote [%s]",
                    remoteBuildTarget, localRulesToKeys.containsKey(remoteBuildTarget),
                    remoteRuleAndKey.getDefaultRuleKey());
            mismatchingBuildTargets.add(remoteBuildTarget);
        }
    }

    SetView<String> buildTargetsOnlyBuildInOneLocation = Sets.symmetricDifference(localRulesToKeys.keySet(),
            remoteBuildTargets);
    for (String buildTarget : buildTargetsOnlyBuildInOneLocation) {
        LOG.warn("Rule [%s] was only built in one location", buildTarget);
        mismatchingBuildTargets.add(buildTarget);
    }

    return mismatchingBuildTargets;
}

From source file:org.waveprotocol.box.server.waveserver.DeltaWaveletStateMap.java

public DeltaWaveletStateAccessor get(final WaveletName waveletName) {
    return new DeltaWaveletStateAccessor() {

        @Override/*from   w w  w . ja v  a 2s .c  om*/
        public DeltaWaveletState get() throws WaveletStateException {
            return getState(states.getUnchecked(waveletName));
        }

        @Override
        public DeltaWaveletState getIfPresent() throws WaveletStateException {
            ListenableFuture<DeltaWaveletState> future = states.getIfPresent(waveletName);
            if (future == null) {
                return null;
            }
            return getState(future);
        }

        @Override
        public ListenableFuture close() {
            states.invalidate(waveletName);
            ListenableFuture future = closingStates.remove(waveletName);
            if (future == null) {
                SettableFuture existingFuture = SettableFuture.create();
                existingFuture.set(null);
                future = existingFuture;
            }
            return future;
        }

        private DeltaWaveletState getState(ListenableFuture<DeltaWaveletState> future)
                throws WaveletStateException {
            try {
                return future.get();
            } catch (InterruptedException | ExecutionException ex) {
                throw new WaveletStateException(ex);
            }
        }
    };
}

From source file:org.opendaylight.nemo.user.tenantmanager.TenantManage.java

/**
 *
 * @return null if an error was encountered, or an empty map if there was no
 *         error but no data was retrieved.
 */// w  ww. j a  v  a2 s .  c  o  m
public Map<UserRoleName, UserRole> getUserRoles() {

    InstanceIdentifier<UserRoles> userRolesInsId = InstanceIdentifier.builder(UserRoles.class).build();
    ListenableFuture<Optional<UserRoles>> userRolesFuture = this.dataBroker.newReadOnlyTransaction()
            .read(LogicalDatastoreType.CONFIGURATION, userRolesInsId);

    final Optional<UserRoles> userRolesOpt;
    try {
        // TODO: consider time out here?
        userRolesOpt = userRolesFuture.get();
    } catch (InterruptedException e) {
        LOG.error("Cannot read role information.", e);
        return null;
    } catch (ExecutionException e) {
        LOG.error("Cannot read role information.", e);
        return null;
    }

    // TODO: change to Java 8 lambda expressions
    return userRolesOpt.transform(new Function<UserRoles, Map<UserRoleName, UserRole>>() {
        @Override
        public Map<UserRoleName, UserRole> apply(UserRoles input) {
            return Maps.uniqueIndex(input.getUserRole(), new Function<UserRole, UserRoleName>() {
                @Override
                public UserRoleName apply(UserRole role) {
                    return role.getRoleName();
                }
            });
        }
    }).or(new HashMap<UserRoleName, UserRole>());
}

From source file:org.opendaylight.alto.altohosttracker.plugin.internal.AltoHostTrackerImpl.java

public void readTest() {
    InstanceIdentifier<Resources> resources = InstanceIdentifier.builder(Resources.class).build();
    ListenableFuture<Optional<Resources>> futureResources;
    try (ReadOnlyTransaction readTx = dataService.newReadOnlyTransaction()) {
        futureResources = readTx.read(LogicalDatastoreType.OPERATIONAL, resources);
        readTx.close();/*from w  w  w.  java 2s  . co m*/
    }
    Optional<Resources> opNodes = null;
    try {
        opNodes = futureResources.get();
    } catch (ExecutionException | InterruptedException ex) {
        log.warn(ex.getLocalizedMessage());
    }
    if (opNodes != null && opNodes.isPresent())
        log.info("resources:" + opNodes.get());
}

From source file:me.lucko.luckperms.bukkit.migration.MigrationPowerfulPerms.java

private CommandResult run(LuckPermsPlugin plugin, Sender sender, List<String> args) {
    ProgressLogger log = new ProgressLogger("PowerfulPerms");
    log.addListener(plugin.getConsoleSender());
    log.addListener(sender);// w  w w  .java  2s  .  c o  m

    log.log("Starting.");

    if (!Bukkit.getPluginManager().isPluginEnabled("PowerfulPerms")) {
        log.logErr("PowerfulPerms is not loaded.");
        return CommandResult.STATE_ERROR;
    }

    final String address = args.get(0);
    final String database = args.get(1);
    final String username = args.get(2);
    final String password = args.get(3);
    final String dbTable = args.get(4);

    // Find a list of UUIDs
    log.log("Getting a list of UUIDs to migrate.");
    Set<UUID> uuids = new HashSet<>();

    try (HikariDataSource hikari = new HikariDataSource()) {
        hikari.setMaximumPoolSize(2);
        hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
        hikari.addDataSourceProperty("serverName", address.split(":")[0]);
        hikari.addDataSourceProperty("port", address.split(":")[1]);
        hikari.addDataSourceProperty("databaseName", database);
        hikari.addDataSourceProperty("user", username);
        hikari.addDataSourceProperty("password", password);

        try (Connection c = hikari.getConnection()) {
            DatabaseMetaData meta = c.getMetaData();

            try (ResultSet rs = meta.getTables(null, null, dbTable, null)) {
                if (!rs.next()) {
                    log.log("Error - Couldn't find table.");
                    return CommandResult.FAILURE;
                }
            }
        }

        try (Connection c = hikari.getConnection()) {
            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT COLUMN_NAME, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?")) {
                ps.setString(1, dbTable);

                try (ResultSet rs = ps.executeQuery()) {
                    log.log("Found table: " + dbTable);
                    while (rs.next()) {
                        log.log("" + rs.getString("COLUMN_NAME") + " - " + rs.getString("COLUMN_TYPE"));
                    }
                }
            }

            try (PreparedStatement ps = c.prepareStatement("SELECT `uuid` FROM " + dbTable)) {
                try (ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        uuids.add(UUID.fromString(rs.getString("uuid")));
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (uuids.isEmpty()) {
        log.logErr("Unable to find any UUIDs to migrate.");
        return CommandResult.FAILURE;
    }

    log.log("Found " + uuids.size() + " uuids. Starting migration.");

    PowerfulPermsPlugin ppPlugin = (PowerfulPermsPlugin) Bukkit.getPluginManager().getPlugin("PowerfulPerms");
    PermissionManager pm = ppPlugin.getPermissionManager();

    // Groups first.
    log.log("Starting group migration.");
    AtomicInteger groupCount = new AtomicInteger(0);
    Map<Integer, Group> groups = pm.getGroups(); // All versions
    for (Group g : groups.values()) {
        plugin.getStorage().createAndLoadGroup(g.getName().toLowerCase(), CreationCause.INTERNAL).join();
        final me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager()
                .getIfLoaded(g.getName().toLowerCase());

        for (Permission p : g.getOwnPermissions()) { // All versions
            applyPerm(group, p, log);
        }

        for (Group parent : g.getParents()) { // All versions
            try {
                group.setPermission("group." + parent.getName().toLowerCase(), true);
            } catch (Exception ex) {
                log.handleException(ex);
            }
        }

        plugin.getStorage().saveGroup(group);
        log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
    }
    log.log("Migrated " + groupCount.get() + " groups");

    // Now users.
    log.log("Starting user migration.");
    final Map<UUID, CountDownLatch> progress = new HashMap<>();

    // Migrate all users and their groups
    for (UUID uuid : uuids) {
        progress.put(uuid, new CountDownLatch(2));

        // Create a LuckPerms user for the UUID
        plugin.getStorage().loadUser(uuid, "null").join();
        User user = plugin.getUserManager().get(uuid);

        // Get a list of Permissions held by the user from the PP API.
        getPlayerPermissions(pm, uuid, perms -> { // Changes each version
            perms.forEach(p -> applyPerm(user, p, log));

            // Update the progress so the user can be saved and unloaded.
            synchronized (progress) {
                progress.get(uuid).countDown();
                if (progress.get(uuid).getCount() == 0) {
                    plugin.getStorage().saveUser(user);
                    plugin.getUserManager().cleanup(user);
                }
            }
        });

        // Migrate the user's groups to LuckPerms from PP.
        Consumer<Map<String, List<CachedGroup>>> callback = groups1 -> {
            for (Map.Entry<String, List<CachedGroup>> e : groups1.entrySet()) {
                final String server;
                if (e.getKey() != null && (e.getKey().equals("") || e.getKey().equalsIgnoreCase("all"))) {
                    server = null;
                } else {
                    server = e.getKey();
                }

                if (superLegacy) {
                    e.getValue().stream().filter(cg -> !cg.isNegated()).map(cg -> {
                        try {
                            return (Group) getGroupMethod.invoke(cg);
                        } catch (IllegalAccessException | InvocationTargetException e1) {
                            e1.printStackTrace();
                            return null;
                        }
                    }).forEach(g -> {
                        if (g != null) {
                            if (server == null) {
                                try {
                                    user.setPermission("group." + g.getName().toLowerCase(), true);
                                } catch (Exception ex) {
                                    log.handleException(ex);
                                }
                            } else {
                                try {
                                    user.setPermission("group." + g.getName().toLowerCase(), true, server);
                                } catch (Exception ex) {
                                    log.handleException(ex);
                                }
                            }
                        }
                    });
                } else {
                    e.getValue().stream().filter(g -> !g.hasExpired() && !g.isNegated()).forEach(g -> {
                        final Group group = pm.getGroup(g.getGroupId());
                        if (g.willExpire()) {
                            if (server == null) {
                                try {
                                    user.setPermission("group." + group.getName().toLowerCase(), true,
                                            g.getExpirationDate().getTime() / 1000L);
                                } catch (Exception ex) {
                                    log.handleException(ex);
                                }
                            } else {
                                try {
                                    user.setPermission("group." + group.getName().toLowerCase(), true, server,
                                            g.getExpirationDate().getTime() / 1000L);
                                } catch (Exception ex) {
                                    log.handleException(ex);
                                }
                            }

                        } else {
                            if (server == null) {
                                try {
                                    user.setPermission("group." + group.getName().toLowerCase(), true);
                                } catch (Exception ex) {
                                    log.handleException(ex);
                                }
                            } else {
                                try {
                                    user.setPermission("group." + group.getName().toLowerCase(), true, server);
                                } catch (Exception ex) {
                                    log.handleException(ex);
                                }
                            }
                        }
                    });
                }
            }

            // Update the progress so the user can be saved and unloaded.
            synchronized (progress) {
                progress.get(uuid).countDown();
                if (progress.get(uuid).getCount() == 0) {
                    plugin.getStorage().saveUser(user);
                    plugin.getUserManager().cleanup(user);
                }
            }
        };

        if (!legacy) {
            try {
                ListenableFuture<LinkedHashMap<String, List<CachedGroup>>> future = (ListenableFuture<LinkedHashMap<String, List<CachedGroup>>>) getPlayerGroupsMethod
                        .invoke(pm, uuid);
                try {
                    if (future.isDone()) {
                        callback.accept(future.get());
                    } else {
                        future.addListener(() -> {
                            try {
                                callback.accept(future.get());
                            } catch (InterruptedException | ExecutionException e) {
                                e.printStackTrace();
                            }
                        }, Runnable::run);
                    }
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            try {
                getPlayerGroupsMethod.invoke(pm, uuid,
                        new LPResultRunnable<LinkedHashMap<String, List<CachedGroup>>>() {
                            @Override
                            public void run() {
                                callback.accept(getResult());
                            }
                        });
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    // All groups are migrated, but there may still be some users being migrated.
    // This block will wait for all users to be completed.
    log.log("Waiting for user migration to complete. This may take some time");
    boolean sleep = true;
    while (sleep) {
        sleep = false;

        for (Map.Entry<UUID, CountDownLatch> e : progress.entrySet()) {
            if (e.getValue().getCount() != 0) {
                sleep = true;
                break;
            }
        }

        if (sleep) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    // We done.
    log.log("Success! Migration complete.");
    return CommandResult.SUCCESS;
}

From source file:io.geobit.chain.dispatchers.BalanceAndReceivedDispatcher.java

public Long getBalance(String address, int cont) {
    if (cont > 5)
        return null;
    Long valCache = recentCache.getIfPresent("b/" + address);
    if (valCache != null)
        return valCache;
    valCache = cache.getIfPresent("b/" + address);
    BalanceProvider bal1 = balanceProviders.take();
    BalanceProvider bal2 = balanceProviders.takeDifferent(bal1);
    log("bal1=" + bal1 + " bal2=" + bal2);
    Callable<Long> runner1 = new BalanceRunnable(bal1, address);
    Callable<Long> runner2 = new BalanceRunnable(bal2, address);
    final Long start = System.currentTimeMillis();
    ListenableFuture<Long> listenableFuture1 = moreExecutor.submit(runner1);
    ListenableFuture<Long> listenableFuture2 = moreExecutor.submit(runner2);
    SettableFuture<Long> returned = SettableFuture.create();
    Futures.addCallback(listenableFuture1, new BalanceFutureCallback(start, bal1, returned, balanceProviders));
    Futures.addCallback(listenableFuture2, new BalanceFutureCallback(start, bal2, returned, balanceProviders));
    Runnable checker = new BalanceCheckRunnable(address, listenableFuture1, bal1, listenableFuture2, bal2,
            balanceProviders, cache);//www.j a v a 2  s  .c  o  m
    moreExecutor.execute(checker);
    try {
        Long valRet = returned.get();
        if (valCache != null && valCache.equals(valRet)) {
            recentCache.put("b/" + address, valRet);
            return valRet;
        }

        Long first = listenableFuture1.get();
        Long second = listenableFuture2.get();
        if (first != null && first.equals(second)) {
            cache.put("b/" + address, first);
            recentCache.put("b/" + address, first);
            return first;
        }
    } catch (Exception e) {
        error("BalanceAndReceivedDispatcher getReceived " + e.getMessage());
    }
    /*waiting?*/
    return getBalance(address, cont + 1);
}

From source file:io.geobit.chain.dispatchers.AddressTransactionsDispatcher.java

public AddressTransactions getAddressUnspents(String address, int cont) {
    if (cont > 5)
        return null;
    AddressTransactions valCache = cache.getIfPresent("u/" + address);
    AddressUnspentsProvider aup1 = addUnsProviders.take();
    AddressUnspentsProvider aup2 = addUnsProviders.takeDifferent(aup1);
    log("aup1=" + aup1 + " aup2=" + aup2);
    Callable<AddressTransactions> runner1 = new AddressUnspentsRunnable(aup1, address);
    Callable<AddressTransactions> runner2 = new AddressUnspentsRunnable(aup2, address);
    final Long start = System.currentTimeMillis();
    ListenableFuture<AddressTransactions> listenableFuture1 = moreExecutor.submit(runner1);
    ListenableFuture<AddressTransactions> listenableFuture2 = moreExecutor.submit(runner2);
    SettableFuture<AddressTransactions> returned = SettableFuture.create();
    Futures.addCallback(listenableFuture1,
            new AddressUnspentsFutureCallback(start, aup1, returned, addUnsProviders));
    Futures.addCallback(listenableFuture2,
            new AddressUnspentsFutureCallback(start, aup2, returned, addUnsProviders));
    Runnable checker = new AddressUnspentsCheckRunnable(address, listenableFuture1, aup1, listenableFuture2,
            aup2, addUnsProviders, cache);
    moreExecutor.execute(checker);//from www .  j a  va2 s  . c  o  m
    try {
        AddressTransactions valRet = returned.get();
        if (valCache != null && valCache.equals(valRet))
            return valRet;

        AddressTransactions first = listenableFuture1.get();
        AddressTransactions second = listenableFuture2.get();
        if (first != null && first.equals(second)) {
            cache.put("u/" + address, first);
            return first;
        }
    } catch (Exception e) {
    }
    return getAddressUnspents(address, cont + 1);
}

From source file:org.opendaylight.nemo.user.vnspacemanager.structurestyle.updateintent.GetDefinitions.java

private void fetchConditionParaDefinitions() {
    InstanceIdentifier<ConditionParameterDefinitions> conditionparadefinitionId = InstanceIdentifier
            .builder(ConditionParameterDefinitions.class).build();
    ListenableFuture<Optional<ConditionParameterDefinitions>> conditionparadefinitionFuture = dataBroker
            .newReadOnlyTransaction().read(LogicalDatastoreType.CONFIGURATION, conditionparadefinitionId);
    Futures.addCallback(conditionparadefinitionFuture,
            new FutureCallback<Optional<ConditionParameterDefinitions>>() {
                @Override//w ww .j  av  a  2s .co  m
                public void onSuccess(Optional<ConditionParameterDefinitions> result) {
                    setConditionParameterDefinitionList(result.get().getConditionParameterDefinition());
                }

                @Override
                public void onFailure(Throwable t) {
                    LOG.error("Can not read condition parameter definition information.", t);
                }
            });
    try {
        conditionparadefinitionFuture.get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        LOG.error("Exception:", e);
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        LOG.error("Exception:", e);
    }
    return;
}

From source file:co.cask.cdap.explore.jdbc.ExploreDatabaseMetaData.java

private ResultSet getMetadataResultSet(ListenableFuture<ExploreExecutionResult> future) throws SQLException {
    try {//w w  w  .j a  v  a 2 s. co m
        return new ExploreResultSet(future.get(), RESULT_FETCH_SIZE);
    } catch (InterruptedException e) {
        LOG.error("Caught exception", e);
        Thread.currentThread().interrupt();
        throw Throwables.propagate(e);
    } catch (ExecutionException e) {
        LOG.error("Error executing query", e);
        throw new SQLException(e);
    } catch (CancellationException e) {
        // If futureResults has been cancelled
        LOG.error("Execution has been cancelled.", e);
        throw new SQLException(e);
    }
}