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.automaton.DefaultStateMachine.java

public DefaultTransition findTransition(final State initialState, final Operation operation,
        final OperationResult operationResult) throws MissingEntryException {
    try {/*  www. j a va  2 s . c o  m*/
        return Iterables.tryFind(ImmutableList.<DefaultTransition>copyOf(transitions),
                new Predicate<DefaultTransition>() {
                    @Override
                    public boolean apply(final DefaultTransition input) {
                        return input.getInitialState().getName().equals(initialState.getName())
                                && input.getOperation().getName().equals(operation.getName())
                                && input.getOperationResult().equals(operationResult);
                    }
                }).get();
    } catch (IllegalStateException e) {
        throw new MissingEntryException("Missing transition for initialState " + initialState.getName()
                + ", operation = " + operation.getName() + ", result = " + operationResult, e);
    }
}

From source file:org.apache.brooklyn.camp.spi.resolve.interpret.PlanInterpretationNode.java

/** convenience for interpreters, tests if nodes are not excluded, and if not:
 * for string nodes, true iff the current value starts with the given prefix;
 * for nodes which are currently maps or lists,
 * true iff not excluded and the value contains such an entry (key, in the case of map) */
public boolean matchesPrefix(String prefix) {
    if (isExcluded())
        return false;
    if (getNewValue() instanceof CharSequence)
        return getNewValue().toString().startsWith(prefix);
    if (getNewValue() instanceof Map)
        return Iterables
                .tryFind(((Map<?, ?>) getNewValue()).keySet(), StringPredicates.isStringStartingWith(prefix))
                .isPresent();/*w  w w.  j  a  va2  s .  com*/
    if (getNewValue() instanceof Iterable)
        return Iterables.tryFind((Iterable<?>) getNewValue(), StringPredicates.isStringStartingWith(prefix))
                .isPresent();
    return false;
}

From source file:org.jenkinsci.plugins.github.util.FluentIterableWrapper.java

/**
 * Returns an {@link 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.
 *//* ww w  . ja  v a 2 s  .c om*/
public final Optional<E> firstMatch(Predicate<? super E> predicate) {
    return Iterables.tryFind(iterable, predicate);
}

From source file:com.eucalyptus.ws.util.ErrorHandlerSupport.java

protected static Optional<Integer> getHttpResponseStatus(final Throwable t) {
    final QueryBindingInfo info = Ats.inClassHierarchy(t.getClass()).get(QueryBindingInfo.class);
    final Optional<Integer> status = info == null ? Optional.<Integer>absent() : Optional.of(info.statusCode());
    return Iterables.tryFind(Exceptions.causes(t), Predicates.instanceOf(HasHttpStatusCode.class))
            .transform(Functions.compose(HasHttpStatusCode.Utils.httpStatusCode(),
                    CollectionUtils.cast(HasHttpStatusCode.class)))
            .or(status);//from  w w w . j  av  a 2s.  c  o  m
}

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

private Predicate<MailboxAnnotation> getPredicateFilterByAll(final Set<MailboxAnnotationKey> keys) {
    return new Predicate<MailboxAnnotation>() {
        @Override/*from  w ww.j a  v a2s.  c  om*/
        public boolean apply(final MailboxAnnotation input) {
            return Iterables.tryFind(keys, filterAnnotationsByPrefix(input)).isPresent();
        }
    };
}

From source file:com.keetip.versio.service.impl.VersioningServiceImpl.java

private Optional<ResourceKey> resolveKey(final UUID projectId, final String resourceName) {
    return Iterables.tryFind(mResources.keySet(), new Predicate<ResourceKey>() {
        public boolean apply(ResourceKey key) {
            return key.matches(projectId, resourceName);
        }//from  ww w.j  av a2  s.com
    });
}

From source file:org.killbill.billing.entitlement.engine.core.EntitlementUtils.java

/**
 * @param externalKey   the bundle externalKey
 * @param tenantContext the context/*from   www.j  a v a  2s  .com*/
 * @return the id of the first subscription (BASE or STANDALONE) that is still active for that key
 */
public UUID getFirstActiveSubscriptionIdForKeyOrNull(final String externalKey,
        final InternalTenantContext tenantContext) {

    final Iterable<UUID> nonAddonUUIDs = subscriptionBaseInternalApi.getNonAOSubscriptionIdsForKey(externalKey,
            tenantContext);
    return Iterables.tryFind(nonAddonUUIDs, new Predicate<UUID>() {
        @Override
        public boolean apply(final UUID input) {
            final BlockingState state = dao.getBlockingStateForService(input, BlockingStateType.SUBSCRIPTION,
                    DefaultEntitlementService.ENTITLEMENT_SERVICE_NAME, tenantContext);
            return (state == null || !state.getStateName().equals(DefaultEntitlementApi.ENT_STATE_CANCELLED));
        }
    }).orNull();
}

From source file:com.eviware.loadui.groovy.util.GroovyComponentTestUtils.java

public static ComponentItem createComponent(final String componentName, ComponentItem component)
        throws ComponentCreationException {
    Optional<ComponentDescriptor> descriptorOptional = null;
    Predicate<ComponentDescriptor> predicate = new Predicate<ComponentDescriptor>() {
        @Override// ww w  . ja va 2 s  .  c om
        public boolean apply(ComponentDescriptor input) {
            return Objects.equal(componentName, input.getLabel());
        }
    };

    long deadline = System.currentTimeMillis() + 5000;
    synchronized (lock) {
        while (!(descriptorOptional = Iterables.tryFind(descriptors.keySet(), predicate)).isPresent()
                && System.currentTimeMillis() < deadline) {
            try {
                lock.wait(deadline - System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
    }

    ComponentDescriptor descriptor = descriptorOptional.get();

    component.setAttribute(ComponentItem.TYPE, descriptor.getLabel());
    ComponentTestUtils.setComponentBehavior(component,
            descriptors.get(descriptor).createBehavior(descriptor, component.getContext()));

    return component;
}

From source file:org.n52.sos.ogc.sensorML.AbstractSensorML.java

public Optional<SmlClassifier> findClassifier(Predicate<SmlClassifier> predicate) {
    if (isSetClassifications()) {
        return Iterables.tryFind(this.classifications, predicate);
    } else {//from   w  w w.  ja v a  2 s  . c  o  m
        return Optional.absent();
    }
}

From source file:com.streamreduce.connections.ConnectionProviderFactory.java

public PushConnectionProvider pushConnectionProviderFromId(final String providerId) {
    return Iterables.tryFind(allPushConnectionProviders, new Predicate<PushConnectionProvider>() {
        @Override/* w  w  w.  j  a  v  a2 s.  c  o m*/
        public boolean apply(@Nullable PushConnectionProvider connectionProvider) {
            return connectionProvider != null && connectionProvider.getId().equals(providerId);
        }
    }).orNull();
}