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.cdap.explore.jdbc.MockExploreClient.java

@Override
public ListenableFuture<ExploreExecutionResult> catalogs() {
    SettableFuture<ExploreExecutionResult> futureDelegate = SettableFuture.create();
    futureDelegate.set(new MockExploreExecutionResult(statementsToResults.get("catalogs_stmt").iterator(),
            statementsToMetadata.get("catalogs_stmt")));
    return new MockStatementExecutionFuture(futureDelegate, "catalogs_stmt", statementsToMetadata,
            statementsToResults);/*from w  ww  .  j ava 2 s  . c o  m*/
}

From source file:com.continuuity.loom.common.zookeeper.LeaderElection.java

/**
 * Withdraw from the leader election process asynchronously.
 *
 * @return A {@link ListenableFuture} that will be completed when cancelling is completed.
 *///from w w  w .  j  a v a 2 s .com
public ListenableFuture<?> asyncCancel() {
    final SettableFuture<String> completion = SettableFuture.create();

    // If cancellation already requested/happened, return the future representing that.
    if (!cancelFuture.compareAndSet(null, completion)) {
        return cancelFuture.get();
    }
    executor.execute(new Runnable() {
        @Override
        public void run() {
            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);
            }
        }
    });
    return completion;
}

From source file:org.opendaylight.openflowplugin.openflow.md.util.RoleUtil.java

/**
 * @param sessionContext switch session context
 * @return generationId from future RpcResult
 *//*from  w  w  w .  j  a v a 2  s .  com*/
public static Future<BigInteger> readGenerationIdFromDevice(SessionContext sessionContext) {
    Future<RpcResult<RoleRequestOutput>> roleReply = sendRoleChangeRequest(sessionContext, OfpRole.NOCHANGE,
            BigInteger.ZERO);
    final SettableFuture<BigInteger> result = SettableFuture.create();

    Futures.addCallback(JdkFutureAdapters.listenInPoolThread(roleReply),
            new FutureCallback<RpcResult<RoleRequestOutput>>() {
                @Override
                public void onSuccess(RpcResult<RoleRequestOutput> input) {
                    if (input != null && input.getResult() != null) {
                        result.set(input.getResult().getGenerationId());
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    //TODO
                }
            });
    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.http.MobileServiceConnection.java

/**
 * Execute a request-response operation with a Mobile Service
 *
 * @param request          The request to execute
 * @param responseCallback Callback to invoke after the request is executed
 *//* www  .j a  v a 2s.  c o m*/
public ListenableFuture<ServiceFilterResponse> start(final ServiceFilterRequest request) {
    if (request == null) {
        throw new IllegalArgumentException("Request can not be null");
    }

    ServiceFilter filter = mClient.getServiceFilter();
    // Set the request's headers
    configureHeadersOnRequest(request);
    return filter.handleRequest(request, new NextServiceFilterCallback() {

        @Override
        public ListenableFuture<ServiceFilterResponse> onNext(ServiceFilterRequest request) {
            SettableFuture<ServiceFilterResponse> future = SettableFuture.create();
            ServiceFilterResponse response = null;

            try {
                response = request.execute();
                int statusCode = response.getStatus().getStatusCode();

                // If the response has error throw exception
                if (statusCode < 200 || statusCode >= 300) {
                    String responseContent = response.getContent();
                    if (responseContent != null && !responseContent.trim().equals("")) {
                        throw new MobileServiceException(responseContent, response);
                    } else {
                        throw new MobileServiceException(String.format("{'code': %d}", statusCode), response);
                    }
                }

                future.set(response);
            } catch (MobileServiceException e) {
                future.setException(e);
            } catch (Exception e) {
                future.setException(new MobileServiceException("Error while processing request.", e, response));
            }

            return future;
        }
    });
}

From source file:org.opendaylight.ocpplugin.impl.services.SalObjectLifecycleServiceImpl.java

@Override
public Future<RpcResult<DeleteObjOutput>> deleteObj(final DeleteObjInput input) {
    ListenableFuture<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.DeleteObjOutput>> future = deleteObj
            .handleServiceCall(input);//from  w  w w  .ja  va2s . c  o  m
    final SettableFuture<RpcResult<DeleteObjOutput>> finalFuture = SettableFuture.create();
    Futures.addCallback(future,
            new FutureCallback<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.DeleteObjOutput>>() {
                @Override
                public void onSuccess(
                        final RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.DeleteObjOutput> result) {
                    org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.DeleteObjOutput output = result
                            .getResult();
                    DeleteObjOutputBuilder builder = new DeleteObjOutputBuilder();
                    builder.setResult(output.getResult());
                    RpcResultBuilder<DeleteObjOutput> rpcResultBuilder = RpcResultBuilder.success(builder);
                    finalFuture.set(rpcResultBuilder.build());
                }

                @Override
                public void onFailure(final Throwable t) {
                    RpcResultBuilder<DeleteObjOutput> rpcResultBuilder = RpcResultBuilder.failed();
                    finalFuture.set(rpcResultBuilder.build());
                }
            });

    return finalFuture;
}

From source file:com.github.fhuss.storm.cassandra.executor.AsyncExecutor.java

/**
 * Asynchronously executes the specified batch statement. Inputs will be passed to
 * the {@link #handler} once query succeed or failed.
 *///from w  w w. j a  v a2s  . c o  m
public SettableFuture<T> execAsync(final Statement statement, final T inputs, AsyncResultHandler<T> handler) {
    final SettableFuture<T> settableFuture = SettableFuture.create();
    pending.put(settableFuture, true);
    ResultSetFuture future = session.executeAsync(statement);
    Futures.addCallback(future, new FutureCallback<ResultSet>() {
        public void release() {
            pending.remove(settableFuture);
        }

        @Override
        public void onSuccess(ResultSet result) {
            release();
            settableFuture.set(inputs);
            handler.success(inputs);
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error(String.format("Failed to execute statement '%s' ", statement), t);
            release();
            settableFuture.setException(t);
            handler.failure(t, inputs);
        }
    }, executorService);
    return settableFuture;
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncTable.java

/**
 * Performs a query against the local table and deletes the results.
 *
 * @param query an optional query to filter results
 * @return A ListenableFuture that is done when results have been purged.
 *///from  www . j a  v  a  2  s  . c  om
public ListenableFuture<Void> purge(Query query) {
    ListenableFuture<Void> internalFuture = this.mInternalTable.purge(query);

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

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

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

        @Override
        public void onSuccess(Void value) {
            future.set(value);
        }
    });

    return future;
}

From source file:co.cask.cdap.metrics.runtime.KafkaMetricsProcessorService.java

@Inject
public KafkaMetricsProcessorService(CConfiguration conf, final ZKClientService zkClient,
        DiscoveryService discoveryService, final DiscoveryServiceClient discoveryServiceClient,
        KafkaMetricsProcessorServiceFactory metricsProcessorFactory) {
    this.conf = conf;
    this.metricsProcessorFactory = metricsProcessorFactory;
    this.discoveryService = discoveryService;

    this.election = new LeaderElection(zkClient, SERVICE_NAME, new ElectionHandler() {
        private ResourceCoordinator coordinator;

        @Override//from   ww w .j av a 2  s . c o  m
        public void leader() {
            coordinator = new ResourceCoordinator(zkClient, discoveryServiceClient,
                    new BalancedAssignmentStrategy());
            coordinator.startAndWait();
        }

        @Override
        public void follower() {
            if (coordinator != null) {
                coordinator.stopAndWait();
                coordinator = null;
            }
        }
    });

    this.resourceClient = new ResourceCoordinatorClient(zkClient);
    this.completion = SettableFuture.create();
}

From source file:com.facebook.buck.parser.ParserLeaseVendor.java

private synchronized ListenableFuture<P> obtainParser(Cell cell) {
    Preconditions.checkState(!closed.get());

    Deque<P> parserQueue = parkedParsers.get(cell);
    if (parserQueue != null && !parserQueue.isEmpty()) {
        P parser = Preconditions.checkNotNull(parserQueue.pop());
        return Futures.immediateFuture(parser);
    }//from w  w  w.j ava  2 s .  co m
    Optional<P> possiblyCreated = createIfAllowed(cell);
    if (possiblyCreated.isPresent()) {
        return Futures.immediateFuture(possiblyCreated.get());
    }
    SettableFuture<P> parserFututre = SettableFuture.create();
    Deque<SettableFuture<P>> requestsQueue = parserRequests.get(cell);
    if (requestsQueue == null) {
        requestsQueue = new ArrayDeque<>();
        parserRequests.put(cell, requestsQueue);
    }
    requestsQueue.add(parserFututre);
    return parserFututre;
}

From source file:org.pentaho.di.core.KettleEnvironment.java

public static void init(List<PluginTypeInterface> pluginClasses, boolean simpleJndi) throws KettleException {
    SettableFuture<Boolean> ready;
    if (initialized.compareAndSet(null, ready = SettableFuture.create())) {

        try {/*  w ww .jav  a 2s  .  c o m*/
            // This creates .kettle and kettle.properties...
            //
            if (!KettleClientEnvironment.isInitialized()) {
                KettleClientEnvironment.init();
            }

            // Configure Simple JNDI when we run in stand-alone mode (spoon, pan, kitchen, carte, ... NOT on the platform
            //
            if (simpleJndi) {
                JndiUtil.initJNDI();
            }

            // Register the native types and the plugins for the various plugin types...
            //
            pluginClasses.forEach(PluginRegistry::addPluginType);
            PluginRegistry.init();

            // Also read the list of variables.
            //
            KettleVariablesList.init();

            // Initialize the Lifecycle Listeners
            //
            initLifecycleListeners();
            ready.set(true);
        } catch (Throwable t) {
            ready.setException(t);
            // If it's a KettleException, throw it, otherwise wrap it in a KettleException
            throw ((t instanceof KettleException) ? (KettleException) t : new KettleException(t));
        }

    } else {
        // A different thread is initializing
        ready = initialized.get();
        // Block until environment is initialized
        try {
            ready.get();
        } catch (Throwable t) {
            // If it's a KettleException, throw it, otherwise wrap it in a KettleException
            throw ((t instanceof KettleException) ? (KettleException) t : new KettleException(t));
        }
    }
}