Example usage for com.google.common.collect Iterables tryFind

List of usage examples for com.google.common.collect Iterables tryFind

Introduction

In this page you can find the example usage for com.google.common.collect Iterables tryFind.

Prototype

public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns an Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.

Usage

From source file:org.apache.brooklyn.entity.messaging.kafka.KafkaSupport.java

/**
 * Retrieve the next message on the given topic from the {@link KafkaCluster}.
 *//*  www .j ava2 s  .  c  o  m*/
public String getMessage(String topic) {
    ZooKeeperNode zookeeper = cluster.getZooKeeper();
    Optional<Entity> anyBrokerNodeInCluster = Iterables.tryFind(cluster.getCluster().getChildren(),
            Predicates.and(Predicates.instanceOf(KafkaBroker.class),
                    EntityPredicates.attributeEqualTo(KafkaBroker.SERVICE_UP, true)));
    if (anyBrokerNodeInCluster.isPresent()) {
        KafkaBroker broker = (KafkaBroker) anyBrokerNodeInCluster.get();

        Properties props = new Properties();

        props.put("bootstrap.servers",
                format("%s:%d", broker.getAttribute(KafkaBroker.HOSTNAME), broker.getKafkaPort()));
        props.put("zookeeper.connect", format(zookeeper.getHostname(), zookeeper.getZookeeperPort()));
        props.put("group.id", "brooklyn");
        props.put("partition.assignment.strategy", "RoundRobin");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer consumer = new KafkaConsumer(props);

        consumer.subscribe(topic);
        // FIXME unimplemented KafkaConsumer.poll
        //            Object consumerRecords = consumer.poll(Duration.seconds(3).toMilliseconds()).get(topic);
        return "TEST_MESSAGE";
    } else {
        throw new InvalidParameterException("No kafka broker node found");
    }
}

From source file:gg.uhc.githubreleasechecker.ReleaseChecker.java

public UpdateResponse checkForUpdate() throws IOException {
    return new UpdateResponse(installed,
            Iterables.tryFind(ImmutableList.copyOf(queryer.queryReleases()), isNewerThanInstalled).orNull());
}

From source file:net.seedboxer.core.logic.ContentManager.java

private boolean isContentIn(Content content, List<Content> historyContentOfType) {
    Optional<Content> find = Iterables.tryFind(historyContentOfType, Predicates.equalTo(content));
    return find.isPresent();
}

From source file:broadwick.model.Model.java

/**
 * Determine whether or not a parameter exists in the config file.
 * @param name the name of the parameter.
 * @return true if the parameter exists in the config file, false otherwise.
 *///ww w.  j  a v a  2  s . c o m
public final boolean hasParameter(final String name) {
    return Iterables.tryFind(parameters, new Predicate<Parameter>() {
        @Override
        public boolean apply(final Parameter parameter) {
            return name.equals(parameter.getId());
        }
    }).isPresent();
}

From source file:com.google.api.tools.framework.aspects.endpoint.model.EndpointUtil.java

private static Endpoint getEndpointConfig(Model model, final String endpoint) {
    List<Endpoint> endpointConfigs = model.getAttribute(ENDPOINTS_KEY);
    return Iterables.tryFind(endpointConfigs, new Predicate<Endpoint>() {
        @Override/*from  w  w w .  j av a  2s  .co  m*/
        public boolean apply(Endpoint input) {
            return endpoint.equals(input.getName());
        }
    }).orNull();
}

From source file:brooklyn.entity.nosql.couchbase.CouchbaseSyncGatewaySshDriver.java

@Override
public void launch() {
    Entity cbNode = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER);
    Entities.waitForServiceUp(cbNode, Duration.ONE_HOUR);
    DependentConfiguration.waitInTaskForAttributeReady(cbNode, CouchbaseCluster.IS_CLUSTER_INITIALIZED,
            Predicates.equalTo(true));/*  www.j  a  va 2s .co  m*/
    // Even once the bucket has published its API URL, it can still take a couple of seconds for it to become available
    Time.sleep(10 * 1000);
    if (cbNode instanceof CouchbaseCluster) {
        Optional<Entity> cbClusterNode = Iterables.tryFind(cbNode.getAttribute(CouchbaseCluster.GROUP_MEMBERS),
                new Predicate<Entity>() {

                    @Override
                    public boolean apply(@Nullable Entity entity) {
                        // Must either be recognised by a cluster as added, or be the primary node in a cluster of ONE.
                        return entity instanceof CouchbaseNode && (Boolean.TRUE
                                .equals(entity.getAttribute(CouchbaseNode.IS_IN_CLUSTER))
                                || Boolean.TRUE.equals(entity.getAttribute(CouchbaseNode.IS_PRIMARY_NODE)));
                    }
                });
        if (cbClusterNode.isPresent()) {
            cbNode = cbClusterNode.get();
        } else {
            throw new IllegalArgumentException(
                    format("The cluster %s does not contain any suitable Couchbase nodes to connect to..",
                            cbNode.getId()));
        }

    }
    String hostname = cbNode.getAttribute(CouchbaseNode.HOSTNAME);
    String webPort = cbNode.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT).toString();

    String username = cbNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_USERNAME);
    String password = cbNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_PASSWORD);

    String bucketName = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER_BUCKET);
    String pool = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER_POOL);
    String pretty = entity.getConfig(CouchbaseSyncGateway.PRETTY) ? "-pretty" : "";
    String verbose = entity.getConfig(CouchbaseSyncGateway.VERBOSE) ? "-verbose" : "";

    String adminRestApiPort = entity.getConfig(CouchbaseSyncGateway.ADMIN_REST_API_PORT).iterator().next()
            .toString();
    String syncRestApiPort = entity.getConfig(CouchbaseSyncGateway.SYNC_REST_API_PORT).iterator().next()
            .toString();

    String serverWebAdminUrl = format("http://%s:%s@%s:%s", username, password, hostname, webPort);
    String options = format(
            "-url %s -bucket %s -adminInterface 0.0.0.0:%s -interface 0.0.0.0:%s -pool %s %s %s",
            serverWebAdminUrl, bucketName, adminRestApiPort, syncRestApiPort, pool, pretty, verbose);

    newScript(ImmutableMap.of("usePidFile", true), LAUNCHING).body
            .append(format("/opt/couchbase-sync-gateway/bin/sync_gateway %s ", options)
                    + "> out.log 2> err.log < /dev/null &")
            .failOnNonZeroResultCode().execute();
}

From source file:org.killbill.automaton.DefaultStateMachineConfig.java

public LinkStateMachine findLinkStateMachine(final StateMachine srcStateMachine, final State srcState,
        final StateMachine dstStateMachine) throws MissingEntryException {

    try {/*from  ww  w.jav a 2 s . c o  m*/
        return Iterables.tryFind(ImmutableList.<LinkStateMachine>copyOf(linkStateMachines),
                new Predicate<LinkStateMachine>() {
                    @Override
                    public boolean apply(final LinkStateMachine input) {
                        return input.getInitialStateMachine().getName().equals(srcStateMachine.getName())
                                && input.getInitialState().getName().equals(srcState.getName())
                                && input.getFinalStateMachine().getName().equals(dstStateMachine.getName());
                    }
                }).get();
    } catch (IllegalStateException e) {
        throw new MissingEntryException("Missing transition for srcStateMachine " + srcStateMachine.getName()
                + ", srcState = " + srcState.getName() + ", dstStateMachine = " + dstStateMachine.getName(), e);
    }
}

From source file:org.eclipse.rcptt.internal.launching.ExecutionStatus.java

public IStatus getCause(boolean flatten) {
    IStatus cause = Iterables.tryFind(Arrays.asList(getChildren()), IS_FAILED).orNull();
    if (flatten && cause instanceof ExecutionStatus) {
        return ((ExecutionStatus) cause).getCause(flatten);
    }//from  ww w .  j  a  v  a  2  s .  c  om
    return cause;
}

From source file:org.apache.brooklyn.entity.nosql.riak.RiakClusterImpl.java

@Override
protected void doStart() {
    super.doStart();
    connectSensors();/*from  w w  w .j a v a2 s .  c  o  m*/

    try {
        Duration delay = getConfig(DELAY_BEFORE_ADVERTISING_CLUSTER);
        Tasks.setBlockingDetails("Sleeping for " + delay + " before advertising cluster available");
        Time.sleep(delay);
    } finally {
        Tasks.resetBlockingDetails();
    }

    //FIXME: add a quorum to tolerate failed nodes before setting on fire.
    @SuppressWarnings("unchecked")
    Optional<Entity> anyNode = Iterables.tryFind(getMembers(),
            Predicates.and(Predicates.instanceOf(RiakNode.class),
                    EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true),
                    EntityPredicates.attributeEqualTo(RiakNode.SERVICE_UP, true)));
    if (anyNode.isPresent()) {
        sensors().set(IS_CLUSTER_INIT, true);
    } else {
        log.warn("No Riak Nodes are found on the cluster: {}. Initialization Failed", getId());
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
    }
}

From source file:stormy.pythian.core.configuration.PythianToplogyConfiguration.java

public ConnectionConfiguration findConnectionTo(final String componentId, final String streamName) {
    return Iterables.tryFind(connections, new Predicate<ConnectionConfiguration>() {
        public boolean apply(ConnectionConfiguration input) {
            return input.isTo(componentId, streamName);
        }/*from  w  w w  . ja v a2s.  c o  m*/
    }).orNull();
}