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.ovsdb.plugin.impl.ConfigurationServiceImpl.java

@Override
public Row<GenericTableSchema> updateRow(Node node, String databaseName, String tableName, UUID rowUuid,
        Row<GenericTableSchema> row, boolean overwrite) {
    Connection connection = connectionService.getConnection(node);
    OvsdbClient client = connection.getClient();

    LOGGER.debug("updateRow : Connection : {} databaseName : {} tableName : {} rowUUID : {} row : {}",
            client.getConnectionInfo(), databaseName, tableName, rowUuid, row.toString());
    try {/*from   w w  w.  j av  a 2  s  . c  om*/
        DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
        TransactionBuilder transactionBuilder = client.transactBuilder(dbSchema);
        TableSchema<GenericTableSchema> tableSchema = dbSchema.table(tableName, GenericTableSchema.class);
        ColumnSchema<GenericTableSchema, UUID> uuid = tableSchema.column("_uuid", UUID.class);
        transactionBuilder.add(op.update(tableSchema, row).where(uuid.opEqual(rowUuid)).build());

        ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
        List<OperationResult> operationResults = results.get();
        for (OperationResult result : operationResults) {
            if (result.getError() != null) {
                throw new OvsdbPluginException(
                        "Error updating row : " + result.getError() + " Details: " + result.getDetails());
            }
        }
        if (operationResults.isEmpty()
                || (transactionBuilder.getOperations().size() != operationResults.size())) {
            throw new OvsdbPluginException("Failed to update row. Please check OVS logs for more info.");
        }

        return this.getRow(node, databaseName, tableName, rowUuid);
    } catch (Exception e) {
        throw new OvsdbPluginException("Error updating row due to an exception " + e.getMessage());
    }
}

From source file:org.apache.twill.internal.ZKServiceDecorator.java

@Override
protected void doStart() {
    callbackExecutor = Executors.newSingleThreadExecutor(Threads.createDaemonThreadFactory("message-callback"));
    // Create the live node, if succeeded, start the decorated service, otherwise fail out.
    Futures.addCallback(createLiveNode(), new FutureCallback<String>() {
        @Override/*from w  w w  . j  a  v a2  s.c  om*/
        public void onSuccess(String result) {
            // Create nodes for states and messaging
            StateNode stateNode = new StateNode(ServiceController.State.STARTING);

            final ListenableFuture<List<String>> createFuture = Futures.allAsList(
                    ZKOperations.ignoreError(
                            zkClient.create(getZKPath("messages"), null, CreateMode.PERSISTENT),
                            KeeperException.NodeExistsException.class, null),
                    zkClient.create(getZKPath("state"), encodeStateNode(stateNode), CreateMode.PERSISTENT));

            createFuture.addListener(new Runnable() {
                @Override
                public void run() {
                    try {
                        createFuture.get();
                        // Starts the decorated service
                        decoratedService.addListener(createListener(), Threads.SAME_THREAD_EXECUTOR);
                        decoratedService.start();
                    } catch (Exception e) {
                        notifyFailed(e);
                    }
                }
            }, Threads.SAME_THREAD_EXECUTOR);
        }

        @Override
        public void onFailure(Throwable t) {
            notifyFailed(t);
        }
    });

    // Watch for session expiration, recreate the live node if reconnected after expiration.
    zkClient.addConnectionWatcher(new Watcher() {
        private boolean expired = false;

        @Override
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.Expired) {
                LOG.warn("ZK Session expired for service {} with runId {}.", decoratedService, id.getId());
                expired = true;
            } else if (event.getState() == Event.KeeperState.SyncConnected && expired) {
                LOG.info("Reconnected after expiration for service {} with runId {}", decoratedService,
                        id.getId());
                expired = false;
                Futures.addCallback(createLiveNode(), new FutureCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        // All good, no-op
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        notifyFailed(t);
                    }
                }, Threads.SAME_THREAD_EXECUTOR);
            }
        }
    });
}

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

private AddressTransactions getAddressTransactions(String address, int cont) {
    if (cont > 5)
        return null;
    AddressTransactions valCache = cache.getIfPresent("a/" + address);
    AddressTransactionsProvider atp1 = addTxsProviders.take();
    AddressTransactionsProvider atp2 = addTxsProviders.takeDifferent(atp1);
    log("atp1=" + atp1 + " atp2=" + atp2);
    Callable<AddressTransactions> runner1 = new AddressTransactionsRunnable(atp1, address);
    Callable<AddressTransactions> runner2 = new AddressTransactionsRunnable(atp2, 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 AddressTransactionsFutureCallback(start, atp1, returned, addTxsProviders));
    Futures.addCallback(listenableFuture2,
            new AddressTransactionsFutureCallback(start, atp2, returned, addTxsProviders));
    Runnable checker = new AddressTransactionsCheckRunnable(address, listenableFuture1, atp1, listenableFuture2,
            atp2, addTxsProviders, cache);
    moreExecutor.execute(checker);/*  ww w. j ava 2s  . co 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("a/" + address, first);
            return first;
        }
    } catch (Exception e) {
    }
    return getAddressTransactions(address, cont + 1);
}

From source file:com.microsoftopentechnologies.intellij.helpers.o365.Office365RestAPIManager.java

@Override
public void authenticate() throws IOException, ExecutionException, InterruptedException, ParseException {
    PluginSettings settings = MSOpenTechToolsApplication.getCurrent().getSettings();
    AuthenticationContext context = null;
    try {//from  w  ww. j  a  v a2s  .  c o  m
        context = new AuthenticationContext(settings.getAdAuthority());
        ListenableFuture<AuthenticationResult> future = context.acquireTokenInteractiveAsync(
                authenticated() ? getTenantDomain() : settings.getTenantName(), settings.getGraphApiUri(),
                settings.getClientId(), settings.getRedirectUri(), null, PromptValue.login);
        setAuthenticationToken(future.get());
    } finally {
        if (context != null) {
            context.dispose();
        }
    }
}

From source file:org.opendaylight.didm.identification.impl.DeviceIdentificationManager.java

private void setDeviceType(String deviceType, InstanceIdentifier<Node> path) {
    final InstanceIdentifier<DeviceType> deviceTypePath = path.augmentation(DeviceType.class);
    final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();

    tx.merge(LogicalDatastoreType.OPERATIONAL, deviceTypePath,
            new DeviceTypeBuilder().setDeviceType(deviceType).build());

    LOG.debug("Setting node '{}' device type to '{}'", path, deviceType);
    CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();

    // chain the result of the write with the expected rpc future.
    ListenableFuture<RpcResult<Void>> transform = Futures.transform(submitFuture,
            new AsyncFunction<Void, RpcResult<Void>>() {
                @Override/*  w w  w  .  ja va 2s .c  o m*/
                public ListenableFuture<RpcResult<Void>> apply(Void result) throws Exception {
                    return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
                }
            });

    // add a callback so we can log any exceptions on the write attempt
    Futures.addCallback(submitFuture, new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("Failed to write DeviceType to: {}", deviceTypePath, t);
        }
    });

    try {
        transform.get();
    } catch (Exception e) {
        LOG.error("Failed to write DeviceType to path: {}", path, e);
    }
}

From source file:org.opendaylight.ovsdb.plugin.impl.ConfigurationServiceImpl.java

@Override
@Deprecated/*w  w  w.  j  a v  a2s . com*/
public Status deleteRow(Node node, String tableName, String uuid) {
    String databaseName = OvsVswitchdSchemaConstants.DATABASE_NAME;
    Connection connection = connectionService.getConnection(node);
    OvsdbClient client = connection.getClient();

    String[] parentColumn = OvsVswitchdSchemaConstants.getParentColumnToMutate(tableName);
    if (parentColumn == null) {
        parentColumn = new String[] { null, null };
    }

    LOGGER.debug(
            "deleteRow : Connection : {} databaseName : {} tableName : {} Uuid : {} ParentTable : {} ParentColumn : {}",
            client.getConnectionInfo(), databaseName, tableName, uuid, parentColumn[0], parentColumn[1]);

    DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
    TransactionBuilder transactionBuilder = client.transactBuilder(dbSchema);
    this.processDeleteTransaction(client, OvsVswitchdSchemaConstants.DATABASE_NAME, tableName, parentColumn[0],
            parentColumn[1], uuid, transactionBuilder);

    ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
    List<OperationResult> operationResults;
    try {
        operationResults = results.get();
        if (operationResults.isEmpty()
                || (transactionBuilder.getOperations().size() != operationResults.size())) {
            return new StatusWithUuid(StatusCode.INTERNALERROR);
        }
        for (OperationResult result : operationResults) {
            if (result.getError() != null) {
                return new StatusWithUuid(StatusCode.BADREQUEST, result.getError());
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        LOGGER.error("Error in deleteRow() {} {}", node, tableName, e);
    }

    return new Status(StatusCode.SUCCESS);
}

From source file:org.opendaylight.ovsdb.plugin.impl.ConfigurationServiceImpl.java

@Override
public void deleteRow(Node node, String databaseName, String tableName, String parentTable, UUID parentRowUuid,
        String parentColumn, UUID rowUuid) {
    Connection connection = connectionService.getConnection(node);
    OvsdbClient client = connection.getClient();

    if (parentTable == null && parentRowUuid != null) {
        parentTable = this.getTableNameForRowUuid(node, databaseName, parentRowUuid);
    }//w ww  .j  a va2s .  c om

    String myParentColumn = parentColumn;
    if (myParentColumn == null && parentTable != null) {
        DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
        TableSchema<GenericTableSchema> parentTableSchema = dbSchema.table(parentTable,
                GenericTableSchema.class);
        myParentColumn = this.getReferencingColumn(parentTableSchema, tableName);
    }

    LOGGER.debug(
            "deleteRow : Connection : {} databaseName : {} tableName : {} Uuid : {} ParentTable : {} ParentColumn : {}",
            client.getConnectionInfo(), databaseName, tableName, rowUuid, parentTable, myParentColumn);

    DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
    TransactionBuilder transactionBuilder = client.transactBuilder(dbSchema);
    this.processDeleteTransaction(client, databaseName, tableName, parentTable, myParentColumn,
            rowUuid.toString(), transactionBuilder);

    ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
    List<OperationResult> operationResults;
    try {
        operationResults = results.get();
        if (operationResults.isEmpty()
                || (transactionBuilder.getOperations().size() != operationResults.size())) {
            throw new OvsdbPluginException("Delete Operation Failed");
        }
        for (OperationResult result : operationResults) {
            if (result.getError() != null) {
                throw new OvsdbPluginException(
                        "Delete Operation Failed with Error : " + result.getError().toString());
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        LOGGER.error("Error in deleteRow() {} {} {} {}", node, databaseName, tableName, parentTable, e);
    }
}

From source file:org.opendaylight.ovsdb.plugin.impl.ConfigurationServiceImpl.java

@Override
@Deprecated//from ww w . j  av  a2  s  . com
public StatusWithUuid insertRow(Node node, String tableName, String parentUuid, Row<GenericTableSchema> row) {
    String[] parentColumn = OvsVswitchdSchemaConstants.getParentColumnToMutate(tableName);
    if (parentColumn == null) {
        parentColumn = new String[] { null, null };
    }

    Connection connection = connectionService.getConnection(node);
    OvsdbClient client = connection.getClient();

    String myParentUuid = parentUuid;
    if (myParentUuid == null) {
        myParentUuid = this.getSpecialCaseParentUUID(node, OvsVswitchdSchemaConstants.DATABASE_NAME, tableName);
    }
    LOGGER.debug(
            "insertRow Connection : {} Table : {} ParentTable : {} Parent Column: {} Parent UUID : {} Row : {}",
            client.getConnectionInfo(), tableName, parentColumn[0], parentColumn[1], myParentUuid, row);

    DatabaseSchema dbSchema = client.getDatabaseSchema(OvsVswitchdSchemaConstants.DATABASE_NAME);
    TransactionBuilder transactionBuilder = client.transactBuilder(dbSchema);

    String namedUuid = "Transaction_" + tableName;
    this.processTypedInsertTransaction(client, OvsVswitchdSchemaConstants.DATABASE_NAME, tableName,
            parentColumn[0], myParentUuid, parentColumn[1], namedUuid, row, transactionBuilder);

    ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
    List<OperationResult> operationResults;
    try {
        operationResults = results.get();
        if (operationResults.isEmpty()
                || (transactionBuilder.getOperations().size() != operationResults.size())) {
            return new StatusWithUuid(StatusCode.INTERNALERROR);
        }
        for (OperationResult result : operationResults) {
            if (result.getError() != null) {
                return new StatusWithUuid(StatusCode.BADREQUEST, result.getError());
            }
        }
        UUID uuid = operationResults.get(0).getUuid();
        return new StatusWithUuid(StatusCode.SUCCESS, uuid);
    } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        return new StatusWithUuid(StatusCode.INTERNALERROR, e.getLocalizedMessage());
    }

}

From source file:org.opendaylight.ovsdb.plugin.impl.ConfigurationServiceImpl.java

/**
 * inserts a Tree of Rows in multiple Tables that has parent-child relationships referenced through the OVSDB schema's refTable construct
 *
 * @param node OVSDB Node//from w  w w. ja  v a  2s  .co  m
 * @param databaseName Database Name that represents the Schema supported by the node.
 * @param tableName Table on which the row is inserted
 * @param parentTable Name of the Parent Table to which this operation will result in attaching/mutating.
 * @param parentUuid UUID of a Row in parent table to which this operation will result in attaching/mutating.
 * @param parentColumn Name of the Column in the Parent Table to be mutated with the UUID that results from the insert operation.
 * @param row Row Tree with parent-child relationships via column of type refTable.
 * @throws OvsdbPluginException Any failure during the insert transaction will result in a specific exception.
 * @return Returns the row tree with the UUID of every inserted Row populated in the _uuid column of every row in the tree
 */
@Override
public Row<GenericTableSchema> insertTree(Node node, String databaseName, String tableName, String parentTable,
        UUID parentUuid, String parentColumn, Row<GenericTableSchema> row) throws OvsdbPluginException {
    Connection connection = connectionService.getConnection(node);
    OvsdbClient client = connection.getClient();

    if (databaseName == null || tableName == null) {
        throw new OvsdbPluginException("databaseName, tableName and parentUuid are Mandatory Parameters");
    }

    if (parentTable == null && parentUuid != null) {
        parentTable = this.getTableNameForRowUuid(node, databaseName, parentUuid);
    }

    if (parentColumn == null && parentTable != null) {
        DatabaseSchema dbSchema = client.getDatabaseSchema(databaseName);
        TableSchema<GenericTableSchema> parentTableSchema = dbSchema.table(parentTable,
                GenericTableSchema.class);
        parentColumn = this.getReferencingColumn(parentTableSchema, tableName);
    }

    LOGGER.debug(
            "insertTree Connection : {} Table : {} ParentTable : {} Parent Column: {} Parent UUID : {} Row : {}",
            client.getConnectionInfo(), tableName, parentTable, parentColumn, parentUuid, row);

    Map<UUID, Map.Entry<String, Row<GenericTableSchema>>> referencedRows = Maps.newConcurrentMap();
    extractReferencedRows(node, databaseName, row, referencedRows, 0);
    DatabaseSchema dbSchema = client.getDatabaseSchema(OvsVswitchdSchemaConstants.DATABASE_NAME);
    TransactionBuilder transactionBuilder = client.transactBuilder(dbSchema);

    String namedUuid = "Transaction_" + tableName;
    this.processInsertTransaction(client, databaseName, tableName, parentTable, parentUuid, parentColumn,
            namedUuid, row, transactionBuilder);

    int referencedRowsInsertIndex = transactionBuilder.getOperations().size();
    // Insert Referenced Rows
    if (referencedRows != null) {
        for (UUID refUuid : referencedRows.keySet()) {
            Map.Entry<String, Row<GenericTableSchema>> referencedRow = referencedRows.get(refUuid);
            TableSchema<GenericTableSchema> refTableSchema = dbSchema.table(referencedRow.getKey(),
                    GenericTableSchema.class);
            transactionBuilder
                    .add(op.insert(refTableSchema, referencedRow.getValue()).withId(refUuid.toString()));
        }
    }

    ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
    List<OperationResult> operationResults;
    try {
        operationResults = results.get();
        if (operationResults.isEmpty()
                || (transactionBuilder.getOperations().size() != operationResults.size())) {
            throw new OvsdbPluginException("Insert Operation Failed");
        }
        for (OperationResult result : operationResults) {
            if (result.getError() != null) {
                throw new OvsdbPluginException(
                        "Insert Operation Failed with Error : " + result.getError().toString());
            }
        }
        return getNormalizedRow(dbSchema, tableName, row, referencedRows, operationResults,
                referencedRowsInsertIndex);
    } catch (InterruptedException | ExecutionException e) {
        throw new OvsdbPluginException("Exception : " + e.getLocalizedMessage());
    }
}

From source file:de.dfki.kiara.impl.DefaultInvocationHandler.java

@Override
protected Object handleInvocation(Object o, Method method, Object[] os) throws Throwable {
    if (method.equals(SpecialMethods.riGetConnection)) {
        return connection;
    }//from w w w .j a  va 2 s  . com

    InterfaceMapping<?> mapping = getInterfaceMapping();

    final String idlFunctionName = mapping.getIDLMethodName(method);
    if (idlFunctionName == null) {
        throw new UnsupportedOperationException("Unbound method: " + method);
    }

    // check for Future<?>
    final MethodEntry methodEntry = mapping.getMethodEntry(method);

    logger.debug("has future params {} has listeningfuture params {}", methodEntry.hasFutureParams,
            methodEntry.hasListeningFutureParams);

    ListenableFuture<List<Object>> futureParams = null;

    if (methodEntry.hasFutureParams) {
        List<ListenableFuture<Object>> futureParamsList = new ArrayList<>(os.length);
        for (int i = 0; i < os.length; ++i) {
            final Function<Object, Object> f = ((Function<Object, Object>) methodEntry.paramConverters[i]);
            futureParamsList.add((ListenableFuture<Object>) f.apply(os[i]));
        }
        futureParams = Futures.allAsList(futureParamsList);
        //System.out.format("futureParams = %s%n", Joiner.on(" ").join(futureParams.get()));
    }

    if (methodEntry.kind == MethodEntry.MethodKind.SERIALIZER) {
        if (futureParams != null) {
            return protocol
                    .createRequestMessage(new Message.RequestObject(idlFunctionName, futureParams.get()));
        } else {
            return protocol.createRequestMessage(new Message.RequestObject(idlFunctionName, os));
        }
    } else if (methodEntry.kind == MethodEntry.MethodKind.DESERIALIZER) {
        Message msg = (Message) os[0];
        Message.ResponseObject ro = msg.getResponseObject(TypeToken.of(method.getGenericReturnType()));

        if (ro.isException) {
            if (ro.result instanceof Exception) {
                throw (Exception) ro.result;
            }
            throw new WrappedRemoteException(ro.result);
        }

        return ro.result;
    } else {
        if (futureParams != null && methodEntry.futureParamOfReturnType != null) {

            AsyncFunction<List<Object>, Object> f = new AsyncFunction<List<Object>, Object>() {

                @Override
                public ListenableFuture<Object> apply(List<Object> params) throws Exception {
                    final Message request = protocol
                            .createRequestMessage(new Message.RequestObject(idlFunctionName, params));
                    final TypeToken<?> returnType = TypeToken.of(methodEntry.futureParamOfReturnType);
                    final ListenableFuture<Message> responseFuture = connection.performRemoteAsyncCall(request,
                            Global.executor);
                    AsyncFunction<Message, Object> g = new AsyncFunction<Message, Object>() {

                        @Override
                        public ListenableFuture<Object> apply(final Message response) throws Exception {
                            return Global.executor.submit(new Callable<Object>() {

                                @Override
                                public Object call() throws Exception {
                                    Message.ResponseObject ro = response.getResponseObject(returnType);

                                    if (ro.isException) {
                                        if (ro.result instanceof Exception) {
                                            throw (Exception) ro.result;
                                        }
                                        throw new WrappedRemoteException(ro.result);
                                    }

                                    return ro.result;

                                }
                            });
                        }
                    };
                    return Futures.transform(responseFuture, g);
                }
            };
            return Futures.transform(futureParams, f);
        } else {

            /* Following code is for testing of synchronous message sending
                    
             if (futureParams == null && methodEntry.futureParamOfReturnType == null) {
             final Message request = protocol.createRequestMessage(new Message.RequestObject(idlFunctionName, os));
             final Message response = performSyncCall(request, method);
             final Message.ResponseObject ro = response.getResponseObject(method.getReturnType());
             if (ro.isException) {
             if (ro.result instanceof Exception) {
             throw (Exception) ro.result;
             }
             throw new WrappedRemoteException(ro.result);
             }
                    
             return ro.result;
             }
             */
            List<Object> params = futureParams != null ? futureParams.get() : Arrays.asList(os);

            final Message request = protocol
                    .createRequestMessage(new Message.RequestObject(idlFunctionName, params));

            final TypeToken<?> returnType = methodEntry.futureParamOfReturnType != null
                    ? TypeToken.of(methodEntry.futureParamOfReturnType)
                    : TypeToken.of(method.getGenericReturnType());

            final ListenableFuture<Message> responseFuture = connection.performRemoteAsyncCall(request,
                    Global.executor);

            if (methodEntry.futureParamOfReturnType != null) {
                AsyncFunction<Message, Object> f = new AsyncFunction<Message, Object>() {

                    @Override
                    public ListenableFuture<Object> apply(final Message response) throws Exception {
                        return Global.executor.submit(new Callable<Object>() {

                            @Override
                            public Object call() throws Exception {
                                Message.ResponseObject ro = response.getResponseObject(returnType);

                                if (ro.isException) {
                                    if (ro.result instanceof Exception) {
                                        throw (Exception) ro.result;
                                    }
                                    throw new WrappedRemoteException(ro.result);
                                }

                                return ro.result;

                            }
                        });
                    }
                };
                return Futures.transform(responseFuture, f);

            } else {

                Message response;
                try {
                    response = responseFuture.get();
                } catch (Exception ex) {
                    throw new RemoteInvocationException(ex);
                }
                Message.ResponseObject ro = response.getResponseObject(returnType);

                if (ro.isException) {
                    if (ro.result instanceof Exception) {
                        throw (Exception) ro.result;
                    }
                    throw new WrappedRemoteException(ro.result);
                }

                return ro.result;
            }
        }
    }

}