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:com.microsoft.azure.keyvault.cryptography.SymmetricKey.java

@Override
public ListenableFuture<byte[]> decryptAsync(final byte[] ciphertext, final byte[] iv,
        final byte[] authenticationData, final byte[] authenticationTag, final String algorithm)
        throws NoSuchAlgorithmException {

    if (Strings.isNullOrWhiteSpace(algorithm)) {
        throw new IllegalArgumentException("algorithm");
    }/*from  w ww  .ja  v a  2  s. c  o m*/

    if (ciphertext == null) {
        throw new IllegalArgumentException("ciphertext");
    }

    if (iv == null) {
        throw new IllegalArgumentException("iv");
    }

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

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

    SymmetricEncryptionAlgorithm algo = (SymmetricEncryptionAlgorithm) baseAlgorithm;

    ICryptoTransform transform = null;

    try {
        transform = algo.CreateDecryptor(_key, iv, authenticationData, authenticationTag, _provider);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }

    byte[] result = null;

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

    return Futures.immediateFuture(result);
}

From source file:net.floodlightcontroller.core.internal.OFConnection.java

@Override
public <REPLY extends OFStatsReply> ListenableFuture<List<REPLY>> writeStatsRequest(
        OFStatsRequest<REPLY> request) {
    if (!isConnected()) {
        return Futures.immediateFailedFuture(new SwitchDisconnectedException(getDatapathId()));
    }/*from www  .  j av a 2s . co m*/

    final DeliverableListenableFuture<List<REPLY>> future = new DeliverableListenableFuture<List<REPLY>>(
            request);

    Deliverable<REPLY> deliverable = new Deliverable<REPLY>() {
        private final List<REPLY> results = Collections.synchronizedList(new ArrayList<REPLY>());

        @Override
        public void deliver(REPLY reply) {
            results.add(reply);
            if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
                // done
                future.deliver(results);
            }
        }

        @Override
        public void deliverError(Throwable cause) {
            future.deliverError(cause);
        }

        @Override
        public boolean isDone() {
            return future.isDone();
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        @Override
        public OFMessage getRequest() {
            return future.getRequest();
        }
    };

    registerDeliverable(request.getXid(), deliverable);
    this.write(request);
    return future;
}

From source file:com.ltln.modules.openflow.controller.manager.OFConnection.java

@Override
public <REPLY extends OFStatsReply> ListenableFuture<List<REPLY>> writeStatsRequest(
        OFStatsRequest<REPLY> request) {
    if (!isConnected()) {
        return Futures.immediateFailedFuture(new SwitchDisconnectedException(getDatapathId()));
    }//from   w  w w .  ja  v a  2 s.  c om

    final DeliverableListenableFuture<List<REPLY>> future = new DeliverableListenableFuture<List<REPLY>>();

    Deliverable<REPLY> deliverable = new Deliverable<REPLY>() {
        private final List<REPLY> results = Collections.synchronizedList(new ArrayList<REPLY>());

        @Override
        public void deliver(REPLY reply) {
            results.add(reply);
            if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
                // done
                future.deliver(results);
            }
        }

        @Override
        public void deliverError(Throwable cause) {
            future.deliverError(cause);
        }

        @Override
        public boolean isDone() {
            return future.isDone();
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }
    };

    registerDeliverable(request.getXid(), deliverable);
    this.write(request);
    return future;
}

From source file:es.udc.pfc.gameroom.GameComponent.java

@Override
protected ListenableFuture<IQ> handleIQ(IQ iq) {
    return Futures.immediateFailedFuture(new Exception("Not implemented"));
}

From source file:net.floodlightcontroller.core.OFConnection.java

@Override
public <REPLY extends OFStatsReply> ListenableFuture<List<REPLY>> writeStatsRequest(
        OFStatsRequest<REPLY> request) {
    if (!isConnected())
        return Futures.immediateFailedFuture(new SwitchDisconnectedException(getDatapathId()));

    final DeliverableListenableFuture<List<REPLY>> future = new DeliverableListenableFuture<List<REPLY>>();

    Deliverable<REPLY> deliverable = new Deliverable<REPLY>() {
        private final List<REPLY> results = Collections.synchronizedList(new ArrayList<REPLY>());

        @Override// w w  w .  j ava  2  s .c om
        public void deliver(REPLY reply) {
            results.add(reply);
            if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
                // done
                future.deliver(results);
            }
        }

        @Override
        public void deliverError(Throwable cause) {
            future.deliverError(cause);
        }

        @Override
        public boolean isDone() {
            return future.isDone();
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }
    };

    registerDeliverable(request.getXid(), deliverable);
    this.write(request);
    return future;
}

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

/**
 * Store the span in the underlying storage for later retrieval.
 */// ww w  .  ja  v  a  2  s  . c om
ListenableFuture<?> storeSpan(Span span, TraceIdUDT traceId, Long timestamp) {
    try {
        if ((null == timestamp || 0 == timestamp)
                && metadata.compactionClass.contains("TimeWindowCompactionStrategy")) {

            LOG.warn("Span {} in trace {} had no timestamp. "
                    + "If this happens a lot consider switching back to SizeTieredCompactionStrategy for "
                    + "{}.traces", span.id, span.traceId, session.getLoggedKeyspace());
        }

        List<AnnotationUDT> annotations = new ArrayList<>(span.annotations.size());
        for (Annotation annotation : span.annotations) {
            annotations.add(new AnnotationUDT(annotation));
        }
        List<BinaryAnnotationUDT> binaryAnnotations = new ArrayList<>(span.binaryAnnotations.size());
        for (BinaryAnnotation annotation : span.binaryAnnotations) {
            binaryAnnotations.add(new BinaryAnnotationUDT(annotation));
        }
        Set<String> annotationKeys = CassandraUtil.annotationKeys(span);

        if (!strictTraceId && traceId.getHigh() != 0L) {
            storeSpan(span, new TraceIdUDT(0L, traceId.getLow()), timestamp);
        }

        BoundStatement bound = bindWithName(insertSpan, "insert-span")
                .set("trace_id", traceId, TraceIdUDT.class)
                .setUUID("ts_uuid",
                        new UUID(UUIDs.startOf(null != timestamp ? (timestamp / 1000) : 0)
                                .getMostSignificantBits(), UUIDs.random().getLeastSignificantBits()))
                .setLong("id", span.id).setString("span_name", span.name).setList("annotations", annotations)
                .setList("binary_annotations", binaryAnnotations)
                .setString("all_annotations", Joiner.on(',').join(annotationKeys));

        if (null != span.timestamp) {
            bound = bound.setLong("ts", span.timestamp);
        }
        if (null != span.duration) {
            bound = bound.setLong("duration", span.duration);
        }
        if (null != span.parentId) {
            bound = bound.setLong("parent_id", span.parentId);
        }

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

From source file:org.apache.druid.indexing.common.task.batch.parallel.TaskMonitor.java

public ListenableFuture<SubTaskCompleteEvent<T>> submit(SubTaskSpec<T> spec) {
    synchronized (startStopLock) {
        if (!running) {
            return Futures.immediateFailedFuture(new ISE("TaskMonitore is not running"));
        }/*from   w w w .  j a v  a2  s  . c om*/
        final T task = spec.newSubTask(0);
        log.info("Submitting a new task[%s] for spec[%s]", task.getId(), spec.getId());
        indexingServiceClient.runTask(task);
        incrementNumRunningTasks();

        final SettableFuture<SubTaskCompleteEvent<T>> taskFuture = SettableFuture.create();
        runningTasks.put(spec.getId(), new MonitorEntry(spec, task,
                indexingServiceClient.getTaskStatus(task.getId()).getStatus(), taskFuture));

        return taskFuture;
    }
}

From source file:com.spotify.asyncdatastoreclient.Datastore.java

/**
 * Start a new transaction./*  w w  w  . ja  v  a 2  s . co m*/
 *
 * The returned {@code TransactionResult} contains the transaction if the
 * request is successful.
 *
 * @param isolationLevel the transaction isolation level to request.
 * @return the result of the transaction request.
 */
public ListenableFuture<TransactionResult> transactionAsync(final IsolationLevel isolationLevel) {
    final ListenableFuture<Response> httpResponse;
    try {
        final DatastoreV1.BeginTransactionRequest.Builder request = DatastoreV1.BeginTransactionRequest
                .newBuilder();
        if (isolationLevel == IsolationLevel.SERIALIZABLE) {
            request.setIsolationLevel(DatastoreV1.BeginTransactionRequest.IsolationLevel.SERIALIZABLE);
        } else {
            request.setIsolationLevel(DatastoreV1.BeginTransactionRequest.IsolationLevel.SNAPSHOT);
        }
        final ProtoHttpContent payload = new ProtoHttpContent(request.build());
        httpResponse = ListenableFutureAdapter
                .asGuavaFuture(prepareRequest("beginTransaction", payload).execute());
    } catch (final Exception e) {
        return Futures.immediateFailedFuture(new DatastoreException(e));
    }
    return Futures.transform(httpResponse, (Response response) -> {
        if (!isSuccessful(response.getStatusCode())) {
            throw new DatastoreException(response.getStatusCode(), response.getResponseBody());
        }
        final DatastoreV1.BeginTransactionResponse transaction = DatastoreV1.BeginTransactionResponse
                .parseFrom(streamResponse(response));
        return Futures.immediateFuture(TransactionResult.build(transaction));
    });
}

From source file:org.thingsboard.server.kafka.TbKafkaRequestTemplate.java

public ListenableFuture<Response> post(String key, Request request) {
    if (tickSize > maxPendingRequests) {
        return Futures.immediateFailedFuture(new RuntimeException("Pending request map is full!"));
    }/*  w  w w.j a v  a  2s . c  om*/
    UUID requestId = UUID.randomUUID();
    List<Header> headers = new ArrayList<>(2);
    headers.add(new RecordHeader(TbKafkaSettings.REQUEST_ID_HEADER, uuidToBytes(requestId)));
    headers.add(new RecordHeader(TbKafkaSettings.RESPONSE_TOPIC_HEADER,
            stringToBytes(responseTemplate.getTopic())));
    SettableFuture<Response> future = SettableFuture.create();
    ResponseMetaData<Response> responseMetaData = new ResponseMetaData<>(tickTs + maxRequestTimeout, future);
    pendingRequests.putIfAbsent(requestId, responseMetaData);
    request = requestTemplate.enrich(request, responseTemplate.getTopic(), requestId);
    log.trace("[{}] Sending request, key [{}], expTime [{}]", requestId, key, responseMetaData.expTime);
    requestTemplate.send(key, request, headers, (metadata, exception) -> {
        if (exception != null) {
            log.trace("[{}] Failed to post the request", requestId, exception);
        } else {
            log.trace("[{}] Posted the request", requestId, metadata);
        }
    });
    return future;
}

From source file:org.opendaylight.vpnservice.natservice.internal.VpnFloatingIpHandler.java

@Override
public void onAddFloatingIp(final BigInteger dpnId, final String routerId, Uuid networkId,
        final String interfaceName, final String externalIp, final String internalIp) {
    final String vpnName = NatUtil.getAssociatedVPN(dataBroker, networkId, LOG);
    if (vpnName == null) {
        LOG.info("No VPN associated with ext nw {} to handle add floating ip configuration {} in router {}",
                networkId, externalIp, routerId);
        return;//w  w  w.j a  va2 s.  c  o  m
    }

    GenerateVpnLabelInput labelInput = new GenerateVpnLabelInputBuilder().setVpnName(vpnName)
            .setIpPrefix(externalIp).build();
    Future<RpcResult<GenerateVpnLabelOutput>> labelFuture = vpnService.generateVpnLabel(labelInput);

    ListenableFuture<RpcResult<Void>> future = Futures.transform(
            JdkFutureAdapters.listenInPoolThread(labelFuture),
            new AsyncFunction<RpcResult<GenerateVpnLabelOutput>, RpcResult<Void>>() {

                @Override
                public ListenableFuture<RpcResult<Void>> apply(RpcResult<GenerateVpnLabelOutput> result)
                        throws Exception {
                    if (result.isSuccessful()) {
                        GenerateVpnLabelOutput output = result.getResult();
                        long label = output.getLabel();
                        LOG.debug("Generated label {} for prefix {}", label, externalIp);
                        listener.updateOperationalDS(routerId, interfaceName, (int) label, internalIp,
                                externalIp);

                        //Inform BGP
                        String rd = NatUtil.getVpnRd(dataBroker, vpnName);
                        String nextHopIp = NatUtil.getEndpointIpAddressForDPN(dataBroker, dpnId);
                        LOG.debug("Nexthop ip for prefix {} is {}", externalIp, nextHopIp);
                        NatUtil.addPrefixToBGP(bgpManager, rd, externalIp + "/32", nextHopIp, label, LOG);

                        List<Instruction> instructions = new ArrayList<Instruction>();
                        List<ActionInfo> actionsInfos = new ArrayList<ActionInfo>();
                        actionsInfos.add(new ActionInfo(ActionType.nx_resubmit,
                                new String[] { Integer.toString(NatConstants.PDNAT_TABLE) }));
                        instructions.add(new InstructionInfo(InstructionType.apply_actions, actionsInfos)
                                .buildInstruction(0));
                        makeTunnelTableEntry(dpnId, label, instructions);

                        //Install custom FIB routes
                        List<Instruction> customInstructions = new ArrayList<>();
                        customInstructions.add(new InstructionInfo(InstructionType.goto_table,
                                new long[] { NatConstants.PDNAT_TABLE }).buildInstruction(0));
                        makeLFibTableEntry(dpnId, label, NatConstants.PDNAT_TABLE);
                        CreateFibEntryInput input = new CreateFibEntryInputBuilder().setVpnName(vpnName)
                                .setSourceDpid(dpnId).setInstruction(customInstructions)
                                .setIpAddress(externalIp + "/32").setServiceId(label)
                                .setInstruction(customInstructions).build();
                        //Future<RpcResult<java.lang.Void>> createFibEntry(CreateFibEntryInput input);
                        Future<RpcResult<Void>> future = fibService.createFibEntry(input);
                        return JdkFutureAdapters.listenInPoolThread(future);
                    } else {
                        String errMsg = String.format(
                                "Could not retrieve the label for prefix %s in VPN %s, %s", externalIp, vpnName,
                                result.getErrors());
                        LOG.error(errMsg);
                        return Futures.immediateFailedFuture(new RuntimeException(errMsg));
                    }
                }
            });

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

        @Override
        public void onFailure(Throwable error) {
            LOG.error("Error in generate label or fib install process", error);
        }

        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                LOG.info("Successfully installed custom FIB routes for prefix {}", externalIp);
            } else {
                LOG.error("Error in rpc call to create custom Fib entries for prefix {} in DPN {}, {}",
                        externalIp, dpnId, result.getErrors());
            }
        }
    });
}