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:brooklyn.entity.nosql.riak.RiakClusterImpl.java

@Override
public void start(Collection<? extends Location> locations) {
    super.start(locations);
    connectSensors();/*from  w  w  w  . java 2  s .  c  om*/

    Time.sleep(getConfig(DELAY_BEFORE_ADVERTISING_CLUSTER));

    //FIXME: add a quorum to tolerate failed nodes before setting on fire.
    Optional<Entity> anyNode = Iterables.tryFind(getMembers(), new Predicate<Entity>() {

        @Override
        public boolean apply(@Nullable Entity entity) {
            return (entity instanceof RiakNode && hasMemberJoinedCluster(entity)
                    && entity.getAttribute(RiakNode.SERVICE_UP));
        }
    });

    if (anyNode.isPresent()) {
        log.info("Planning and Committing cluster changes on node: {}, cluster: {}", anyNode.get().getId(),
                getId());
        Entities.invokeEffector(this, anyNode.get(), RiakNode.COMMIT_RIAK_CLUSTER).blockUntilEnded();
        setAttribute(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:org.eclipse.emf.compare.uml2.internal.provider.profile.StereotypeAttributeChangeProfileSupportItemProvider.java

/**
 * Retrieves the {@link AttributeChange} which is refined by the {@link StereotypeAttributeChange}.
 * /*from w  w w .java 2 s  . c om*/
 * @param diff
 *            Input object. .
 * @return an {@link AttributeChange} if the input is a {@link StereotypeAttributeChange} which is refined
 *         by an {@link AttributeChange} or <code>null</code> otherwise.
 */
private AttributeChange getAttributeChange(Object diff) {
    AttributeChange attributeChange = null;
    if (diff instanceof StereotypeAttributeChange) {
        StereotypeAttributeChange stereotypeAttributeChange = (StereotypeAttributeChange) diff;
        Optional<Diff> element = Iterables.tryFind(stereotypeAttributeChange.getRefinedBy(),
                Predicates.instanceOf(AttributeChange.class));
        if (element.isPresent()) {
            attributeChange = (AttributeChange) element.get();
        }
    }
    return attributeChange;
}

From source file:com.r4intellij.editor.formatting.processor.RIndentProcessor.java

private static boolean continsPipeOp(PsiElement node) {
    boolean hasPipeOp = Iterables.tryFind(PsiTreeUtil.getChildrenOfTypeAsList(node, LeafPsiElement.class),
            new Predicate<LeafPsiElement>() {
                @Override/* w  w  w  .  ja  v a  2  s .c om*/
                public boolean apply(@Nullable LeafPsiElement leafPsiElement) {
                    return leafPsiElement.getElementType().equals(R_ARITH_MISC);
                }
            }).isPresent();

    return hasPipeOp;
}

From source file:com.gradleware.tooling.toolingmodel.repository.internal.HierarchyHelper.java

Optional<T> tryFind(Spec<? super T> predicate) {
    return Iterables.tryFind(getAll(), toPredicate(predicate));
}

From source file:brooklyn.entity.nosql.mongodb.sharding.CoLocatedMongoDBRouterImpl.java

@Override
protected void doStart(Collection<? extends Location> locations) {
    // TODO Changed to create the router child after init as a workaround.
    // When we use `mongo-sharded.yaml`, and we call 
    // `getConfig(CoLocatedMongoDBRouter.SHARDED_DEPLOYMENT)`,
    // the value is `$brooklyn:component("shardeddeployment")`.
    // To look up the component, it tries to do `entity().getApplication()` to
    // search the entities for one with the correct id. However if being done
    // during `init()`, then this (which is returned by `entity()`) has not had its parent
    // set, so `entity().getApplication()` returns null.
    ///*from  www . j  a  va2  s  . com*/
    // We should move this code back to `init()` once we have a solution for that.
    // We can also remove the call to Entities.manage() once this is in init() again.

    MongoDBRouter router = addChild(
            EntitySpec.create(MongoDBRouter.class).configure(MongoDBRouter.CONFIG_SERVERS,
                    DependentConfiguration.attributeWhenReady(
                            getConfig(CoLocatedMongoDBRouter.SHARDED_DEPLOYMENT),
                            MongoDBConfigServerCluster.CONFIG_SERVER_ADDRESSES)));
    Entities.manage(router);
    setAttribute(ROUTER,
            (MongoDBRouter) Iterables.tryFind(getChildren(), Predicates.instanceOf(MongoDBRouter.class)).get());
    addEnricher(Enrichers.builder().propagating(MongoDBRouter.PORT).from(router).build());

    super.doStart(locations);
    setAttribute(Startable.SERVICE_UP, true);
}

From source file:org.apache.brooklyn.entity.nosql.mongodb.sharding.MongoDBRouterClusterImpl.java

protected void setAnyRouter() {
    sensors().set(MongoDBRouterCluster.ANY_ROUTER, Iterables
            .tryFind(getRouters(), EntityPredicates.attributeEqualTo(Startable.SERVICE_UP, true)).orNull());

    sensors().set(MongoDBRouterCluster.ANY_RUNNING_ROUTER, Iterables
            .tryFind(getRouters(), EntityPredicates.attributeEqualTo(MongoDBRouter.RUNNING, true)).orNull());
}

From source file:org.ow2.petals.cloud.manager.commands.iaas.RegisterAccountCommand.java

@Override
protected Object doExecute() throws Exception {

    // check that the input provider exist
    checkNotNull(Iterables.tryFind(providersManager, new Predicate<ProviderManager>() {
        public boolean apply(ProviderManager input) {
            return input.getProviderName().equalsIgnoreCase(type);
        }//w  w w  .j  ava 2s  .com
    }).orNull(), "Can not find the %s provider in the platform, aborting account registration", type);

    Credentials c = new Credentials();
    c.setUsername(username);
    c.setPassword(password);

    Provider provider = new Provider();
    provider.setEndpoint(endpoint);
    provider.setName(name);
    provider.setType(type);
    provider.setCredentials(c);
    this.registryService.create(provider);

    System.out.println("Account has been registered for provider " + type);
    return null;
}

From source file:org.sosy_lab.cpachecker.pcc.strategy.partitioning.FiducciaMattheysesAlgorithm.java

private Optional<Pair<Long, TreeMap<Long, LinkedList<Integer>>>> tryFindBestGainWithNonEmptyBucket(
        final TreeMap<Long, LinkedList<Integer>> bucket) {
    Optional<Long> bestGain = Iterables.tryFind(bucket.descendingKeySet(), new Predicate<Long>() {
        @Override/*w w w  . j  ava2s .  co m*/
        public boolean apply(@Nullable Long pLong) {
            return !bucket.get(pLong).isEmpty();
        }
    });
    if (!bestGain.isPresent()) {
        return Optional.absent();
    }
    return Optional.of(Pair.of(bestGain.get(), bucket));
}

From source file:pt.ist.maidSyncher.domain.activeCollab.ACProject.java

public static ACProject findByName(final String name) {
    checkArgument(StringUtils.isBlank(name) == false, "Name mustn't be blank");
    MaidRoot maidRoot = MaidRoot.getInstance();

    Optional<ACObject> optional = Iterables.tryFind(maidRoot.getAcObjectsSet(), new Predicate<ACObject>() {
        @Override/*  w ww .  j  av  a 2s. com*/
        public boolean apply(ACObject input) {
            if (input instanceof ACProject) {
                ACProject acProject = (ACProject) input;
                return name.equalsIgnoreCase(acProject.getName());
            } else
                return false;
        }
    });
    return (ACProject) (optional.isPresent() ? optional.get() : null);
}

From source file:org.jclouds.vcloud.director.testng.FormatApiResultsListener.java

private String getApi(ITestResult res) {
    Optional<String> found = Iterables.tryFind(Arrays.asList(res.getMethod().getGroups()), Predicates.in(apis));
    return found.isPresent() ? found.get() : "";
}