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.killbill.billing.catalog.caching.EhCacheOverriddenPlanCache.java

private PlanPhasePriceOverride[] createOverrides(final Plan defaultPlan,
        final List<CatalogOverridePhaseDefinitionModelDao> phaseDefs) {

    final PlanPhasePriceOverride[] result = new PlanPhasePriceOverride[defaultPlan.getAllPhases().length];

    for (int i = 0; i < defaultPlan.getAllPhases().length; i++) {

        final PlanPhase curPhase = defaultPlan.getAllPhases()[i];
        final CatalogOverridePhaseDefinitionModelDao overriddenPhase = Iterables
                .tryFind(phaseDefs, new Predicate<CatalogOverridePhaseDefinitionModelDao>() {
                    @Override//from w w w . java 2 s .  c om
                    public boolean apply(final CatalogOverridePhaseDefinitionModelDao input) {
                        return input.getParentPhaseName().equals(curPhase.getName());
                    }
                }).orNull();
        result[i] = (overriddenPhase != null)
                ? new DefaultPlanPhasePriceOverride(curPhase.getName(),
                        Currency.valueOf(overriddenPhase.getCurrency()), overriddenPhase.getFixedPrice(),
                        overriddenPhase.getRecurringPrice())
                : null;
    }
    return result;
}

From source file:org.killbill.billing.util.customfield.api.DefaultCustomFieldUserApi.java

@Override
public void addCustomFields(final List<CustomField> customFields, final CallContext context)
        throws CustomFieldApiException {
    // TODO make it transactional

    final Map<UUID, ObjectType> mapping = new HashMap<UUID, ObjectType>();
    for (final CustomField cur : customFields) {
        mapping.put(cur.getObjectId(), cur.getObjectType());
    }//from   ww w .j  av a2  s . co  m

    final List<CustomFieldModelDao> all = new LinkedList<CustomFieldModelDao>();
    for (UUID cur : mapping.keySet()) {
        final ObjectType type = mapping.get(cur);
        all.addAll(customFieldDao.getCustomFieldsForObject(cur, type,
                internalCallContextFactory.createInternalCallContext(cur, type, context)));
    }
    final List<CustomField> toBeInserted = new LinkedList<CustomField>();
    for (final CustomField cur : customFields) {
        final CustomFieldModelDao match = Iterables
                .tryFind(all, new com.google.common.base.Predicate<CustomFieldModelDao>() {
                    @Override
                    public boolean apply(final CustomFieldModelDao input) {
                        return input.getObjectId().equals(cur.getObjectId())
                                && input.getObjectType() == cur.getObjectType()
                                && input.getFieldName().equals(cur.getFieldName());

                    }
                }).orNull();
        if (match != null) {
            throw new CustomFieldApiException(ErrorCode.CUSTOM_FIELD_ALREADY_EXISTS, match.getId());
        }
        toBeInserted.add(cur);
    }

    for (CustomField cur : toBeInserted) {
        customFieldDao.create(
                new CustomFieldModelDao(context.getCreatedDate(), cur.getFieldName(), cur.getFieldValue(),
                        cur.getObjectId(), cur.getObjectType()),
                internalCallContextFactory.createInternalCallContext(cur.getObjectId(), cur.getObjectType(),
                        context));
    }
}

From source file:org.apache.drill.exec.store.text.DrillTextRecordReader.java

@Override
public boolean isStarQuery() {
    return super.isStarQuery() || Iterables.tryFind(getColumns(), new Predicate<SchemaPath>() {
        private final SchemaPath COLUMNS = SchemaPath.getSimplePath("columns");

        @Override/*  ww w . j  a  v  a 2  s. c om*/
        public boolean apply(@Nullable SchemaPath path) {
            return path.equals(COLUMNS);
        }
    }).isPresent();
}

From source file:gobblin.compaction.mapreduce.MRCompactorJobPropCreator.java

protected List<Dataset> createJobProps() throws IOException {

    if (Iterables.tryFind(this.dataset.inputPaths(), new Predicate<Path>() {
        public boolean apply(Path input) {
            try {
                return MRCompactorJobPropCreator.this.fs.exists(input);
            } catch (IOException e) {
                MRCompactorJobPropCreator.LOG
                        .error(String.format("Failed to check if %s exits", new Object[] { input }), e);
            }/*from   w  w  w  .  ja  v  a  2 s. c o  m*/
            return false;
        }
    }).isPresent()) {
        Optional<Dataset> datasetWithJobProps = createJobProps(this.dataset);
        if (datasetWithJobProps.isPresent()) {
            setCompactionSLATimestamp((Dataset) datasetWithJobProps.get());
            return ImmutableList.of(datasetWithJobProps.get());
        }
        return ImmutableList.of();
    }
    LOG.warn("Input folders " + this.dataset.inputPaths() + " do not exist. Skipping dataset " + this.dataset);
    return ImmutableList.of();
}

From source file:org.apache.james.mailbox.inmemory.mail.InMemoryAnnotationMapper.java

private Predicate<MailboxAnnotation> getPredicateFilterByOne(final Set<MailboxAnnotationKey> keys) {
    return new Predicate<MailboxAnnotation>() {
        @Override//from   ww w  . j av  a  2 s . c o  m
        public boolean apply(final MailboxAnnotation input) {
            return Iterables.tryFind(keys, filterAnnotationsByParentKey(input.getKey())).isPresent();
        }
    };
}

From source file:org.zanata.webtrans.client.presenter.SourceContentsPresenter.java

private Optional<HasSelectableSource> tryFindSelectedSourcePanel(List<HasSelectableSource> sourcePanelList) {
    return Iterables.tryFind(sourcePanelList, input -> input == selectedSource);
}

From source file:net.shibboleth.idp.profile.interceptor.impl.PopulateProfileInterceptorContext.java

/** {@inheritDoc} */
@Override/*from   ww  w .ja v  a  2  s .c o  m*/
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final ProfileInterceptorContext interceptorContext) {

    interceptorContext.getAvailableFlows().clear();
    interceptorContext.setAttemptedFlow(null);

    final Collection<String> activeFlows = activeFlowsLookupStrategy.apply(profileRequestContext);
    if (activeFlows != null) {
        for (final String id : activeFlows) {
            final String flowId = ProfileInterceptorFlowDescriptor.FLOW_ID_PREFIX + id;
            final Optional<ProfileInterceptorFlowDescriptor> flow = Iterables.tryFind(availableFlows,
                    new Predicate<ProfileInterceptorFlowDescriptor>() {
                        public boolean apply(ProfileInterceptorFlowDescriptor input) {
                            return input.getId().equals(flowId);
                        }
                    });

            if (flow.isPresent()) {
                log.debug("{} Installing flow {} into interceptor context", getLogPrefix(), flowId);
                interceptorContext.getAvailableFlows().put(flow.get().getId(), flow.get());
            } else {
                log.error("{} Configured interceptor flow {} not available for use", getLogPrefix(), flowId);
                ActionSupport.buildEvent(profileRequestContext, IdPEventIds.INVALID_PROFILE_CONFIG);
                return;
            }
        }
    }
}

From source file:info.magnolia.configuration.app.overview.data.DefinitionRawViewId.java

private String resolveName() {
    String name = super.getName();
    if (name == null && getValue().getKind() == DefinitionRawView.Kind.subBean) {
        final Optional<DefinitionRawView.Property> propertyOptional = Iterables
                .tryFind(tryGetProperties(getValue().getSubRawView()), new NamePropertyPredicate());

        if (propertyOptional.isPresent()) {
            name = propertyOptional.get().getSimpleValue();
        } else {// w  ww.j  ava2 s  . c  o  m
            final Id parent = getParent();
            if (parent instanceof DefinitionRawViewId) {
                final DefinitionRawViewId parentRawViewId = (DefinitionRawViewId) parent;
                if (parentRawViewId.getValue().getKind() == DefinitionRawView.Kind.collection) {
                    final int index = Iterables.indexOf(parentRawViewId.getValue().getCollection(),
                            new IsCurrentRawViewValue());
                    name = Noun.singularOf(parentRawViewId.getName()) + (index + 1);
                }
            }
        }
    }
    return name;
}

From source file:domainapp.dom.menu.Menu.java

@Programmatic
public MenuItem newItem2(final String name, final BigDecimal memberPrice, final Boolean mandatory) {
    if (name == null) {
        return null;
    }//from   www  .ja  v  a  2 s .c  o  m

    final Optional<MenuItem> menuItemIfAny = Iterables.tryFind(getItems(),
            input -> Objects.equal(input.getName(), name));
    if (menuItemIfAny.isPresent()) {
        final MenuItem menuItem = menuItemIfAny.get();
        if (memberPrice != null) {
            menuItem.setMemberPrice(memberPrice);
        }
        if (mandatory != null) {
            menuItem.setMandatory(mandatory);
        }
        return menuItem;
    }

    final MenuItem menuItem = container.newTransientInstance(MenuItem.class);
    menuItem.setMenu(this);
    menuItem.setName(name);
    menuItem.setMemberPrice(memberPrice);
    menuItem.setMandatory(mandatory != null && mandatory);

    container.persistIfNotAlready(menuItem);

    return menuItem;
}

From source file:org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveStatementBase.java

protected final <R> R firstSubstatementOfType(final Class<?> type, final Class<R> returnType) {
    final Optional<? extends EffectiveStatement<?, ?>> possible = Iterables.tryFind(substatements,
            Predicates.and(Predicates.instanceOf(type), Predicates.instanceOf(returnType)));
    return possible.isPresent() ? returnType.cast(possible.get()) : null;
}