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:org.opendaylight.atrium.hostservice.impl.ArpSender.java

/**
 * Sends ARP Request as packet-out from the given port (node connector).
 *
 * @param senderAddress/*  w  w w . j a  v  a2  s . c  om*/
 *            the addresses used in sender part of ARP packet
 * @param tpa
 *            the target protocol address, in this case IPv4 address for
 *            which MAC should be discovered
 * @param egressNc
 *            the path to node connector from where the ARP packet will be
 *            sent
 * @return future result about success of packet-out
 */
public ListenableFuture<RpcResult<Void>> sendArp(ArpMessageAddress senderAddress, Ipv4Address tpa,
        InstanceIdentifier<NodeConnector> egressNc) {
    checkNotNull(senderAddress);
    checkNotNull(tpa);
    checkNotNull(egressNc);
    final Ethernet arpFrame = createArpFrame(senderAddress, tpa);
    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

    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 REQUEST \n{}", ArpUtils.getArpFrameToStringFormat(arpFrame));
    }
    Future<RpcResult<Void>> futureTransmitPacketResult = packetProcessingService.transmitPacket(packet);
    return JdkFutureAdapters.listenInPoolThread(futureTransmitPacketResult);
}

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

@Override
public <R extends OFMessage> ListenableFuture<R> writeRequest(OFRequest<R> request) {
    if (!isConnected())
        return Futures.immediateFailedFuture(new SwitchDisconnectedException(getDatapathId()));

    DeliverableListenableFuture<R> future = new DeliverableListenableFuture<R>();
    xidDeliverableMap.put(request.getXid(), future);
    listener.messageWritten(this, request);
    write(request);//from  w  w  w .j  ava  2  s  .  com
    return future;
}

From source file:org.opendaylight.sxp.route.core.RouteReactorZipImpl.java

@Override
public ListenableFuture<Void> wipeRouting() {
    ListenableFuture<Void> futureResult;
    try {//w  w  w. j av a  2 s  .  c  om
        queueGuard.acquire();

        if (compressionQueue.isEmpty()) {
            compressionQueue.add(new MutablePair<>(null, WIPE_ROUTING_MARK));
            // schedule task
            futureResult = servicePool.submit(updateRouteTask);
        } else {
            // compress, expect that task is already scheduled
            compressionQueue.peek().setRight(WIPE_ROUTING_MARK);
            futureResult = COMPRESSED_FUTURE_RESULT;
            LOG.trace("route update request got state compressed - firing immediate future");
        }

        queueGuard.release();
    } catch (Exception e) {
        LOG.warn("failed to get lock upon compression queue: {}", e.getMessage());
        futureResult = Futures.immediateFailedFuture(e);
    }
    return futureResult;
}

From source file:org.opendaylight.faas.fabric.general.FabricResourceAPIProvider.java

@Override
public Future<RpcResult<Void>> createFabricPort(CreateFabricPortInput input) {
    return Futures.immediateFailedFuture(new RuntimeException("Not implemet yet!"));
}

From source file:co.cask.cdap.app.guice.ImpersonatedTwillController.java

@Override
public Future<? extends ServiceController> terminate() {
    try {//  www . j  a  v a  2s .com
        return impersonator.doAs(programId, new Callable<Future<? extends ServiceController>>() {
            @Override
            public Future<? extends ServiceController> call() throws Exception {
                return delegate.terminate();
            }
        });
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:com.orangerhymelabs.helenus.cassandra.table.TableRepository.java

@Override
public ListenableFuture<Table> create(Table table) {
    if (createDocumentSchema(table)) {
        // TODO: what about rollback?
        return super.create(table);
    } else {/* ww w  . j a  v  a2 s . c o  m*/
        return Futures.immediateFailedFuture(
                new StorageException("Failed to create document schema for: " + table.toDbTable()));
    }
}

From source file:org.jclouds.rest.internal.AsyncRestClientProxy.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private ListenableFuture<?> createListenableFuture(Method method, Object[] args) throws ExecutionException {
    method = annotationProcessor.getDelegateOrNull(method);
    logger.trace("Converting %s.%s", declaring.getSimpleName(), method.getName());
    Function<Exception, ?> exceptionParser = annotationProcessor
            .createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(method);
    // in case there is an exception creating the request, we should at least
    // pass in args
    if (exceptionParser instanceof InvocationContext) {
        ((InvocationContext) exceptionParser).setContext((HttpRequest) null);
    }/*  w  w w.  j  a  v  a2 s  .  c  o  m*/
    ListenableFuture<?> result;
    try {
        GeneratedHttpRequest<T> request = annotationProcessor.createRequest(method, args);
        if (exceptionParser instanceof InvocationContext) {
            ((InvocationContext) exceptionParser).setContext(request);
        }
        logger.trace("Converted %s.%s to %s", declaring.getSimpleName(), method.getName(),
                request.getRequestLine());

        Function<HttpResponse, ?> transformer = annotationProcessor.createResponseParser(method, request);
        logger.trace("Response from %s.%s is parsed by %s", declaring.getSimpleName(), method.getName(),
                transformer.getClass().getSimpleName());

        logger.debug("Invoking %s.%s", declaring.getSimpleName(), method.getName());
        result = commandFactory.create(request, transformer).execute();

    } catch (RuntimeException e) {
        AuthorizationException aex = Throwables2.getFirstThrowableOfType(e, AuthorizationException.class);
        if (aex != null)
            e = aex;
        if (exceptionParser != null) {
            try {
                return Futures.immediateFuture(exceptionParser.apply(e));
            } catch (Exception ex) {
                return Futures.immediateFailedFuture(ex);
            }
        }
        return Futures.immediateFailedFuture(e);
    }

    if (exceptionParser != null) {
        logger.trace("Exceptions from %s.%s are parsed by %s", declaring.getSimpleName(), method.getName(),
                exceptionParser.getClass().getSimpleName());
        result = new ExceptionParsingListenableFuture(result, exceptionParser);
    }
    return result;
}

From source file:com.orangerhymelabs.helenus.cassandra.table.ViewRepository.java

@Override
public ListenableFuture<View> create(View view) {
    if (createDocumentSchema(view)) {
        // TODO: what about rollback?
        return super.create(view);
    } else {//from   w  ww .  j a  va  2 s . c  om
        return Futures.immediateFailedFuture(
                new StorageException("Failed to create document schema for view: " + view.name()));
    }
}

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

/**
 * Get PureCloud license definition.//from  ww w . j  ava2  s . 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<LicenseDefinition>> getLicenseDefinitionAsync(ApiRequest<Void> request,
        final AsyncApiCallback<ApiResponse<LicenseDefinition>> callback) {
    try {
        final SettableFuture<ApiResponse<LicenseDefinition>> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request, new TypeReference<LicenseDefinition>() {
        }, new AsyncApiCallback<ApiResponse<LicenseDefinition>>() {
            @Override
            public void onCompleted(ApiResponse<LicenseDefinition> response) {
                notifySuccess(future, callback, response);
            }

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

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

@Override
public ListenableFuture<MultipleStreamingGetOut> multipleStreamingGet(final VContext context, ServerCall call,
        final ServerStream<String, Boolean> stream) {
    final SettableFuture<MultipleStreamingGetOut> future = SettableFuture.create();
    final AtomicInteger numSent = new AtomicInteger(0);
    Futures.addCallback(InputChannels.withCallback(stream, new InputChannelCallback<Boolean>() {
        @Override//from  www  .j a  v a2  s . co m
        public ListenableFuture<Void> onNext(Boolean result) {
            if (lastAddedFortune == null) {
                return Futures.immediateFailedFuture(new NoFortunesException(context));
            }
            return Futures.transform(stream.send(lastAddedFortune), new Function<Void, Void>() {
                @Override
                public Void apply(Void input) {
                    numSent.incrementAndGet();
                    return null;
                }
            });
        }
    }), new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            MultipleStreamingGetOut ret = new MultipleStreamingGetOut();
            ret.total = numSent.get();
            ret.another = numSent.get();
            future.set(ret);
        }

        @Override
        public void onFailure(Throwable t) {
            future.setException(t);
        }
    });
    return future;
}