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:org.opendaylight.openflowjava.protocol.impl.core.TcpHandler.java

/**
 * Constructor of TCPHandler that listens on selected address and port.
 * @param address listening address of TCPHandler server
 * @param port listening port of TCPHandler server
 *///w  w w . j  av  a 2  s. c  om
public TcpHandler(InetAddress address, int port) {
    this.port = port;
    this.startupAddress = address;
    channelInitializer = new PublishingChannelInitializer();
    isOnlineFuture = SettableFuture.create();
}

From source file:c5db.client.FutureBasedMessageHandler.java

@Override
public ListenableFuture<Response> buffer(final Call request, final Channel channel) {
    SettableFuture<Response> settableFuture = SettableFuture.create();
    futures.put(request.getCommandId(), settableFuture);
    // Keep track of how many outstanding requests we have and limit it.
    ChannelFuture future = channel.write(request);
    future.addListener(objectFuture -> inFlightCalls.decrementAndGet());

    if (inFlightCalls.incrementAndGet() > C5Constants.IN_FLIGHT_CALLS) {
        System.out.println("Backing off:" + C5Constants.IN_FLIGHT_CALLS);
        try {/*w ww .  j av a  2 s. c  o  m*/
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    return settableFuture;
}

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

/**
 * Create a binding event to be published to disruptor. Also prepare the event before publishing by
 * calling prepare methods.//from  ww  w  .  j  a  va  2s. c om
 *
 * @param boundedQueue           Information on the queue bound
 * @param boundMessageRouterName name of message router
 * @param routingKey             binding key
 */
public InboundBindingEvent(QueueInfo boundedQueue, String boundMessageRouterName, String routingKey) {
    this.boundMessageRouterName = boundMessageRouterName;
    this.boundedQueue = boundedQueue;
    this.routingKey = routingKey;
    this.isEventComplete = SettableFuture.create();
}

From source file:io.datakernel.service.ServiceAdapters.java

public static ServiceAdapter<EventloopServer> forEventloopServer() {
    return new ServiceAdapter<EventloopServer>() {
        @Override//from   www. j ava2s  . c  o  m
        public Service toService(final EventloopServer instance, Executor executor) {
            return new Service() {
                @Override
                public ListenableFuture<?> start() {
                    final SettableFuture<?> future = SettableFuture.create();
                    instance.getEventloop().execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                instance.listen();
                                future.set(null);
                            } catch (IOException e) {
                                future.setException(e);
                            }
                        }
                    });
                    return future;
                }

                @Override
                public ListenableFuture<?> stop() {
                    final SettableFuture<?> future = SettableFuture.create();
                    instance.getEventloop().execute(new Runnable() {
                        @Override
                        public void run() {
                            instance.close();
                            future.set(null);
                        }
                    });
                    return future;
                }
            };
        }
    };
}

From source file:org.opendaylight.openflowplugin.impl.role.RoleContextImpl.java

public RoleContextImpl(final DeviceContext deviceContext, final EntityOwnershipService entityOwnershipService,
        final Entity entity) {
    this.entityOwnershipService = Preconditions.checkNotNull(entityOwnershipService);
    this.deviceContext = Preconditions.checkNotNull(deviceContext);
    this.entity = Preconditions.checkNotNull(entity);

    salRoleService = new SalRoleServiceImpl(this, deviceContext);
    initRoleChangeFuture = SettableFuture.create();
}

From source file:com.facebook.buck.rules.AbstractCachingBuildRule.java

protected AbstractCachingBuildRule(Buildable buildable, BuildRuleParams params) {
    super(params);
    this.buildable = Preconditions.checkNotNull(buildable);
    this.hasBuildStarted = new AtomicBoolean(false);
    this.buildRuleResult = SettableFuture.create();
}

From source file:com.microsoft.office365.connect.MailController.java

/**
 * Sends an email message using the Office 365 mail capability from the address of the
 * signed in user./* w  w  w  . j  a v  a  2s. com*/
 * @param emailAddress The recipient email address.
 * @param subject The subject to use in the mail message.
 * @param body The body of the message.
 * @return A signal to wait on before continuing execution. The signal contains
 * a boolean value of true if the operation was successful.
 */
public SettableFuture<Boolean> sendMail(final String emailAddress, final String subject, final String body) {

    if (!isReady()) {
        throw new MissingResourceException(
                "You must set the ServiceResourceId and ServiceEndPointUri before using sendMail",
                "MailController", "ServiceResourceId, ServiceEndPointUri");
    }

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

    try {
        AuthenticationManager.getInstance().setResourceId(mServiceResourceId);
        ADALDependencyResolver dependencyResolver = (ADALDependencyResolver) AuthenticationManager.getInstance()
                .getDependencyResolver();

        OutlookClient mailClient = new OutlookClient(mServiceEndpointUri, dependencyResolver);

        // Prepare the message.
        List<Recipient> recipientList = new ArrayList<>();

        Recipient recipient = new Recipient();
        EmailAddress email = new EmailAddress();
        email.setAddress(emailAddress);
        recipient.setEmailAddress(email);
        recipientList.add(recipient);

        Message messageToSend = new Message();
        messageToSend.setToRecipients(recipientList);

        ItemBody bodyItem = new ItemBody();
        bodyItem.setContentType(BodyType.HTML);
        bodyItem.setContent(body);
        messageToSend.setBody(bodyItem);
        messageToSend.setSubject(subject);

        // Contact the Office 365 service and try to deliver the message.
        ListenableFuture<Integer> mailSent = mailClient.getMe().getOperations().sendMail(messageToSend, true);
        Futures.addCallback(mailSent, new FutureCallback<Integer>() {
            @Override
            public void onSuccess(Integer mailItemId) {
                Log.i(TAG, "sendMail - Email sent");
                result.set(true);
            }

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

From source file:org.opendaylight.mdsal.dom.broker.ShardedDOMReadTransactionAdapter.java

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    checkRunning();/*  w  w  w . j  a v a  2 s.  c  o m*/
    LOG.debug("{}: Invoking read at {}:{}", txIdentifier, store, path);
    final ListenerRegistration<DOMDataTreeListener> reg;
    final SettableFuture<Optional<NormalizedNode<?, ?>>> initialDataTreeChangeFuture = SettableFuture.create();
    try {
        reg = service.registerListener(new ReadShardedListener(initialDataTreeChangeFuture),
                Collections.singleton(new DOMDataTreeIdentifier(store, path)), false, Collections.emptyList());
        registrations.add(reg);
    } catch (final DOMDataTreeLoopException e) {
        // This should not happen, we are not specifying any
        // producers when registering listener
        throw new IllegalStateException("Loop in listener and producers detected", e);
    }

    // After data tree change future is finished, we can close the listener registration
    Futures.addCallback(initialDataTreeChangeFuture, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
        @Override
        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
            reg.close();
        }

        @Override
        public void onFailure(final Throwable throwable) {
            reg.close();
        }
    });

    return Futures.makeChecked(initialDataTreeChangeFuture, ReadFailedException.MAPPER);
}

From source file:edu.umich.si.inteco.minuku.dao.LocationDataRecordDAO.java

@Override
public Future<List<LocationDataRecord>> getAll() throws DAOException {
    final SettableFuture<List<LocationDataRecord>> settableFuture = SettableFuture.create();
    String firebaseUrlForLocation = Constants.getInstance().getFirebaseUrlForLocation();
    Firebase locationListRef = new Firebase(firebaseUrlForLocation).child(myUserEmail)
            .child(new SimpleDateFormat("MMddyyyy").format(new Date()).toString());

    locationListRef.addValueEventListener(new ValueEventListener() {
        @Override//  w  w  w . j ava 2 s.c  om
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, LocationDataRecord> locationListMap = (HashMap<String, LocationDataRecord>) dataSnapshot
                    .getValue();
            List<LocationDataRecord> values = (List) locationListMap.values();
            settableFuture.set(values);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            settableFuture.set(null);
        }
    });
    return settableFuture;
}

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   w  w w .j a  v  a  2  s.  c o  m*/
    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;
}