Example usage for com.google.common.util.concurrent SettableFuture set

List of usage examples for com.google.common.util.concurrent SettableFuture set

Introduction

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

Prototype

@Override
    public boolean set(@Nullable V value) 

Source Link

Usage

From source file:co.cask.cdap.common.zookeeper.ZKExtOperations.java

/**
 * Performs the get and condition set part as described in
 * {@link #updateOrCreate(ZKClient, String, Function, Codec, List)}.
 *//*from   ww w . j av a2s . c om*/
private static <V> void getAndSet(final ZKClient zkClient, final String path,
        final AsyncFunction<V, V> modifier, final Codec<V> codec, final SettableFuture<V> resultFuture,
        final List<ACL> createAcl) {

    // Try to fetch the node data
    Futures.addCallback(zkClient.getData(path), new FutureCallback<NodeData>() {
        @Override
        public void onSuccess(final NodeData result) {
            try {
                // Node has data. Call modifier to get newer version of content
                final int version = result.getStat().getVersion();

                Futures.addCallback(modifier.apply(codec.decode(result.getData())), new FutureCallback<V>() {
                    @Override
                    public void onSuccess(final V content) {
                        // When modifier calls completed, try to set the content

                        // Modifier decided to abort
                        if (content == null) {
                            resultFuture.set(null);
                            return;
                        }
                        try {
                            byte[] data = codec.encode(content);

                            // No change in content. No need to update and simply set the future to complete.
                            if (Arrays.equals(data, result.getData())) {
                                resultFuture.set(content);
                                return;
                            }

                            Futures.addCallback(zkClient.setData(path, data, version),
                                    new FutureCallback<Stat>() {
                                        @Override
                                        public void onSuccess(Stat result) {
                                            resultFuture.set(content);
                                        }

                                        @Override
                                        public void onFailure(Throwable t) {
                                            if (t instanceof KeeperException.BadVersionException) {
                                                // If the version is not good, get and set again
                                                getAndSet(zkClient, path, modifier, codec, resultFuture,
                                                        createAcl);
                                            } else if (t instanceof KeeperException.NoNodeException) {
                                                // If the node not exists, try to do create
                                                createOrGetAndSet(zkClient, path, modifier, codec, resultFuture,
                                                        createAcl);
                                            } else {
                                                resultFuture.setException(t);
                                            }
                                        }
                                    }, Threads.SAME_THREAD_EXECUTOR);
                        } catch (Throwable t) {
                            resultFuture.setException(t);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        resultFuture.setException(t);
                    }
                }, Threads.SAME_THREAD_EXECUTOR);

            } catch (Throwable t) {
                resultFuture.setException(t);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            // If failed to get data because node not exists, try the create.
            if (t instanceof KeeperException.NoNodeException) {
                createOrGetAndSet(zkClient, path, modifier, codec, resultFuture, createAcl);
            } else {
                resultFuture.setException(t);
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:org.opendaylight.controller.clustering.it.provider.impl.PrefixShardHandler.java

public ListenableFuture<RpcResult<Void>> onRemovePrefixShard(final RemovePrefixShardInput input) {

    final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());
    final DistributedShardRegistration registration = registrations.get(identifier);

    if (registration == null) {
        final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "registration-missing",
                "No shard registered at this prefix.");
        return Futures.immediateFuture(RpcResultBuilder.<Void>failed().withRpcError(error).build());
    }//from  ww  w .  j  av a 2  s . c  om

    final SettableFuture<RpcResult<Void>> future = SettableFuture.create();

    final CompletionStage<Void> close = registration.close();
    close.thenRun(() -> future.set(RpcResultBuilder.<Void>success().build()));
    close.exceptionally(throwable -> {
        LOG.warn("Shard[{}] removal failed:", identifier, throwable);

        final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "remove-shard-failed",
                "Shard removal failed", "cluster-test-app", "", throwable);
        future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
        return null;
    });

    return future;
}

From source file:com.google.devtools.build.lib.packages.GlobCache.java

@VisibleForTesting
protected List<String> getGlobUnsorted(String pattern, boolean excludeDirs)
        throws IOException, BadGlobException, InterruptedException {
    Future<List<Path>> futureResult = getGlobUnsortedAsync(pattern, excludeDirs);
    List<Path> globPaths = fromFuture(futureResult);
    // Replace the UnixGlob.GlobFuture with a completed future object, to allow
    // garbage collection of the GlobFuture and GlobVisitor objects.
    if (!(futureResult instanceof SettableFuture<?>)) {
        SettableFuture<List<Path>> completedFuture = SettableFuture.create();
        completedFuture.set(globPaths);
        globCache.put(Pair.of(pattern, excludeDirs), completedFuture);
    }//  w  ww . j av a2  s. c  o m

    List<String> result = Lists.newArrayListWithCapacity(globPaths.size());
    for (Path path : globPaths) {
        String relative = path.relativeTo(packageDirectory).getPathString();
        // Don't permit "" (meaning ".") in the glob expansion, since it's
        // invalid as a label, plus users should say explicitly if they
        // really want to name the package directory.
        if (!relative.isEmpty()) {
            result.add(relative);
        }
    }
    return result;
}

From source file:org.opendaylight.openflowplugin.impl.statistics.StatisticsContextImpl.java

void statChainFuture(final Iterator<MultipartType> iterator, final SettableFuture<Boolean> resultFuture) {
    if (!iterator.hasNext()) {
        resultFuture.set(Boolean.TRUE);
        LOG.debug("Stats collection successfully finished for node {}",
                deviceContext.getDeviceState().getNodeId());
        return;//from  w w w  .  j  a va2s .  co m
    }

    final MultipartType nextType = iterator.next();
    LOG.debug("Stats iterating to next type for node {} of type {}", deviceContext.getDeviceState().getNodeId(),
            nextType);

    final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = chooseStat(nextType);
    Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
        @Override
        public void onSuccess(final Boolean result) {
            statChainFuture(iterator, resultFuture);
        }

        @Override
        public void onFailure(final Throwable t) {
            resultFuture.setException(t);
        }
    });
}

From source file:org.apache.hadoop.hive.ql.exec.tez.SampleTezSessionState.java

@Override
public SettableFuture<WmTezSession> waitForAmRegistryAsync(int timeoutMs,
        ScheduledExecutorService timeoutPool) {
    final SampleTezSessionState session = this;
    final SettableFuture<WmTezSession> future = SettableFuture.create();
    Futures.addCallback(waitForAmRegFuture, new FutureCallback<Boolean>() {
        @Override//from  w  w w  .j a  v  a2s  .  c  o m
        public void onSuccess(Boolean result) {
            future.set(session);
        }

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

From source file:com.navercorp.nbasearc.gcp.GatewayConnectionPool.java

public ListenableFuture<?> delGw(final Integer gwid, final String ip, final int port) {
    synchronized (gwMap) {
        Gateway gw = gwMap.get(gwid);//ww w .jav a2  s. c  o m
        if (gw == null || (!gw.getIp().equals(ip) || gw.getPort() != port)) {
            SettableFuture<?> sf = SettableFuture.create();
            sf.set(null);
            return sf;
        }

        gwMap.remove(gwid);
        updateGatewayList();
        return gw.unuse(vcConcurrentSet);
    }
}

From source file:io.crate.executor.transport.task.elasticsearch.ESCountTask.java

public ESCountTask(ESCountNode node, CrateTransportCountAction transportCountAction) {
    this.transportCountAction = transportCountAction;
    assert node != null;

    final SettableFuture<QueryResult> result = SettableFuture.create();
    results = Arrays.<ListenableFuture<QueryResult>>asList(result);

    String indices[] = node.indices();
    if (node.whereClause().noMatch() || indices.length == 0) {
        result.set(ZERO_RESULT);
    } else {//from   w w  w.j a  v  a 2 s .c  o m
        request = new CountRequest(indices).types(Constants.DEFAULT_MAPPING_TYPE)
                .routing(node.whereClause().clusteredBy().orNull());
        listener = new CountResponseListener(result);
        try {
            request.source(queryBuilder.convert(node.whereClause()), false);
        } catch (IOException e) {
            result.setException(e);
        }
    }
}

From source file:com.google.pubsub.flic.controllers.Controller.java

/**
 * Sends a LoadtestFramework.Start RPC to all clients to commence the load test. When this
 * function returns it is guaranteed that all clients have started.
 *//*  w  w w  .  ja  va2 s  .  c om*/
public void startClients(MessageTracker messageTracker) {
    SettableFuture<Void> startFuture = SettableFuture.create();
    clients.forEach((client) -> executor.execute(() -> {
        try {
            client.start(messageTracker);
            startFuture.set(null);
        } catch (Throwable t) {
            startFuture.setException(t);
        }
    }));
    try {
        startFuture.get();
    } catch (ExecutionException e) {
        shutdown(e.getCause());
    } catch (InterruptedException e) {
        shutdown(e);
    }
}

From source file:com.twitter.heron.statemgr.localfs.LocalFileSystemStateManager.java

@SuppressWarnings("unchecked") // we don't know what M is until runtime
protected <M extends Message> ListenableFuture<M> getData(String path, Message.Builder builder) {
    final SettableFuture<M> future = SettableFuture.create();
    byte[] data = FileUtils.readFromFile(path);
    if (data.length == 0) {
        future.set(null);
        return future;
    }/*from   w w  w  . j a v  a 2  s .  c o  m*/

    try {
        builder.mergeFrom(data);
        future.set((M) builder.build());
    } catch (InvalidProtocolBufferException e) {
        future.setException(new RuntimeException("Could not parse " + Message.Builder.class, e));
    }

    return future;
}

From source file:com.spotify.folsom.client.DefaultRawMemcacheClient.java

public static ListenableFuture<RawMemcacheClient> connect(final HostAndPort address,
        final int outstandingRequestLimit, final boolean binary, final Executor executor,
        final long timeoutMillis, final Charset charset, final Metrics metrics, final int maxSetLength) {

    final ChannelInboundHandler decoder;
    if (binary) {
        decoder = new BinaryMemcacheDecoder();
    } else {//from   w  ww .  j  a v a2 s.  co  m
        decoder = new AsciiMemcacheDecoder(charset);
    }

    final ChannelHandler initializer = new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpTuningHandler(), decoder,

                    // Downstream
                    new MemcacheEncoder());
        }
    };

    final SettableFuture<RawMemcacheClient> clientFuture = SettableFuture.create();

    final Bootstrap bootstrap = new Bootstrap().group(EVENT_LOOP_GROUP).handler(initializer)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, SimpleSizeEstimator.INSTANCE);

    final ChannelFuture connectFuture = bootstrap
            .connect(new InetSocketAddress(address.getHostText(), address.getPort()));

    connectFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Create client
                final RawMemcacheClient client = new DefaultRawMemcacheClient(address, future.channel(),
                        outstandingRequestLimit, executor, timeoutMillis, metrics, maxSetLength);
                clientFuture.set(client);
            } else {
                clientFuture.setException(future.cause());
            }
        }
    });

    return onExecutor(clientFuture, executor);
}