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

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

Introduction

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

Prototype

public static <V> SettableFuture<V> create() 

Source Link

Document

Creates a new SettableFuture that can be completed or cancelled by a later method call.

Usage

From source file:co.cask.tigon.internal.app.runtime.distributed.AbstractServiceTwillRunnable.java

@Override
public void run() {
    runThread = Thread.currentThread();

    LOG.info("Starting runnable {}", name);
    List<ListenableFuture<Service.State>> completions = Lists.newArrayList();
    for (Service service : services) {
        SettableFuture<Service.State> completion = SettableFuture.create();
        service.addListener(createServiceListener(completion), Threads.SAME_THREAD_EXECUTOR);
        completions.add(completion);/*from ww  w  . j a va 2 s. co  m*/
    }

    Services.chainStart(services.get(0), services.subList(1, services.size()).toArray(new Service[0]));
    LOG.info("Runnable started {}", name);

    try {
        Futures.allAsList(completions).get();
    } catch (InterruptedException e) {
        LOG.debug("Waiting on latch interrupted {}", name);
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        LOG.error("Exception in service.", e);
        throw Throwables.propagate(e);
    }

    List<Service> reverse = Lists.reverse(services);
    Services.chainStop(reverse.get(0), reverse.subList(1, reverse.size()).toArray(new Service[0]));

    LOG.info("Runnable stopped {}", name);
}

From source file:com.twitter.heron.statemgr.NullStateManager.java

@Override
public ListenableFuture<PhysicalPlans.PhysicalPlan> getPhysicalPlan(WatchCallback watcher,
        String topologyName) {
    return SettableFuture.create();
}

From source file:co.cask.cdap.data.stream.AbstractStreamCoordinator.java

@Override
public ListenableFuture<Integer> nextGeneration(final StreamConfig streamConfig, final int lowerBound) {
    return Futures.transform(
            propertyStore.get().update(streamConfig.getName(), new PropertyUpdater<StreamProperty>() {
                @Override/*from w ww.ja  v  a 2 s  .c o m*/
                public ListenableFuture<StreamProperty> apply(@Nullable final StreamProperty property) {
                    final SettableFuture<StreamProperty> resultFuture = SettableFuture.create();
                    updateExecutor.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                long currentTTL = (property == null) ? streamConfig.getTTL()
                                        : property.getTTL();
                                int newGeneration = ((property == null) ? lowerBound : property.getGeneration())
                                        + 1;
                                // Create the generation directory
                                Locations.mkdirsIfNotExists(StreamUtils
                                        .createGenerationLocation(streamConfig.getLocation(), newGeneration));
                                resultFuture.set(new StreamProperty(newGeneration, currentTTL));
                            } catch (IOException e) {
                                resultFuture.setException(e);
                            }
                        }
                    });
                    return resultFuture;
                }
            }), new Function<StreamProperty, Integer>() {
                @Override
                public Integer apply(StreamProperty property) {
                    return property.getGeneration();
                }
            });
}

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

public ListenableFuture<Long> execute(DropRepositoryAnalyzedStatement analyzedStatement) {
    final SettableFuture<Long> future = SettableFuture.create();
    final String repoName = analyzedStatement.repositoryName();
    deleteRepositoryAction.execute(new DeleteRepositoryRequest(repoName),
            new ActionListener<DeleteRepositoryResponse>() {
                @Override/*from ww  w . j ava2s. c o m*/
                public void onResponse(DeleteRepositoryResponse deleteRepositoryResponse) {
                    if (!deleteRepositoryResponse.isAcknowledged()) {
                        LOGGER.info("delete repository '{}' not acknowledged", repoName);
                    }
                    future.set(1L);
                }

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

From source file:org.fiware.kiara.transport.tcp.TcpBlockTransportFactory.java

private ListenableFuture<Transport> createTransport(URI uri, Map<String, Object> settings) throws IOException {
    if (uri == null) {
        throw new NullPointerException("uri");
    }/*www.  j av a 2s  .com*/

    final String scheme = uri.getScheme();

    if (!"tcp".equalsIgnoreCase(scheme) && !"tcps".equalsIgnoreCase(scheme)) {
        throw new IllegalArgumentException("URI has neither tcp nor tcps scheme");
    }

    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("tcp".equalsIgnoreCase(scheme)) {
            port = DEFAULT_TCP_PORT;
        } else if ("tcps".equalsIgnoreCase(scheme)) {
            port = DEFAULT_TCPS_PORT;
        }
    }

    // Configure SSL context if necessary.
    final boolean ssl = "tcps".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    final SettableFuture<Transport> onConnectionActive = SettableFuture.create();
    final TcpHandler clientHandler = new TcpHandler(this, uri, null);
    clientHandler.setConnectionListener(new TransportConnectionListener() {

        public void onConnectionOpened(TransportImpl connection) {
            clientHandler.setConnectionListener(null);
            onConnectionActive.set(connection);
        }

        public void onConnectionClosed(TransportImpl connection) {

        }
    });

    Bootstrap b = new Bootstrap();
    b.group(getEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new TcpClientInitializer(sslCtx, clientHandler));
    b.connect(host, port);

    return onConnectionActive;
}

From source file:org.wso2.andes.kernel.disruptor.inbound.InboundQueueEvent.java

/**
 * create an instance of andes queue//from  w  ww . j  a  va 2s . co  m
 *
 * @param queueName   name of the queue
 * @param queueOwner  owner of the queue (virtual host)
 * @param isExclusive is queue exclusive
 * @param isDurable   is queue durable
 */
public InboundQueueEvent(String queueName, boolean isDurable, boolean isShared, String queueOwner,
        boolean isExclusive) {
    this.queueName = queueName;
    this.isDurable = isDurable;
    this.isShared = isShared;
    this.queueOwner = queueOwner;
    this.isExclusive = isExclusive;
    purgedCount = SettableFuture.create();
    isEventComplete = SettableFuture.create();
}

From source file:co.cask.cdap.internal.app.runtime.AbstractProgramController.java

@Override
public final ListenableFuture<ProgramController> resume() {
    if (!state.compareAndSet(State.SUSPENDED, State.RESUMING)) {
        return Futures
                .immediateFailedFuture(new IllegalStateException("Resumption not allowed").fillInStackTrace());
    }//  ww  w  .  ja  v  a  2 s .  co  m
    final SettableFuture<ProgramController> result = SettableFuture.create();
    executor(State.RESUMING).execute(new Runnable() {
        @Override
        public void run() {
            try {
                caller.resuming();
                doResume();
                state.set(State.ALIVE);
                result.set(AbstractProgramController.this);
                caller.alive();
            } catch (Throwable t) {
                error(t, result);
            }
        }
    });
    return result;
}

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

@Override
public ListenableFuture<Integer> streamingGet(final VContext context, ServerCall call,
        final ServerStream<String, Boolean> stream) {
    final SettableFuture<Integer> future = SettableFuture.create();
    final AtomicInteger numSent = new AtomicInteger(0);
    Futures.addCallback(InputChannels.withCallback(stream, new InputChannelCallback<Boolean>() {
        @Override//from   ww  w . ja v  a2  s  . com
        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) {
            future.set(numSent.get());
        }

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

From source file:org.apache.twill.internal.zookeeper.LeaderElection.java

@Override
protected void doStop() {
    final SettableFuture<String> completion = SettableFuture.create();
    Futures.addCallback(completion, new FutureCallback<String>() {
        @Override/*from   ww w . j a  v  a  2  s .  c  om*/
        public void onSuccess(String result) {
            try {
                notifyStopped();
            } finally {
                executor.shutdown();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            try {
                notifyFailed(t);
            } finally {
                executor.shutdown();
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);

    executor.execute(new Runnable() {
        @Override
        public void run() {
            if (watcherCancellable != null) {
                watcherCancellable.cancel();
            }
            if (state != State.CANCELLED) {
                // becomeFollower has to be called before deleting node to make sure no two active leader.
                if (state == State.LEADER) {
                    becomeFollower();
                }
                state = State.CANCELLED;
                doDeleteNode(completion);
            }
        }
    });
}

From source file:com.google.pubsub.clients.vtk.CPSPublisherTask.java

@Override
public ListenableFuture<RunResult> doRun() {
    List<PubsubMessage> messages = new ArrayList<>(batchSize);
    String sendTime = String.valueOf(System.currentTimeMillis());
    for (int i = 0; i < batchSize; i++) {
        messages.add(PubsubMessage.newBuilder().setData(payload).putAttributes("sendTime", sendTime)
                .putAttributes("clientId", id.toString())
                .putAttributes("sequenceNumber", Integer.toString(sequenceNumber.getAndIncrement())).build());
    }//  w ww  .  java  2 s.c om
    PublishRequest request = PublishRequest.newBuilder().setTopic(topic).addAllMessages(messages).build();
    SettableFuture<RunResult> result = SettableFuture.create();
    publisherApi.publishCallable().futureCall(request).addCallback(new RpcFutureCallback<PublishResponse>() {
        @Override
        public void onSuccess(PublishResponse s) {
            result.set(RunResult.fromBatchSize(batchSize));
        }

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