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:com.eucalyptus.auth.euare.identity.region.RegionConfigurationManager.java

/**
 * Get the region information for the local region (if any)
 *
 * @return The optional region information
 *///  ww w .  j a  v a2  s. c o m
public Optional<RegionInfo> getRegionInfoByHost(final String host) {
    final Optional<RegionConfiguration> regionConfigurationOptional = regionConfigurationSupplier.get();
    return Iterables
            .tryFind(Iterables.concat(regionConfigurationOptional.asSet()),
                    propertyContainsPredicate(host, RegionServiceHostTransform.INSTANCE))
            .transform(regionToRegionInfoTransform(regionConfigurationOptional));
}

From source file:module.siadap.domain.SiadapYearConfiguration.java

public static SiadapYearConfiguration getSiadapYearConfiguration(final String chosenYearConfigurationLabel) {
    if (StringUtils.isBlank(chosenYearConfigurationLabel)) {
        return null;
    }/*from w w  w. j  ava 2 s.  co  m*/
    return Iterables.tryFind(SiadapRootModule.getInstance().getYearConfigurations(),
            new Predicate<SiadapYearConfiguration>() {
                @Override
                public boolean apply(SiadapYearConfiguration siadapYearConfiguration) {
                    if (siadapYearConfiguration == null) {
                        return false;
                    }
                    return siadapYearConfiguration.getLabel().equals(chosenYearConfigurationLabel);
                }
            }).orNull();
}

From source file:org.killbill.billing.invoice.tree.AccountItemTree.java

private InvoiceItem getLinkedInvoiceItem(final InvoiceItem item, final Iterable<InvoiceItem> allItems) {
    return Iterables.tryFind(allItems, new Predicate<InvoiceItem>() {
        @Override/*from  ww w.j a  v a2 s  . co m*/
        public boolean apply(final InvoiceItem input) {
            return input.getId().equals(item.getLinkedItemId());
        }
    }).orNull();
}

From source file:org.jmingo.JMingoTemplate.java

/**
 * Gets index by name.//w  w w .  j a  v a  2 s .c o m
 *
 * @param collectionName the collection name
 * @param indexName      the index name
 * @return index or null if no indexes for the given name
 */
public DBObject getIndex(String collectionName, final String indexName) {
    DBObject index;
    Validate.notBlank(collectionName, "collectionName cannot be null or empty");
    Validate.notBlank(collectionName, "indexName cannot be null or empty");
    DBCollection dbCollection = mongoDBFactory.getDB().getCollection(collectionName);
    List<DBObject> dbObjects = dbCollection.getIndexInfo();
    index = Iterables
            .tryFind(dbObjects,
                    dbObject -> StringUtils.equalsIgnoreCase(dbObject.get("name").toString(), indexName))
            .orNull();
    return index;
}

From source file:org.killbill.billing.plugin.analytics.dao.factory.BusinessBundleFactory.java

private BusinessBundleModelDao buildBBS(final BusinessContextFactory businessContextFactory,
        final Account account, final AuditLog creationAuditLog, final Long accountRecordId,
        final Map<UUID, SubscriptionBundle> bundles, final BusinessSubscriptionTransitionModelDao bst,
        final Integer bundleAccountRank, final CurrencyConverter currencyConverter, final Long tenantRecordId,
        final ReportGroup reportGroup) throws AnalyticsRefreshException {
    final SubscriptionBundle bundle = bundles.get(bst.getBundleId());
    final Long bundleRecordId = businessContextFactory.getBundleRecordId(bundle.getId());
    final Boolean latestForBundleExternalKey = businessContextFactory
            .getLatestSubscriptionBundleForExternalKey(bundle.getExternalKey()).getId().equals(bundle.getId());

    LocalDate chargedThroughDate = null;
    final Optional<Subscription> base = Iterables.tryFind(bundle.getSubscriptions(),
            new Predicate<Subscription>() {
                @Override/*from   www .  j  a va 2s .c o  m*/
                public boolean apply(final Subscription subscription) {
                    return ProductCategory.BASE.equals(subscription.getLastActiveProductCategory());
                }
            });
    if (base.isPresent()) {
        chargedThroughDate = base.get().getChargedThroughDate();
    }

    return new BusinessBundleModelDao(account, accountRecordId, bundle, bundleRecordId, bundleAccountRank,
            latestForBundleExternalKey, chargedThroughDate, bst, currencyConverter, creationAuditLog,
            tenantRecordId, reportGroup);
}

From source file:org.opensaml.saml.common.profile.logic.EntityAttributesPredicate.java

/** {@inheritDoc} */
@Override//  w  ww. j  a  va2 s.c  om
public boolean apply(@Nullable final EntityDescriptor input) {
    if (input == null) {
        return false;
    }

    Collection<Attribute> entityAttributes = null;

    // Check for a tag match in the EntityAttributes extension of the entity and its parent(s).
    Extensions exts = input.getExtensions();
    if (exts != null) {
        final List<XMLObject> children = exts.getUnknownXMLObjects(EntityAttributes.DEFAULT_ELEMENT_NAME);
        if (!children.isEmpty() && children.get(0) instanceof EntityAttributes) {
            if (entityAttributes == null) {
                entityAttributes = new ArrayList<>();
            }
            entityAttributes.addAll(((EntityAttributes) children.get(0)).getAttributes());
        }
    }

    EntitiesDescriptor group = (EntitiesDescriptor) input.getParent();
    while (group != null) {
        exts = group.getExtensions();
        if (exts != null) {
            final List<XMLObject> children = exts.getUnknownXMLObjects(EntityAttributes.DEFAULT_ELEMENT_NAME);
            if (!children.isEmpty() && children.get(0) instanceof EntityAttributes) {
                if (entityAttributes == null) {
                    entityAttributes = new ArrayList<>();
                }
                entityAttributes.addAll(((EntityAttributes) children.get(0)).getAttributes());
            }
        }
        group = (EntitiesDescriptor) group.getParent();
    }

    if (entityAttributes == null || entityAttributes.isEmpty()) {
        log.debug("no EntityAttributes extension found for {}", input.getEntityID());
        return false;
    }

    // If we find a matching tag, we win. Each tag is treated in OR fashion.
    final EntityAttributesMatcher matcher = new EntityAttributesMatcher(entityAttributes);

    if (matchAll) {
        return Iterables.all(candidateSet, matcher);
    } else {
        if (Iterables.tryFind(candidateSet, matcher).isPresent()) {
            return true;
        }
    }

    return false;
}

From source file:org.obm.push.mail.imap.LinagoraMailboxService.java

@Override
public Optional<MailboxFolder> getFolder(UserDataRequest udr, MailboxPath path) throws MailException {
    try {/* w ww . j a va2 s  .  c  o m*/
        ListResult listFolders = imapClientProvider.getImapClient(udr).listAll(NO_REFERENCE_NAME,
                path.getPath());

        return Iterables.tryFind(mailboxFolders(listFolders), Predicates.alwaysTrue());
    } catch (OpushLocatorException | IMAPException e) {
        throw new MailException(e);
    } catch (ImapTimeoutException e) {
        throw new TimeoutException(e);
    }
}

From source file:org.opensaml.storage.impl.client.LoadClientStorageServices.java

/**
 * Load the specified storage service from a cookie.
 * //w  ww.j av  a2 s . c  om
 * @param storageService service to load
 * @param source source to apply to load operation
 */
private void loadFromCookie(@Nonnull final ClientStorageService storageService,
        @Nonnull final ClientStorageSource source) {

    Optional<Cookie> cookie = Optional.absent();

    // Search for our cookie.
    final Cookie[] cookies = getHttpServletRequest().getCookies();
    if (cookies != null) {
        cookie = Iterables.tryFind(Arrays.asList(cookies), new Predicate<Cookie>() {
            public boolean apply(@Nullable final Cookie c) {
                return c != null && c.getName().equals(storageService.getStorageName());
            }
        });
    }

    if (!cookie.isPresent() || cookie.get().getValue() == null || cookie.get().getValue().isEmpty()) {
        log.debug("{} No cookie data present, initializing StorageService '{}' to empty state", getLogPrefix(),
                storageService.getId());
        storageService.load(null, source);
    } else {
        log.debug("{} Initializing StorageService '{}' from cookie", getLogPrefix(), storageService.getId());
        storageService.load(URISupport.doURLDecode(cookie.get().getValue()), source);
    }
}

From source file:org.ow2.play.governance.platform.user.service.PermissionCheck.java

/**
 * Get all the groups where the resource is available in a given mode
 *
 * @param resource//from   w w  w  .j ava  2 s . c om
 * @param mode
 * @return
 */
public Set<String> getGroupsForResourceInMode(final String resource, final String mode) {
    if (resource == null || mode == null) {
        return Sets.newHashSet();
    }

    Set<String> result = Sets.newHashSet();

    // get all the permissions where the access is defined for this resource
    // ie the permission is defined for the given resource
    List<MetaResource> permissions = null;
    try {
        permissions = permissionService.getWhereAccessTo(resource);
    } catch (GovernanceExeption e) {
        e.printStackTrace();
        return result;
    }

    if (permissions == null) {
        return result;
    }

    // get all the permissions where the mode is set like the input one
    Iterable<MetaResource> permissionsWhereModeIsOK = Iterables.filter(permissions,
            new Predicate<MetaResource>() {
                @Override
                public boolean apply(MetaResource input) {

                    // get the mode metadata
                    Metadata md = Iterables.tryFind(input.getMetadata(), new Predicate<Metadata>() {
                        @Override
                        public boolean apply(org.ow2.play.metadata.api.Metadata input) {
                            return input.getName().equals(Constants.MODE);
                        }
                    }).orNull();

                    if (md == null) {
                        return false;
                    }

                    // found a mode metadata, let's check the mode value is the input one
                    Data found = Iterables.tryFind(md.getData(), new Predicate<Data>() {
                        @Override
                        public boolean apply(Data input) {
                            return Type.URI.equals(input.getType()) && mode.equals(input.getValue());
                        }
                    }).orNull();

                    if (found != null) {
                        return true;
                    }
                    return false;
                }
            });

    // we now have all the permissions where the resource and mode are like the input one:
    // extract the groups from them (ie agent metadata)
    Iterable<Set<String>> groupss = Iterables.transform(permissionsWhereModeIsOK,
            new Function<MetaResource, Set<String>>() {
                public Set<String> apply(MetaResource input) {

                    Set<String> result = Sets.newHashSet();

                    // first time we extract all permissions where the agent is set
                    Metadata md = Iterables.tryFind(input.getMetadata(), new Predicate<Metadata>() {
                        @Override
                        public boolean apply(org.ow2.play.metadata.api.Metadata input) {
                            return input.getName().equals(Constants.AGENT);
                        }
                    }).orNull();

                    if (md == null) {
                        return result;
                    }

                    Iterable<Data> all = Iterables.filter(md.getData(), new Predicate<Data>() {
                        @Override
                        public boolean apply(org.ow2.play.metadata.api.Data input) {
                            return input != null && input.getValue() != null
                                    && input.getValue().endsWith("#group");
                        }
                    });

                    result = Sets.newHashSet(Iterables.transform(all, new Function<Data, String>() {
                        @Override
                        public String apply(org.ow2.play.metadata.api.Data input) {
                            return input.getValue();
                        }
                    }));

                    return result;
                };
            });

    // change the set of set<string> into set<string> (eliminate duplicates)
    Iterator<Set<String>> iter = groupss.iterator();
    while (iter.hasNext()) {
        Iterables.addAll(result, iter.next());
    }
    return result;
}

From source file:org.apache.gobblin.data.management.conversion.hive.publisher.HiveConvertPublisher.java

@Override
public void publishData(Collection<? extends WorkUnitState> states) throws IOException {

    Set<String> cleanUpQueries = Sets.newLinkedHashSet();
    Set<String> publishQueries = Sets.newLinkedHashSet();
    List<String> directoriesToDelete = Lists.newArrayList();

    try {/*ww w.  j a v  a  2  s. c  om*/
        if (Iterables.tryFind(states, UNSUCCESSFUL_WORKUNIT).isPresent()) {
            /////////////////////////////////////////
            // Prepare cleanup and ignore publish
            /////////////////////////////////////////
            for (WorkUnitState wus : states) {
                QueryBasedHivePublishEntity publishEntity = HiveAvroORCQueryGenerator
                        .deserializePublishCommands(wus);

                // Add cleanup commands - to be executed later
                if (publishEntity.getCleanupQueries() != null) {
                    cleanUpQueries.addAll(publishEntity.getCleanupQueries());
                }

                if (publishEntity.getCleanupDirectories() != null) {
                    directoriesToDelete.addAll(publishEntity.getCleanupDirectories());
                }

                EventWorkunitUtils.setBeginPublishDDLExecuteTimeMetadata(wus, System.currentTimeMillis());
                wus.setWorkingState(WorkingState.FAILED);
                if (!wus.getPropAsBoolean(PartitionLevelWatermarker.IS_WATERMARK_WORKUNIT_KEY)) {
                    try {
                        new SlaEventSubmitter(eventSubmitter, EventConstants.CONVERSION_FAILED_EVENT,
                                wus.getProperties()).submit();
                    } catch (Exception e) {
                        log.error("Failed while emitting SLA event, but ignoring and moving forward to curate "
                                + "all clean up comamnds", e);
                    }
                }
            }
        } else {
            /////////////////////////////////////////
            // Prepare publish and cleanup commands
            /////////////////////////////////////////
            for (WorkUnitState wus : PARTITION_PUBLISH_ORDERING.sortedCopy(states)) {
                QueryBasedHivePublishEntity publishEntity = HiveAvroORCQueryGenerator
                        .deserializePublishCommands(wus);

                // Add cleanup commands - to be executed later
                if (publishEntity.getCleanupQueries() != null) {
                    cleanUpQueries.addAll(publishEntity.getCleanupQueries());
                }

                if (publishEntity.getCleanupDirectories() != null) {
                    directoriesToDelete.addAll(publishEntity.getCleanupDirectories());
                }

                if (publishEntity.getPublishDirectories() != null) {
                    // Publish snapshot / partition directories
                    Map<String, String> publishDirectories = publishEntity.getPublishDirectories();
                    for (Map.Entry<String, String> publishDir : publishDirectories.entrySet()) {
                        moveDirectory(publishDir.getKey(), publishDir.getValue());
                    }
                }

                if (publishEntity.getPublishQueries() != null) {
                    publishQueries.addAll(publishEntity.getPublishQueries());
                }
            }

            /////////////////////////////////////////
            // Core publish
            /////////////////////////////////////////

            // Update publish start timestamp on all workunits
            for (WorkUnitState wus : PARTITION_PUBLISH_ORDERING.sortedCopy(states)) {
                if (HiveAvroORCQueryGenerator.deserializePublishCommands(wus).getPublishQueries() != null) {
                    EventWorkunitUtils.setBeginPublishDDLExecuteTimeMetadata(wus, System.currentTimeMillis());
                }
            }

            // Actual publish: Register snapshot / partition
            executeQueries(Lists.newArrayList(publishQueries));

            // Update publish completion timestamp on all workunits
            for (WorkUnitState wus : PARTITION_PUBLISH_ORDERING.sortedCopy(states)) {
                if (HiveAvroORCQueryGenerator.deserializePublishCommands(wus).getPublishQueries() != null) {
                    EventWorkunitUtils.setEndPublishDDLExecuteTimeMetadata(wus, System.currentTimeMillis());
                }

                wus.setWorkingState(WorkingState.COMMITTED);
                this.watermarker.setActualHighWatermark(wus);

                // Emit an SLA event for conversion successful
                if (!wus.getPropAsBoolean(PartitionLevelWatermarker.IS_WATERMARK_WORKUNIT_KEY)) {
                    EventWorkunitUtils.setIsFirstPublishMetadata(wus);
                    try {
                        new SlaEventSubmitter(eventSubmitter, EventConstants.CONVERSION_SUCCESSFUL_SLA_EVENT,
                                wus.getProperties()).submit();
                    } catch (Exception e) {
                        log.error("Failed while emitting SLA event, but ignoring and moving forward to curate "
                                + "all clean up commands", e);
                    }
                    if (LineageUtils.shouldSetLineageInfo(wus)) {
                        setDestLineageInfo(wus, this.lineageInfo);
                    }
                }
            }
        }
    } finally {
        /////////////////////////////////////////
        // Preserving partition params
        /////////////////////////////////////////
        preservePartitionParams(states);

        /////////////////////////////////////////
        // Post publish cleanup
        /////////////////////////////////////////

        // Execute cleanup commands
        try {
            executeQueries(Lists.newArrayList(cleanUpQueries));
        } catch (Exception e) {
            log.error("Failed to cleanup staging entities in Hive metastore.", e);
        }
        try {
            deleteDirectories(directoriesToDelete);
        } catch (Exception e) {
            log.error("Failed to cleanup staging directories.", e);
        }
    }
}