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.obm.opush.command.sync.SyncTestUtils.java

public static Optional<CollectionChange> getCollectionWithId(FolderSyncResponse response,
        final CollectionId lookForId) {
    return Iterables.tryFind(response.getCollectionsAddedAndUpdated(), new Predicate<CollectionChange>() {

        @Override/* www  . j a v  a  2s.c  o m*/
        public boolean apply(CollectionChange change) {
            return lookForId.equals(change.getCollectionId());
        }
    });
}

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

protected void onServerPoolMemberChanged(Entity member) {
    synchronized (mutex) {
        log.trace("For {}, considering membership of {} which is in locations {}",
                new Object[] { this, member, member.getLocations() });

        Map<Entity, String> nodes = getAttribute(RIAK_CLUSTER_NODES);
        if (belongsInServerPool(member)) {
            // TODO can we discover the nodes by asking the riak cluster, rather than assuming what we add will be in there?
            // TODO and can we do join as part of node starting?

            if (nodes == null) {
                nodes = Maps.newLinkedHashMap();
            }//w w  w .  ja va2  s . c  o m
            String riakName = getRiakName(member);
            Preconditions.checkNotNull(riakName);

            // flag a first node to be the first node in the riak cluster.
            Boolean firstNode = getAttribute(IS_FIRST_NODE_SET);
            if (!Boolean.TRUE.equals(firstNode)) {
                setAttribute(IS_FIRST_NODE_SET, Boolean.TRUE);

                nodes.put(member, riakName);
                setAttribute(RIAK_CLUSTER_NODES, nodes);

                ((EntityInternal) member).setAttribute(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE);

                log.info("Adding riak node {}: {}; {} to cluster",
                        new Object[] { this, member, getRiakName(member) });
            } else {
                // TODO: be wary of erroneous nodes but are still flagged 'in cluster'
                // add the new node to be part of the riak cluster.
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), new Predicate<Entity>() {
                    @Override
                    public boolean apply(@Nullable Entity node) {
                        return (node instanceof RiakNode && hasMemberJoinedCluster(node));
                    }
                });

                if (anyNodeInCluster.isPresent()) {
                    if (!nodes.containsKey(member) && !hasMemberJoinedCluster(member)) {
                        String anyNodeName = anyNodeInCluster.get().getAttribute(RiakNode.RIAK_NODE_NAME);
                        Entities.invokeEffectorWithArgs(this, member, RiakNode.JOIN_RIAK_CLUSTER, anyNodeName);
                        if (getAttribute(IS_CLUSTER_INIT)) {
                            Entities.invokeEffector(RiakClusterImpl.this, anyNodeInCluster.get(),
                                    RiakNode.COMMIT_RIAK_CLUSTER);
                        }
                        nodes.put(member, riakName);
                        setAttribute(RIAK_CLUSTER_NODES, nodes);
                        log.info("Adding riak node {}: {}; {} to cluster",
                                new Object[] { this, member, getRiakName(member) });
                    }
                } else {
                    log.error("isFirstNodeSet , but no cluster members found to add {}", member.getId());
                }
            }
        } else {
            if (nodes != null && nodes.containsKey(member)) {
                final Entity memberToBeRemoved = member;

                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), new Predicate<Entity>() {
                    @Override
                    public boolean apply(@Nullable Entity node) {
                        return (node instanceof RiakNode && hasMemberJoinedCluster(node)
                                && !node.equals(memberToBeRemoved));
                    }
                });
                if (anyNodeInCluster.isPresent()) {
                    Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), RiakNode.LEAVE_RIAK_CLUSTER,
                            getRiakName(memberToBeRemoved));
                }

                nodes.remove(member);
                setAttribute(RIAK_CLUSTER_NODES, nodes);
                log.info("Removing riak node {}: {}; {} from cluster",
                        new Object[] { this, member, getRiakName(member) });
            }
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, RIAK_CLUSTER_NODES);
        if (log.isTraceEnabled())
            log.trace("Done {} checkEntity {}", this, member);

        calculateClusterAddresses();
    }
}

From source file:com.thinkbiganalytics.feedmgr.service.feed.InMemoryFeedManagerFeedService.java

@Override
public FeedMetadata getFeedByName(final String categoryName, final String feedName) {

    if (feeds != null && !feeds.isEmpty()) {
        return Iterables.tryFind(feeds.values(), new Predicate<FeedMetadata>() {
            @Override/*from ww w . j  a  va  2 s .c o m*/
            public boolean apply(FeedMetadata metadata) {

                return metadata.getFeedName().equalsIgnoreCase(feedName)
                        && metadata.getCategoryName().equalsIgnoreCase(categoryName);
            }
        }).orNull();
    }
    return feeds.get(feedName);
}

From source file:org.calrissian.mango.collect.FluentCloseableIterable.java

/**
 * Returns an {@link com.google.common.base.Optional} containing the first element in this fluent iterable that
 * satisfies the given predicate, if such an element exists.
 *
 * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
 * is matched in this fluent iterable, a {@link NullPointerException} will be thrown.
 *//*from  www .  ja v  a  2  s  . com*/
public final Optional<T> firstMatch(Predicate<? super T> predicate) {
    return Iterables.tryFind(this, predicate);
}

From source file:com.thinkbiganalytics.nifi.rest.model.NifiProcessGroup.java

public List<NiFiComponentErrors> getErrorsForCategory(final String category) {
    if (StringUtils.isBlank(category)) {
        return null;
    }//from   w w w  .j  a  va2s . c o m
    return Lists.newArrayList(Iterables.filter(getErrors(), new Predicate<NiFiComponentErrors>() {
        @Override
        public boolean apply(NiFiComponentErrors nifiProcessorDTO) {
            NifiError error = Iterables
                    .tryFind(nifiProcessorDTO.getValidationErrors(), new Predicate<NifiError>() {
                        @Override
                        public boolean apply(NifiError nifiError) {
                            return category.equalsIgnoreCase(nifiError.getCategory());
                        }
                    }).orNull();
            return error != null;
        }
    }));
}

From source file:com.eucalyptus.auth.euare.persist.DatabasePrincipalProvider.java

@Override
public UserPrincipal lookupPrincipalByAccessKeyId(final String keyId, final String nonce) throws AuthException {
    try (final TransactionResource tx = Entities.readOnlyDistinctTransactionFor(AccessKeyEntity.class)) {
        final UserEntity user;
        try {/*from www.  j  a  v  a 2  s. com*/
            user = (UserEntity) Entities.createCriteria(UserEntity.class).createCriteria("keys")
                    .add(Restrictions.eq("accessKey", keyId)).setFlushMode(FlushMode.MANUAL).setReadOnly(true)
                    .uniqueResult();
        } catch (Exception e) {
            throw new InvalidAccessKeyAuthException("Failed to find access key", e);
        }
        if (user == null) {
            throw new InvalidAccessKeyAuthException("Failed to find access key");
        }
        final UserPrincipal principal = new UserPrincipalImpl(user);
        final Optional<AccessKey> accessKey = Iterables.tryFind(principal.getKeys(),
                CollectionUtils.propertyPredicate(keyId, AccessKeys.accessKeyIdentifier()));
        if (!Iterables.any(accessKey.asSet(), AccessKeys.isActive())) {
            throw new InvalidAccessKeyAuthException("Invalid access key or token");
        }
        return decorateCredentials(principal, nonce, accessKey.get().getSecretKey());
    }
}

From source file:org.apache.brooklyn.util.exceptions.Exceptions.java

/** returns the first exception that matches the filter, or null */
public static Throwable getFirstThrowableMatching(Throwable from, Predicate<? super Throwable> filter) {
    return Iterables.tryFind(getCausalChain(from), filter).orNull();
}

From source file:org.killbill.billing.payment.core.sm.payments.PaymentLeavingStateCallback.java

protected PaymentTransactionModelDao getUnknownPaymentTransaction(
        final List<PaymentTransactionModelDao> existingPaymentTransactions) throws PaymentApiException {
    return Iterables.tryFind(existingPaymentTransactions, new Predicate<PaymentTransactionModelDao>() {
        @Override//from   w  w w.  ja v  a2s.c o  m
        public boolean apply(final PaymentTransactionModelDao input) {
            return input.getTransactionStatus() == TransactionStatus.UNKNOWN;
        }
    }).orNull();
}

From source file:org.ow2.petals.cloud.manager.commands.paas.CreatePaaSCommand.java

/**
 * Get the provider from its name/*  ww w . ja  va 2s.  c  o  m*/
 *
 * @param providerName
 * @return
 * @throws CloudManagerException
 */
protected Provider getProvider(final String providerName) throws CloudManagerException {
    return Iterables.tryFind(providerRegistry.get(), new Predicate<Provider>() {
        public boolean apply(org.ow2.petals.cloud.manager.api.deployment.Provider input) {
            return input.getName() != null && input.getName().equals(providerName);
        }
    }).orNull();
}

From source file:com.thinkbiganalytics.nifi.rest.model.visitor.NifiVisitableProcessor.java

/**
 * Check to see if this processor contains an incoming processor
 *
 * @param parent the processor to check for in this processors {@link #getDestinations()}
 * @return {@code true} if this processor already contains the incoming processor as its destination, {@code false} if not
 *//*from   www  .  java  2 s . co  m*/
public boolean containsDestination(NifiVisitableProcessor parent) {
    final String thisId = getDto().getId();
    final String parentId = parent.getDto().getId();
    NifiVisitableProcessor p = Iterables.tryFind(getDestinations(), new Predicate<NifiVisitableProcessor>() {
        @Override
        public boolean apply(NifiVisitableProcessor nifiVisitableProcessor) {
            return nifiVisitableProcessor.getDto().getId().equalsIgnoreCase(thisId)
                    || nifiVisitableProcessor.getDto().getId().equalsIgnoreCase(parentId);
        }
    }).orNull();
    return p != null;
}