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

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

Introduction

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

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) 

Source Link

Document

Returns a ListenableFuture which has an exception set immediately upon construction.

Usage

From source file:zipkin.storage.cassandra3.CassandraSpanConsumer.java

ListenableFuture<?> storeServiceSpanName(String serviceName, String spanName) {
    try {/*from  w w w .j a va 2 s.  c  o  m*/
        BoundStatement bound = bindWithName(insertServiceSpanName, "insert-service-span-name")
                .setString("service_name", serviceName).setString("span_name", spanName);

        return session.executeAsync(bound);
    } catch (RuntimeException ex) {
        return Futures.immediateFailedFuture(ex);
    }
}

From source file:org.glowroot.central.util.Session.java

public ListenableFuture<ResultSet> readAsyncFailIfNoRows(Statement statement, String errorMessage)
        throws Exception {
    return Futures.transformAsync(readAsync(statement), new AsyncFunction<ResultSet, ResultSet>() {
        @Override//from   w  w w.j  a v  a 2s  .  c om
        public ListenableFuture<ResultSet> apply(ResultSet results) {
            if (results.isExhausted()) {
                return Futures.immediateFailedFuture(new Exception(errorMessage));
            } else {
                return Futures.immediateFuture(results);
            }
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java

/**
 * Get all PureCloud license definitions available for the organization.
 * /*from   ww  w . ja v a 2s  .c  o m*/
 * @param request the request object
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<ApiResponse<List<LicenseDefinition>>> getLicenseDefinitionsAsync(ApiRequest<Void> request,
        final AsyncApiCallback<ApiResponse<List<LicenseDefinition>>> callback) {
    try {
        final SettableFuture<ApiResponse<List<LicenseDefinition>>> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request, new TypeReference<List<LicenseDefinition>>() {
        }, new AsyncApiCallback<ApiResponse<List<LicenseDefinition>>>() {
            @Override
            public void onCompleted(ApiResponse<List<LicenseDefinition>> response) {
                notifySuccess(future, callback, response);
            }

            @Override
            public void onFailed(Throwable exception) {
                if (exception instanceof ApiException) {
                    @SuppressWarnings("unchecked")
                    ApiResponse<List<LicenseDefinition>> response = (ApiResponse<List<LicenseDefinition>>) (ApiResponse<?>) exception;
                    notifySuccess(future, callback, response);
                }
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    @SuppressWarnings("unchecked")
                    ApiResponse<List<LicenseDefinition>> response = (ApiResponse<List<LicenseDefinition>>) (ApiResponse<?>) (new ApiException(
                            exception));
                    notifySuccess(future, callback, response);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:org.opendaylight.faas.fabricmgr.VContainerNetNodeServiceProvider.java

@Override
public Future<RpcResult<CreateLneLayer2Output>> createLneLayer2(CreateLneLayer2Input input) {
    FabricMgrProvider fmgr = FabricMgrProvider.getInstance();
    if (fmgr == null) {
        LOG.error("FABMGR: null FabricMgrProvider");
        return Futures.immediateFailedFuture(new IllegalArgumentException("fmgr is null!"));
    }//from ww w.  j a v  a2s .  c o  m

    TenantId tenantId = input.getTenantId();
    VContainerConfigMgr vcMgr = fmgr.getVcConfigDataMgr(new Uuid(tenantId.getValue()));
    if (vcMgr == null) {
        LOG.error("FABMGR: ERROR: createLneLayer2: vcMgr is null: {}", tenantId.getValue());
        return Futures.immediateFailedFuture(new IllegalArgumentException("vcMgr is null"));
    }

    FabricId fabricId = new FabricId(input.getVfabricId());
    int l2Resource = vcMgr.getLdNodeConfigDataMgr().getAvailableL2Resource(fabricId);
    if (l2Resource == 0) {
        LOG.error("No L2 VNI resoruce avaialble!");
        return Futures.immediateFailedFuture(new IllegalArgumentException("No L2 VNI resource avaialbe!"));
    }

    CreateLogicalSwitchInputBuilder lswInputBuilder = new CreateLogicalSwitchInputBuilder();
    String lswName = input.getName();
    lswInputBuilder.setFabricId(fabricId);
    lswInputBuilder.setName(lswName);

    lswInputBuilder.setVni(new Integer(l2Resource));
    lswInputBuilder.setExternal(false);

    LOG.debug("FABMGR: createLneLayer2: lswName={}, fabricId={}, vni={}", lswName, fabricId.getValue(),
            l2Resource);

    final RpcResultBuilder<CreateLneLayer2Output> resultBuilder = RpcResultBuilder
            .<CreateLneLayer2Output>success();
    Future<RpcResult<CreateLogicalSwitchOutput>> result = this.fabServiceService
            .createLogicalSwitch(lswInputBuilder.build());
    try {
        RpcResult<CreateLogicalSwitchOutput> output = result.get();
        if (output.isSuccessful()) {
            LOG.debug("FABMGR: createLneLayer2: createLogicSwitch RPC success");
            CreateLneLayer2OutputBuilder builder = new CreateLneLayer2OutputBuilder();
            CreateLogicalSwitchOutput createLswOutput = output.getResult();

            NodeId nodeId = createLswOutput.getNodeId();
            builder.setLneId(new VcLneId(nodeId));

            return Futures.immediateFuture(resultBuilder.withResult(builder.build()).build());
        }
    } catch (Exception e) {
        LOG.error("FABMGR: ERROR: createLneLayer2: createLogicSwitch RPC failed.", e);
    }

    return Futures.immediateFailedFuture(new IllegalArgumentException("createLogicSwitch RPC failed"));

}

From source file:org.apache.twill.internal.logging.KafkaAppender.java

private ListenableFuture<Integer> doPublishLogs(Collection<ByteBuffer> logs) {
    // Nothing to publish, simply returns a completed future.
    if (logs.isEmpty()) {
        return Futures.immediateFuture(0);
    }/*from w ww . j  a  v  a  2 s .c  o  m*/

    // If the publisher is not available, tries to create one.
    KafkaPublisher.Preparer publisher = KafkaAppender.this.publisher.get();
    if (publisher == null) {
        try {
            KafkaPublisher.Preparer preparer = kafkaClient
                    .getPublisher(KafkaPublisher.Ack.LEADER_RECEIVED, Compression.SNAPPY).prepare(topic);
            KafkaAppender.this.publisher.compareAndSet(null, preparer);
            publisher = KafkaAppender.this.publisher.get();
        } catch (Exception e) {
            return Futures.immediateFailedFuture(e);
        }
    }

    for (ByteBuffer buffer : logs) {
        publisher.add(buffer, 0);
    }

    return publisher.send();
}

From source file:com.microsoft.azure.keyvault.cryptography.RsaKey.java

@Override
public ListenableFuture<Boolean> verifyAsync(final byte[] digest, final byte[] signature,
        final String algorithm) throws NoSuchAlgorithmException {

    if (digest == null) {
        throw new IllegalArgumentException("encryptedKey ");
    }/*  w w w  . j  a  v  a2 s  .c  o m*/

    // Interpret the requested algorithm
    if (Strings.isNullOrWhiteSpace(algorithm)) {
        throw new IllegalArgumentException("algorithm");
    }

    // Interpret the requested algorithm
    Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm);

    if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) {
        throw new NoSuchAlgorithmException(algorithm);
    }

    Rs256 algo = (Rs256) baseAlgorithm;

    ISignatureTransform signer = algo.createSignatureTransform(_keyPair);

    try {
        return Futures.immediateFuture(signer.verify(digest, signature));
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils.java

/**
 * InitializationNodeInformation is good to call only for MASTER otherwise we will have not empty transaction
 * for every Cluster Node (SLAVE too) and we will get race-condition by closing Connection.
 *
 * @param deviceContext/*from ww w.  j  a v  a2  s.com*/
 * @param switchFeaturesMandatory
 * @return future - recommended to have blocking call for this future
 */
public static ListenableFuture<Void> initializeNodeInformation(final DeviceContext deviceContext,
        final boolean switchFeaturesMandatory) {
    Preconditions.checkArgument(deviceContext != null);
    final DeviceState deviceState = Preconditions.checkNotNull(deviceContext.getDeviceState());
    final ConnectionContext connectionContext = Preconditions
            .checkNotNull(deviceContext.getPrimaryConnectionContext());
    final short version = deviceState.getVersion();
    LOG.trace("initalizeNodeInformation for node {}", deviceState.getNodeId());
    final SettableFuture<Void> returnFuture = SettableFuture.<Void>create();
    addNodeToOperDS(deviceContext, returnFuture);
    final ListenableFuture<List<RpcResult<List<MultipartReply>>>> deviceFeaturesFuture;
    if (OFConstants.OFP_VERSION_1_0 == version) {
        final CapabilitiesV10 capabilitiesV10 = connectionContext.getFeatures().getCapabilitiesV10();

        DeviceStateUtil.setDeviceStateBasedOnV10Capabilities(deviceState, capabilitiesV10);

        deviceFeaturesFuture = createDeviceFeaturesForOF10(deviceContext, deviceState);
        // create empty tables after device description is processed
        chainTableTrunkWriteOF10(deviceContext, deviceFeaturesFuture);

        final short ofVersion = deviceContext.getDeviceState().getVersion();
        final TranslatorKey translatorKey = new TranslatorKey(ofVersion, PortGrouping.class.getName());
        final MessageTranslator<PortGrouping, FlowCapableNodeConnector> translator = deviceContext.oook()
                .lookupTranslator(translatorKey);
        final BigInteger dataPathId = deviceContext.getPrimaryConnectionContext().getFeatures().getDatapathId();

        for (final PortGrouping port : connectionContext.getFeatures().getPhyPort()) {
            final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, deviceContext, null);

            final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil
                    .nodeConnectorId(dataPathId.toString(), port.getPortNo(), ofVersion);
            final NodeConnectorBuilder ncBuilder = new NodeConnectorBuilder().setId(nodeConnectorId);
            ncBuilder.addAugmentation(FlowCapableNodeConnector.class, fcNodeConnector);
            ncBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class,
                    new FlowCapableNodeConnectorStatisticsDataBuilder().build());
            final NodeConnector connector = ncBuilder.build();
            final InstanceIdentifier<NodeConnector> connectorII = deviceState.getNodeInstanceIdentifier()
                    .child(NodeConnector.class, connector.getKey());
            try {
                deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, connectorII, connector);
            } catch (final Exception e) {
                LOG.debug("Failed to write node {} to DS ",
                        deviceContext.getDeviceState().getNodeId().toString(), e);
            }

        }
    } else if (OFConstants.OFP_VERSION_1_3 == version) {
        final Capabilities capabilities = connectionContext.getFeatures().getCapabilities();
        LOG.debug("Setting capabilities for device {}", deviceContext.getDeviceState().getNodeId());
        DeviceStateUtil.setDeviceStateBasedOnV13Capabilities(deviceState, capabilities);
        deviceFeaturesFuture = createDeviceFeaturesForOF13(deviceContext, deviceState, switchFeaturesMandatory);
    } else {
        deviceFeaturesFuture = Futures
                .immediateFailedFuture(new ConnectionException("Unsupported version " + version));
    }

    Futures.addCallback(deviceFeaturesFuture, new FutureCallback<List<RpcResult<List<MultipartReply>>>>() {
        @Override
        public void onSuccess(final List<RpcResult<List<MultipartReply>>> result) {
            LOG.debug("All init data for node {} is in submited.", deviceState.getNodeId());
            returnFuture.set(null);
        }

        @Override
        public void onFailure(final Throwable t) {
            // FIXME : remove session
            LOG.trace("Device capabilities gathering future failed.");
            LOG.trace("more info in exploration failure..", t);
            LOG.debug("All init data for node {} was not submited correctly - connection has to go down.",
                    deviceState.getNodeId());
            returnFuture.setException(t);
        }
    });
    return returnFuture;
}

From source file:com.google.cloud.bigtable.hbase.BatchExecutor.java

private ListenableFuture<? extends GeneratedMessageV3> issueAsyncRequest(BulkOperation bulkOperation, Row row) {
    try {/*from  w  w  w.ja  v a 2 s  .  co  m*/
        if (row instanceof Get) {
            return bulkOperation.readRowsAsync(requestAdapter.adapt((Get) row));
        } else if (row instanceof Put) {
            return bulkOperation.mutateRowAsync(requestAdapter.adapt((Put) row));
        } else if (row instanceof Delete) {
            return bulkOperation.mutateRowAsync(requestAdapter.adapt((Delete) row));
        } else if (row instanceof Append) {
            return asyncExecutor.readModifyWriteRowAsync(requestAdapter.adapt((Append) row));
        } else if (row instanceof Increment) {
            return asyncExecutor.readModifyWriteRowAsync(requestAdapter.adapt((Increment) row));
        } else if (row instanceof RowMutations) {
            return bulkOperation.mutateRowAsync(requestAdapter.adapt((RowMutations) row));
        }
    } catch (Exception e) {
        return Futures.immediateFailedFuture(new IOException("Could not process the batch", e));
    }
    LOG.error("Encountered unknown action type %s", row.getClass());
    return Futures.immediateFailedFuture(
            new IllegalArgumentException("Encountered unknown action type: " + row.getClass()));
}

From source file:org.voltdb.DeprecatedDefaultSnapshotDataTarget.java

private ListenableFuture<?> write(final Callable<BBContainer> tupleDataC, final boolean prependLength) {
    /*/*from w w  w  .j  a v  a 2s  . c o  m*/
     * Unwrap the data to be written. For the traditional
     * snapshot data target this should be a noop.
     */
    BBContainer tupleDataTemp;
    try {
        tupleDataTemp = tupleDataC.call();
    } catch (Throwable t) {
        return Futures.immediateFailedFuture(t);
    }
    final BBContainer tupleData = tupleDataTemp;

    if (m_writeFailed) {
        tupleData.discard();
        return null;
    }

    if (prependLength) {
        tupleData.b.putInt(tupleData.b.remaining() - 4);
        tupleData.b.position(0);
    }

    m_outstandingWriteTasks.incrementAndGet();
    ListenableFuture<?> writeTask = m_es.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            try {
                if (m_acceptOneWrite) {
                    m_acceptOneWrite = false;
                } else {
                    if (m_simulateFullDiskWritingChunk) {
                        throw new IOException("Disk full");
                    }
                }

                m_bytesAllowedBeforeSync.acquire(tupleData.b.remaining());

                int totalWritten = 0;
                while (tupleData.b.hasRemaining()) {
                    totalWritten += m_channel.write(tupleData.b);
                }
                m_bytesWritten += totalWritten;
                m_bytesWrittenSinceLastSync.addAndGet(totalWritten);
            } catch (IOException e) {
                m_writeException = e;
                hostLog.error("Error while attempting to write snapshot data to file " + m_file, e);
                m_writeFailed = true;
                throw e;
            } finally {
                tupleData.discard();
                m_outstandingWriteTasksLock.lock();
                try {
                    if (m_outstandingWriteTasks.decrementAndGet() == 0) {
                        m_noMoreOutstandingWriteTasksCondition.signalAll();
                    }
                } finally {
                    m_outstandingWriteTasksLock.unlock();
                }
            }
            return null;
        }
    });
    return writeTask;
}

From source file:com.microsoft.azure.keyvault.cryptography.SymmetricKey.java

@Override
public ListenableFuture<Pair<byte[], String>> wrapKeyAsync(final byte[] key, final String algorithm)
        throws NoSuchAlgorithmException {

    if (key == null || key.length == 0) {
        throw new IllegalArgumentException("key");
    }// ww w .j  av  a2s  . c  o  m

    // Interpret the algorithm
    String algorithmName = (Strings.isNullOrWhiteSpace(algorithm)) ? getDefaultKeyWrapAlgorithm() : algorithm;
    Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithmName);

    if (baseAlgorithm == null || !(baseAlgorithm instanceof KeyWrapAlgorithm)) {
        throw new NoSuchAlgorithmException(algorithmName);
    }

    KeyWrapAlgorithm algo = (KeyWrapAlgorithm) baseAlgorithm;

    ICryptoTransform transform = null;

    try {
        transform = algo.CreateEncryptor(_key, null, _provider);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }

    byte[] encrypted = null;

    try {
        encrypted = transform.doFinal(key);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }

    return Futures.immediateFuture(Pair.of(encrypted, algorithmName));
}