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.cassandra.CassandraSpanConsumer.java

/**
 * Store the span in the underlying storage for later retrieval.
 *//*from  ww w .j a  v  a  2 s .  co  m*/
ListenableFuture<?> storeSpan(long traceId, long timestamp, String key, ByteBuffer span) {
    try {
        if (0 == timestamp && metadata.compactionClass.contains("DateTieredCompactionStrategy")) {
            LOG.warn("Span {} in trace {} had no timestamp. "
                    + "If this happens a lot consider switching back to SizeTieredCompactionStrategy for "
                    + "{}.traces", key, traceId, session.getLoggedKeyspace());
        }

        BoundStatement bound = bindWithName(insertSpan, "insert-span").setLong("trace_id", traceId)
                .setBytesUnsafe("ts", timestampCodec.serialize(timestamp)).setString("span_name", key)
                .setBytes("span", span);
        if (!metadata.hasDefaultTtl)
            bound.setInt("ttl_", spanTtl);

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

From source file:io.v.android.security.BlessingsManager.java

/**
 * Mints a new set of {@link Blessings} that are persisted in {@link SharedPreferences} under
 * the provided key.//from  ww w  . j  a va 2s  .com
 * <p>
 * If {@code googleAccount} is non-{@code null} and non-empty, mints the blessings using
 * that account;  otherwise, prompts the user to pick one of the installed Google accounts
 * (if there is more than one installed).
 * <p>
 * This method will start an activity to handle the creation of new blessings.  Hence, you
 * should be prepared that your activity will be stopped and re-started, at the minimum.
 * <p>
 * This method is re-entrant: if invoked the 2nd time while the 1st invocation is still
 * pending, the future associated with the 2nd invocation will overwrite the 1st future: the
 * 1st future will never be invoked.
 * <p>
 * This method must be invoked on the UI thread.
 *
 * @param activity      android {@link Activity} requesting blessings
 * @param key           a key in {@link SharedPreferences} under which the newly minted
 *                      blessings are persisted
 * @param googleAccount a Google account to use to mint the blessings; if {@code null} or
 *                      empty, user will be prompted to pick one of the installed Google
 *                      accounts, if there is more than one installed
 * @param setAsDefault  if true, the returned {@link Blessings} will be set as default
 *                      blessings for the app
 * @return              a new {@link ListenableFuture} whose result are the newly minted
 *                      {@link Blessings}
 */
public static ListenableFuture<Blessings> mintBlessings(VContext ctx, final Activity activity, String key,
        String googleAccount, boolean setAsDefault) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        return Futures
                .immediateFailedFuture(new VException("mintBlessings() must be invoked " + "on the UI thread"));
    }
    if (mintFuture != null) {
        // Mint already in progress, which means that the invoking activity has been
        // destroyed and then recreated.  Register the new future to be invoked on completion
        // of that mint.  Note that it is safe and desirable to override the old future
        // as it's invocation would be handled by a destroyed activity.
        mintFuture = SettableFuture.create();
        return setAsDefault ? wrapWithSetAsDefault(ctx, activity, mintFuture) : mintFuture;
    }
    mintFuture = SettableFuture.create();
    FragmentTransaction transaction = activity.getFragmentManager().beginTransaction();
    BlessingsManager fragment = new BlessingsManager();
    fragment.mPrefKey = key;
    fragment.mGoogleAccount = googleAccount;
    transaction.add(fragment, UUID.randomUUID().toString());
    transaction.commit(); // this will invoke the fragment's onCreate() immediately.
    return setAsDefault ? wrapWithSetAsDefault(ctx, activity, mintFuture) : mintFuture;
}

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

/**
 * Get the billing overview for an organization that is managed by a partner.
 * Tax Disclaimer: Prices returned by this API do not include applicable taxes. It is the responsibility of the customer to pay all taxes that are appropriate in their jurisdiction. See the PureCloud API Documentation in the Developer Center for more information about this API: https://developer.mypurecloud.com/api/rest/v2/
 * @param request the request object//from w w w.j a  va  2 s.  c  o  m
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<TrusteeBillingOverview> getBillingTrusteebillingoverviewTrustorOrgIdAsync(
        GetBillingTrusteebillingoverviewTrustorOrgIdRequest request,
        final AsyncApiCallback<TrusteeBillingOverview> callback) {
    try {
        final SettableFuture<TrusteeBillingOverview> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<TrusteeBillingOverview>() {
        }, new AsyncApiCallback<ApiResponse<TrusteeBillingOverview>>() {
            @Override
            public void onCompleted(ApiResponse<TrusteeBillingOverview> response) {
                notifySuccess(future, callback, response.getBody());
            }

            @Override
            public void onFailed(Throwable exception) {
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    notifySuccess(future, callback, null);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:io.crate.executor.transport.AlterTableOperation.java

public ListenableFuture<Long> executeAlterTable(AlterTableAnalyzedStatement analysis) {
    DocTableInfo table = analysis.table();
    if (table.isAlias() && !table.isPartitioned()) {
        return Futures.immediateFailedFuture(new AlterTableAliasException(table.ident().fqn()));
    }/*from  www  .j ava 2  s .c  o m*/

    List<ListenableFuture<Long>> results = new ArrayList<>(3);

    if (table.isPartitioned()) {
        // create new filtered partition table settings
        AlterPartitionedTableParameterInfo tableSettingsInfo = (AlterPartitionedTableParameterInfo) table
                .tableParameterInfo();
        TableParameter parameterWithFilteredSettings = new TableParameter(analysis.tableParameter().settings(),
                tableSettingsInfo.partitionTableSettingsInfo().supportedInternalSettings());

        Optional<PartitionName> partitionName = analysis.partitionName();
        if (partitionName.isPresent()) {
            String index = partitionName.get().asIndexName();
            results.add(updateMapping(analysis.tableParameter().mappings(), index));
            results.add(updateSettings(parameterWithFilteredSettings, index));
        } else {
            // template gets all changes unfiltered
            results.add(updateTemplate(analysis.tableParameter(), table.ident()));

            if (!analysis.excludePartitions()) {
                String[] indices = table.concreteIndices();
                results.add(updateMapping(analysis.tableParameter().mappings(), indices));
                results.add(updateSettings(parameterWithFilteredSettings, indices));
            }
        }
    } else {
        results.add(updateMapping(analysis.tableParameter().mappings(), table.ident().indexName()));
        results.add(updateSettings(analysis.tableParameter(), table.ident().indexName()));
    }

    final SettableFuture<Long> result = SettableFuture.create();
    applyMultiFutureCallback(result, results);
    return result;
}

From source file:org.opendaylight.atrium.hostservice.impl.ArpSender.java

public ListenableFuture<RpcResult<Void>> sendArpResponse(ArpMessageAddress senderAddress,
        ArpMessageAddress receiverAddress, InstanceIdentifier<NodeConnector> egressNc, Header8021q vlan) {
    checkNotNull(senderAddress);//from  ww  w .  java 2s. co  m
    checkNotNull(receiverAddress);
    checkNotNull(egressNc);
    final Ethernet arpFrame = createArpFrame(senderAddress, receiverAddress, vlan);
    byte[] arpFrameAsBytes;
    try {
        arpFrameAsBytes = arpFrame.serialize();
    } catch (PacketException e) {
        LOG.warn("Serializition of ARP packet is not successful.", e);
        if (LOG.isDebugEnabled()) {
            LOG.debug("ARP packet: {}", ArpUtils.getArpFrameToStringFormat(arpFrame));
        }
        return Futures.immediateFailedFuture(e);
    }
    // Generate packet with destination switch and port
    LOG.debug("Egress for ARP packetOut: " + new NodeConnectorRef(egressNc).toString());
    TransmitPacketInput packet = new TransmitPacketInputBuilder().setEgress(new NodeConnectorRef(egressNc))
            .setNode(new NodeRef(egressNc.firstIdentifierOf(Node.class))).setPayload(arpFrameAsBytes).build();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Sending ARP RESPONSE \n{}", ArpUtils.getArpFrameToStringFormat(arpFrame));
    }
    Future<RpcResult<Void>> futureTransmitPacketResult = packetProcessingService.transmitPacket(packet);
    return JdkFutureAdapters.listenInPoolThread(futureTransmitPacketResult);
}

From source file:com.vmware.photon.controller.rootscheduler.service.ManagedScheduler.java

public ListenableFuture<FindResponse> find(FindRequest request, long timeout) {
    // Clone the request and set the scheduler id
    request = new FindRequest(request);
    request.setScheduler_id(id);//from  ww  w  .java  2s .c o m

    try {
        SettableFuture<FindResponse> promise = SettableFuture.create();
        client.setTimeout(timeout);
        client.find(request, new FindCallback(promise));
        return promise;
    } catch (TException e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:io.v.x.jni.test.fortune.FortuneServerImpl.java

@Override
public ListenableFuture<Void> getComplexError(VContext context, ServerCall call) {
    return Futures.immediateFailedFuture(COMPLEX_ERROR);
}

From source file:com.dogecoin.dogecoinj.net.NioClientManager.java

@Override
public ListenableFuture<SocketAddress> openConnection(SocketAddress serverAddress, StreamParser parser) {
    if (!isRunning())
        throw new IllegalStateException();
    // Create a new connection, give it a parser as an attachment
    try {//from ww  w  . java  2s .c  o  m
        SocketChannel sc = SocketChannel.open();
        sc.configureBlocking(false);
        sc.connect(serverAddress);
        PendingConnect data = new PendingConnect(sc, parser, serverAddress);
        newConnectionChannels.offer(data);
        selector.wakeup();
        return data.future;
    } catch (Throwable e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:org.bitcoinj.net.NioClientManager.java

@Override
public ListenableFuture<SocketAddress> openConnection(SocketAddress serverAddress,
        StreamConnection connection) {//from   w ww. j a  va2 s .  c  o  m
    if (!isRunning())
        throw new IllegalStateException();
    // Create a new connection, give it a connection as an attachment
    try {
        SocketChannel sc = SocketChannel.open();
        sc.configureBlocking(false);
        sc.connect(serverAddress);
        PendingConnect data = new PendingConnect(sc, connection, serverAddress);
        newConnectionChannels.offer(data);
        selector.wakeup();
        return data.future;
    } catch (Throwable e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:io.v.x.jni.test.fortune.FortuneServerImpl.java

@Override
public ListenableFuture<Void> testServerCall(VContext context, ServerCall call) {
    if (call == null) {
        return Futures.immediateFailedFuture(new VException("ServerCall is null"));
    }/*from w w  w . ja va  2s  .c o m*/
    if (call.suffix() == null) {
        return Futures.immediateFailedFuture(new VException("Suffix is null"));
    }
    if (call.localEndpoint() == null) {
        return Futures.immediateFailedFuture(new VException("Local endpoint is null"));
    }
    if (call.remoteEndpoint() == null) {
        return Futures.immediateFailedFuture(new VException("Remote endpoint is null"));
    }
    if (context == null) {
        return Futures.immediateFailedFuture(new VException("Vanadium context is null"));
    }
    return Futures.immediateFuture(null);
}