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

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

Introduction

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

Prototype

@GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
@CheckReturnValue
public static <V, X extends Throwable> ListenableFuture<V> catching(ListenableFuture<? extends V> input,
        Class<X> exceptionType, Function<? super X, ? extends V> fallback) 

Source Link

Document

Returns a Future whose result is taken from the given primary input or, if the primary input fails with the given exceptionType , from the result provided by the fallback .

Usage

From source file:com.linkedin.pinot.server.request.ScheduledRequestHandler.java

@Override
public ListenableFuture<byte[]> processRequest(ChannelHandlerContext channelHandlerContext, ByteBuf request) {
    final long queryStartTime = System.nanoTime();
    serverMetrics.addMeteredGlobalValue(ServerMeter.QUERIES, 1);

    LOGGER.debug("Processing request : {}", request);

    byte[] byteArray = new byte[request.readableBytes()];
    request.readBytes(byteArray);/*  ww w  .  java2  s  .c  o m*/
    SerDe serDe = new SerDe(new TCompactProtocol.Factory());
    final InstanceRequest instanceRequest = new InstanceRequest();

    if (!serDe.deserialize(instanceRequest, byteArray)) {
        LOGGER.error("Failed to deserialize query request from broker ip: {}",
                ((InetSocketAddress) channelHandlerContext.channel().remoteAddress()).getAddress()
                        .getHostAddress());
        DataTable result = new DataTable();
        result.addException(QueryException.INTERNAL_ERROR);
        serverMetrics.addMeteredGlobalValue(ServerMeter.REQUEST_DESERIALIZATION_EXCEPTIONS, 1);
        return Futures.immediateFuture(serializeDataTable(null, serverMetrics, result, queryStartTime));
    }
    long deserializationEndTime = System.nanoTime();
    final BrokerRequest brokerRequest = instanceRequest.getQuery();
    serverMetrics.addPhaseTiming(brokerRequest, ServerQueryPhase.REQUEST_DESERIALIZATION,
            deserializationEndTime - queryStartTime);
    LOGGER.debug("Processing requestId:{},request={}", instanceRequest.getRequestId(), instanceRequest);
    final QueryRequest queryRequest = new QueryRequest(instanceRequest);
    String brokerId = instanceRequest.isSetBrokerId() ? instanceRequest.getBrokerId()
            : ((InetSocketAddress) channelHandlerContext.channel().remoteAddress()).getAddress()
                    .getHostAddress();
    // we will set the ip address as client id. This is good enough for start.
    // Ideally, broker should send it's identity as part of the request
    queryRequest.setClientId(brokerId);

    final long schedulerSubmitTime = System.nanoTime();
    ListenableFuture<DataTable> queryTask = queryScheduler.submit(queryRequest);

    // following future will provide default response in case of uncaught
    // exceptions from query processing
    ListenableFuture<DataTable> queryResponse = Futures.catching(queryTask, Throwable.class,
            new Function<Throwable, DataTable>() {
                @Nullable
                @Override
                public DataTable apply(@Nullable Throwable input) {
                    // this is called iff queryTask fails with unhandled exception
                    serverMetrics.addMeteredGlobalValue(ServerMeter.UNCAUGHT_EXCEPTIONS, 1);
                    DataTable result = new DataTable();
                    result.addException(QueryException.INTERNAL_ERROR);
                    return result;
                }
            });

    // transform the DataTable to serialized byte[] to send back to broker
    ListenableFuture<byte[]> serializedQueryResponse = Futures.transform(queryResponse,
            new Function<DataTable, byte[]>() {
                @Nullable
                @Override
                public byte[] apply(@Nullable DataTable instanceResponse) {
                    long totalNanos = System.nanoTime() - schedulerSubmitTime;
                    serverMetrics.addPhaseTiming(brokerRequest, ServerQueryPhase.QUERY_PROCESSING, totalNanos);
                    return serializeDataTable(instanceRequest, serverMetrics, instanceResponse, queryStartTime);
                }
            });

    return serializedQueryResponse;
}

From source file:com.google.cloud.logging.spi.DefaultLoggingRpc.java

private static <V> Future<V> translate(ListenableFuture<V> from, final boolean idempotent,
        int... returnNullOn) {
    final Set<Integer> returnNullOnSet = Sets.newHashSetWithExpectedSize(returnNullOn.length);
    for (int value : returnNullOn) {
        returnNullOnSet.add(value);/*from  www.  java 2  s.c  om*/
    }
    return Futures.catching(from, ApiException.class, new Function<ApiException, V>() {
        @Override
        public V apply(ApiException exception) {
            if (returnNullOnSet.contains(exception.getStatusCode().value())) {
                return null;
            }
            throw new LoggingException(exception, idempotent);
        }
    });
}

From source file:com.google.cloud.pubsub.spi.DefaultPubSubRpc.java

private static <V> ListenableFuture<V> translate(ListenableFuture<V> from, final boolean idempotent,
        int... returnNullOn) {
    final Set<Integer> returnNullOnSet = Sets.newHashSetWithExpectedSize(returnNullOn.length);
    for (int value : returnNullOn) {
        returnNullOnSet.add(value);/*from  ww w  .  j a  va2  s  .  co  m*/
    }
    return Futures.catching(from, ApiException.class, new Function<ApiException, V>() {
        @Override
        public V apply(ApiException exception) {
            if (returnNullOnSet.contains(exception.getStatusCode().value())) {
                return null;
            }
            throw new PubSubException(exception, idempotent);
        }
    });
}