Example usage for com.google.common.util.concurrent FutureCallback FutureCallback

List of usage examples for com.google.common.util.concurrent FutureCallback FutureCallback

Introduction

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

Prototype

FutureCallback

Source Link

Usage

From source file:c5db.regionserver.RegionServerService.java

@Override
protected void doStart() {
    fiber.start();// w ww.  j  a va  2  s .c  o m

    fiber.execute(() -> {
        // we need the tablet module:
        ListenableFuture<C5Module> f = server.getModule(ModuleType.Tablet);
        Futures.addCallback(f, new FutureCallback<C5Module>() {
            @Override
            public void onSuccess(final C5Module result) {
                tabletModule = (TabletModule) result;
                bootstrap.group(acceptGroup, workerGroup).option(ChannelOption.SO_REUSEADDR, true)
                        .childOption(ChannelOption.TCP_NODELAY, true).channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline p = ch.pipeline();
                                p.addLast("http-server-codec", new HttpServerCodec());
                                p.addLast("http-agg",
                                        new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("websocket-agg",
                                        new WebSocketFrameAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("decoder", new WebsocketProtostuffDecoder("/websocket"));
                                p.addLast("encoder", new WebsocketProtostuffEncoder());
                                p.addLast("handler", new RegionServerHandler(RegionServerService.this));
                            }
                        });

                bootstrap.bind(port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            listenChannel = future.channel();
                            notifyStarted();
                        } else {
                            LOG.error("Unable to find Region Server to {} {}", port, future.cause());
                            notifyFailed(future.cause());
                        }
                    }
                });
            }

            @Override
            public void onFailure(Throwable t) {
                notifyFailed(t);
            }
        }, fiber);
    });
}

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

@Override
public Future<RpcResult<Void>> addPerson(AddPersonInput input) {
    log.info("RPC addPerson : adding person [{}]", input);

    PersonBuilder builder = new PersonBuilder(input);
    final Person person = builder.build();
    final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();

    // Each entry will be identifiable by a unique key, we have to create that identifier
    final InstanceIdentifier.InstanceIdentifierBuilder<Person> personIdBuilder = InstanceIdentifier
            .<People>builder(People.class).child(Person.class, person.getKey());
    final InstanceIdentifier personId = personIdBuilder.build();
    // Place entry in data store tree
    WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
    tx.put(LogicalDatastoreType.CONFIGURATION, personId, person, true);

    Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
        @Override/*from  ww w.  ja  v  a  2  s  . co m*/
        public void onSuccess(final Void result) {
            log.info("RPC addPerson : person added successfully [{}]", person);
            rpcRegistration.registerPath(PersonContext.class, personId);
            log.info("RPC addPerson : routed rpc registered for instance ID [{}]", personId);
            futureResult.set(RpcResultBuilder.<Void>success().build());
        }

        @Override
        public void onFailure(final Throwable t) {
            log.error(String.format("RPC addPerson : person addition failed [%s]", person), t);
            futureResult.set(RpcResultBuilder.<Void>failed()
                    .withError(RpcError.ErrorType.APPLICATION, t.getMessage()).build());
        }
    });
    return futureResult;
}

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

@Override
public OperationFuture<NodeData> getData(String path, Watcher watcher) {
    if (watcher == null) {
        return super.getData(path, null);
    }//  w w w  . jav  a  2 s .c  o  m
    final RewatchOnExpireWatcher wrappedWatcher = new RewatchOnExpireWatcher(this, ActionType.DATA, path,
            watcher);
    OperationFuture<NodeData> result = super.getData(path, wrappedWatcher);
    Futures.addCallback(result, new FutureCallback<NodeData>() {
        @Override
        public void onSuccess(NodeData result) {
            wrappedWatcher.setLastResult(result);
        }

        @Override
        public void onFailure(Throwable t) {
            // No-op
        }
    });
    return result;

}

From source file:io.druid.indexing.overlord.ThreadPoolTaskRunner.java

@Override
public ListenableFuture<TaskStatus> run(final Task task) {
    final TaskToolbox toolbox = toolboxFactory.build(task);
    final ListenableFuture<TaskStatus> statusFuture = exec
            .submit(new ThreadPoolTaskRunnerCallable(task, toolbox));
    final ThreadPoolTaskRunnerWorkItem taskRunnerWorkItem = new ThreadPoolTaskRunnerWorkItem(task,
            statusFuture);//from w  w  w  . ja v  a2 s .  c  o  m
    runningItems.add(taskRunnerWorkItem);
    Futures.addCallback(statusFuture, new FutureCallback<TaskStatus>() {
        @Override
        public void onSuccess(TaskStatus result) {
            runningItems.remove(taskRunnerWorkItem);
        }

        @Override
        public void onFailure(Throwable t) {
            runningItems.remove(taskRunnerWorkItem);
        }
    });

    return statusFuture;
}

From source file:com.microsoft.office365.snippetapp.helpers.DiscoveryController.java

/**
 * Provides information about the service that corresponds to the provided
 * capability./*from   ww w.  j a  v a  2 s.c  om*/
 *
 * @param capability A string that contains the capability of the service that
 *                   is going to be discovered.
 * @return A signal to wait on before continuing execution. The signal contains the
 * ServiceInfo object with extra information about discovered service.
 */
public SettableFuture<ServiceInfo> getServiceInfo(final String capability) {

    final SettableFuture<ServiceInfo> result = SettableFuture.create();

    // First, look in the locally cached services.
    if (mServices != null) {
        boolean serviceFound = false;
        for (ServiceInfo service : mServices) {
            if (service.getcapability().equals(capability)) {
                Log.i(TAG, "getServiceInfo - " + service.getserviceName() + " service for " + capability
                        + " was found in local cached services");
                result.set(service);
                serviceFound = true;
                break;
            }
        }

        if (!serviceFound) {
            NoSuchElementException noSuchElementException = new NoSuchElementException(
                    "The " + capability + " capability was not found in the local cached services.");
            Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage());
            result.setException(noSuchElementException);
        }
    } else { // The services have not been cached yet. Go ask the discovery service.
        AuthenticationController.getInstance().setResourceId(Constants.DISCOVERY_RESOURCE_ID);
        ADALDependencyResolver dependencyResolver = (ADALDependencyResolver) AuthenticationController
                .getInstance().getDependencyResolver();

        DiscoveryClient discoveryClient = new DiscoveryClient(Constants.DISCOVERY_RESOURCE_URL,
                dependencyResolver);

        try {
            ListenableFuture<List<ServiceInfo>> future = discoveryClient.getservices()
                    .select("serviceResourceId,serviceEndpointUri,capability").read();
            Futures.addCallback(future, new FutureCallback<List<ServiceInfo>>() {
                @Override
                public void onSuccess(final List<ServiceInfo> services) {
                    Log.i(TAG, "getServiceInfo - Services discovered\n");
                    // Save the discovered services to serve further requests from the local cache.
                    mServices = services;

                    boolean serviceFound = false;
                    for (ServiceInfo service : services) {
                        if (service.getcapability().equals(capability)) {
                            Log.i(TAG, "getServiceInfo - " + service.getserviceName() + " service for "
                                    + capability + " was found in services retrieved from discovery");
                            result.set(service);
                            serviceFound = true;
                            break;
                        }
                    }

                    if (!serviceFound) {
                        NoSuchElementException noSuchElementException = new NoSuchElementException(
                                "The " + capability + " capability was not found in the user services.");
                        Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage());
                        result.setException(noSuchElementException);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.e(TAG, "getServiceInfo - " + t.getMessage());
                    result.setException(t);
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "getServiceInfo - " + e.getMessage());
            result.setException(e);
        }
    }
    return result;
}

From source file:org.opendaylight.openflowplugin.impl.services.RoleService.java

public Future<BigInteger> getGenerationIdFromDevice(Short version) throws RoleChangeException {
    final NodeId nodeId = deviceContext.getPrimaryConnectionContext().getNodeId();
    LOG.info("getGenerationIdFromDevice called for device:{}", nodeId.getValue());

    // send a dummy no-change role request to get the generation-id of the switch
    final RoleRequestInputBuilder roleRequestInputBuilder = new RoleRequestInputBuilder();
    roleRequestInputBuilder.setRole(toOFJavaRole(OfpRole.NOCHANGE));
    roleRequestInputBuilder.setVersion(version);
    roleRequestInputBuilder.setGenerationId(BigInteger.ZERO);

    final SettableFuture<BigInteger> finalFuture = SettableFuture.create();
    ListenableFuture<RpcResult<RoleRequestOutput>> genIdListenableFuture = handleServiceCall(
            roleRequestInputBuilder);/*from   www. java2  s.c om*/
    Futures.addCallback(genIdListenableFuture, new FutureCallback<RpcResult<RoleRequestOutput>>() {
        @Override
        public void onSuccess(RpcResult<RoleRequestOutput> roleRequestOutputRpcResult) {
            if (roleRequestOutputRpcResult.isSuccessful()) {
                RoleRequestOutput roleRequestOutput = roleRequestOutputRpcResult.getResult();
                if (roleRequestOutput != null) {
                    LOG.debug("roleRequestOutput.getGenerationId()={}", roleRequestOutput.getGenerationId());
                    finalFuture.set(roleRequestOutput.getGenerationId());
                } else {
                    LOG.info("roleRequestOutput is null in getGenerationIdFromDevice");
                    finalFuture.setException(new RoleChangeException(
                            "Exception in getting generationId for device:" + nodeId.getValue()));
                }

            } else {
                LOG.error("getGenerationIdFromDevice RPC error "
                        + roleRequestOutputRpcResult.getErrors().iterator().next().getInfo());

            }

        }

        @Override
        public void onFailure(Throwable throwable) {
            LOG.info("onFailure - getGenerationIdFromDevice RPC error {}", throwable);
            finalFuture.setException(new ExecutionException(throwable));
        }
    });
    return finalFuture;
}

From source file:com.newlandframework.rpc.netty.RpcServerLoader.java

public void load(String serverAddress, RpcSerializeProtocol serializeProtocol) {
    String[] ipAddr = serverAddress.split(RpcServerLoader.DELIMITER);
    if (ipAddr.length == 2) {
        String host = ipAddr[0];//from w  w  w  .  ja v  a 2  s. c o m
        int port = Integer.parseInt(ipAddr[1]);
        final InetSocketAddress remoteAddr = new InetSocketAddress(host, port);

        System.out.printf("[author tangjie] Netty RPC Client start success!\nip:%s\nport:%d\nprotocol:%s\n\n",
                host, port, serializeProtocol);

        ListenableFuture<Boolean> listenableFuture = threadPoolExecutor
                .submit(new MessageSendInitializeTask(eventLoopGroup, remoteAddr, serializeProtocol));

        Futures.addCallback(listenableFuture, new FutureCallback<Boolean>() {
            public void onSuccess(Boolean result) {
                try {
                    lock.lock();

                    if (messageSendHandler == null) {
                        handlerStatus.await();
                    }

                    if (result == Boolean.TRUE && messageSendHandler != null) {
                        connectStatus.signalAll();
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(RpcServerLoader.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    lock.unlock();
                }
            }

            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        }, threadPoolExecutor);
    }
}

From source file:org.opendaylight.atrium.bgprouter.impl.DeviceListener.java

@Override
public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
    Map<InstanceIdentifier<?>, DataObject> createdData = change.getCreatedData();

    for (Map.Entry<InstanceIdentifier<?>, DataObject> entrySet : createdData.entrySet()) {

        InstanceIdentifier<?> iiD = entrySet.getKey();
        final DataObject dataObject = entrySet.getValue();

        if (dataObject instanceof FlowCapableNode) {
            final InstanceIdentifier<Node> path = iiD.firstIdentifierOf(Node.class);

            ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();
            final CheckedFuture<Optional<Node>, ReadFailedException> readFuture = readOnlyTransaction
                    .read(LogicalDatastoreType.OPERATIONAL, path);
            Futures.addCallback(readFuture, new FutureCallback<Optional<Node>>() {
                @Override/*from  w w w  .j a  va  2s  .co m*/
                public void onSuccess(Optional<Node> result) {
                    if (result.isPresent()) {
                        bgpRouter.processNodeAdd(result.get().getId());
                        LOG.info("Node discovered and passed to processNodeAdd : " + result.get().getId());
                    } else {
                        LOG.info("Read succeeded, node doesn't exist: {}", path);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    LOG.info("Failed to read Node: {}", path, t);
                }
            });
        }
    }
}

From source file:org.opendaylight.netconf.topology.singleton.impl.RemoteOperationTxProcessorImpl.java

@Override
public void doSubmit(final ActorRef recipient, final ActorRef sender) {
    currentUser = null;//w w w .  ja v  a2s  .  c  om
    if (writeTx != null) {
        CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTx.submit();
        Futures.addCallback(submitFuture, new FutureCallback<Void>() {
            @Override
            public void onSuccess(Void result) {
                recipient.tell(new SubmitReply(), sender);
            }

            @Override
            public void onFailure(@Nonnull Throwable throwable) {
                recipient.tell(throwable, sender);
            }
        });
    } else {
        recipient.tell(new SubmitFailedReply(), sender);
        LOG.warn("{}: Couldn't submit transaction because it was already closed.", id);
    }
}

From source file:org.apache.flink.batch.connectors.cassandra.CassandraPojoOutputFormat.java

/**
 * Opens a Session to Cassandra and initializes the prepared statement.
 *
 * @param taskNumber The number of the parallel instance.
 *//*from   w  ww . j av  a2  s .c  om*/
@Override
public void open(int taskNumber, int numTasks) {
    this.session = cluster.connect();
    MappingManager mappingManager = new MappingManager(session);
    this.mapper = mappingManager.mapper(outputClass);
    if (mapperOptions != null) {
        Mapper.Option[] optionsArray = mapperOptions.getMapperOptions();
        if (optionsArray != null) {
            mapper.setDefaultSaveOptions(optionsArray);
        }
    }
    this.callback = new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void ignored) {
            onWriteSuccess();
        }

        @Override
        public void onFailure(Throwable t) {
            onWriteFailure(t);
        }
    };
}