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.plugin.entitlement.coupon.demo.CouponDemoEntitlementPluginApi.java

private PluginProperty findCouponProperty(@Nullable final Iterable<PluginProperty> pluginProperties) {
    return Iterables.tryFind(pluginProperties, new Predicate<PluginProperty>() {
        @Override/*from  ww  w . ja  v a 2  s.  co m*/
        public boolean apply(@Nullable PluginProperty input) {
            return input.getKey().equals(COUPON_PROPERTY);
        }
    }).orNull();
}

From source file:brooklyn.util.flags.MethodCoercions.java

/**
 * Tries to find a multiple-parameter method with each parameter compatible with (can be coerced to) the
 * corresponding argument, and invokes it.
 *
 * @param instance the object to invoke the method on
 * @param methodName the name of the method to invoke
 * @param argument a list of the arguments to the method's parameters.
 * @return the result of the method call, or {@link brooklyn.util.guava.Maybe#absent()} if method could not be matched.
 *//*from  w ww .java2s  .c om*/
public static Maybe<?> tryFindAndInvokeMultiParameterMethod(final Object instance, final String methodName,
        final List<?> arguments) {
    Class<?> clazz = instance.getClass();
    Iterable<Method> methods = Arrays.asList(clazz.getMethods());
    Optional<Method> matchingMethod = Iterables.tryFind(methods,
            matchMultiParameterMethod(methodName, arguments));
    if (matchingMethod.isPresent()) {
        Method method = matchingMethod.get();
        try {
            int numOptionParams = ((List) arguments).size();
            Object[] coercedArguments = new Object[numOptionParams];
            for (int paramCount = 0; paramCount < numOptionParams; paramCount++) {
                Object argument = arguments.get(paramCount);
                Type paramType = method.getGenericParameterTypes()[paramCount];
                coercedArguments[paramCount] = TypeCoercions.coerce(argument, TypeToken.of(paramType));
            }
            return Maybe.of(method.invoke(instance, coercedArguments));
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw Exceptions.propagate(e);
        }
    } else {
        return Maybe.absent();
    }
}

From source file:org.ow2.play.governance.permission.service.PermissionService.java

/**
 * @param metadata// w w  w  . j  a  v  a2  s  .c o  m
 * @param accessTo
 * @return
 */
protected Metadata get(final List<Metadata> metadata, final String key) {
    return Iterables.tryFind(metadata, new Predicate<Metadata>() {
        public boolean apply(Metadata input) {
            return input != null && input.getName() != null && input.getName().equals(key);
        }
    }).orNull();
}

From source file:org.eclipse.osee.orcs.core.internal.attribute.AttributeManagerImpl.java

@Override
public Attribute<Object> getAttributeById(AttributeId attributeId) throws OseeCoreException {
    Attribute<Object> attribute = null;
    Optional<Attribute<Object>> tryFind = Iterables.tryFind(getAttributes(),
            OrcsPredicates.attributeId(attributeId));
    if (tryFind.isPresent()) {
        attribute = tryFind.get();//from  ww w. ja v a2  s  .  c  o  m
    } else {
        throw new AttributeDoesNotExist("Attribute[%s] does not exist for %s", attributeId,
                getExceptionString());
    }
    return attribute;
}

From source file:org.apache.brooklyn.util.core.flags.MethodCoercions.java

/**
 * Tries to find a multiple-parameter method with each parameter compatible with (can be coerced to) the
 * corresponding argument, and invokes it.
 *
 * @param instance the object to invoke the method on
 * @param methodName the name of the method to invoke
 * @param argument a list of the arguments to the method's parameters.
 * @return the result of the method call, or {@link org.apache.brooklyn.util.guava.Maybe#absent()} if method could not be matched.
 *///from w  w  w.  j  a v  a2  s . c o  m
public static Maybe<?> tryFindAndInvokeMultiParameterMethod(final Object instance, final String methodName,
        final List<?> arguments) {
    Class<?> clazz = instance.getClass();
    Iterable<Method> methods = Arrays.asList(clazz.getMethods());
    Optional<Method> matchingMethod = Iterables.tryFind(methods,
            matchMultiParameterMethod(methodName, arguments));
    if (matchingMethod.isPresent()) {
        Method method = matchingMethod.get();
        try {
            int numOptionParams = ((List<?>) arguments).size();
            Object[] coercedArguments = new Object[numOptionParams];
            for (int paramCount = 0; paramCount < numOptionParams; paramCount++) {
                Object argument = arguments.get(paramCount);
                Type paramType = method.getGenericParameterTypes()[paramCount];
                coercedArguments[paramCount] = TypeCoercions.coerce(argument, TypeToken.of(paramType));
            }
            return Maybe.of(method.invoke(instance, coercedArguments));
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw Exceptions.propagate(e);
        }
    } else {
        return Maybe.absent();
    }
}

From source file:com.google.errorprone.bugpatterns.TypeNameShadowing.java

/** Iterate through a list of type parameters, looking for type names shadowed by any of them. */
private Description findShadowedTypes(Tree tree, List<? extends TypeParameterTree> typeParameters,
        VisitorState state) {/*from w w  w. j  a v a 2s . com*/

    Env<AttrContext> env = Enter.instance(state.context)
            .getEnv(ASTHelpers.getSymbol(state.findEnclosing(ClassTree.class)));

    Symtab symtab = state.getSymtab();
    PackageSymbol javaLang = symtab.enterPackage(symtab.java_base, Names.instance(state.context).java_lang);

    Iterable<Symbol> enclosingTypes = typesInEnclosingScope(env, javaLang);

    List<Symbol> shadowedTypes = typeParameters.stream()
            .map(param -> Iterables
                    .tryFind(enclosingTypes,
                            sym -> sym.getSimpleName().equals(ASTHelpers.getType(param).tsym.getSimpleName()))
                    .orNull())
            .filter(Objects::nonNull).collect(ImmutableList.toImmutableList());

    if (shadowedTypes.isEmpty()) {
        return Description.NO_MATCH;
    }

    Description.Builder descBuilder = buildDescription(tree);

    descBuilder.setMessage(buildMessage(shadowedTypes));

    Set<String> visibleNames = Streams.stream(Iterables.concat(env.info.getLocalElements(), enclosingTypes))
            .map(sym -> sym.getSimpleName().toString()).collect(ImmutableSet.toImmutableSet());

    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    shadowedTypes.stream()
            .filter(tv -> TypeParameterNamingClassification.classify(tv.name.toString()).isValidName())
            .map(tv -> TypeParameterShadowing.renameTypeVariable(
                    TypeParameterShadowing.typeParameterInList(typeParameters, tv), tree,
                    TypeParameterShadowing.replacementTypeVarName(tv.name, visibleNames), state))
            .forEach(fixBuilder::merge);

    descBuilder.addFix(fixBuilder.build());
    return descBuilder.build();
}

From source file:com.kurtraschke.wmata.gtfsrealtime.services.WMATARouteMapperService.java

private AgencyAndId mapRailRoute(String routeName) {
    Optional<Route> matchedRoute = Iterables.tryFind(_gtfsRoutes,
            new ShortNameFilterPredicate(routeName, false));

    if (matchedRoute.isPresent()) {
        AgencyAndId mappedRouteID = matchedRoute.get().getId();
        _log.info("Mapped WMATA route " + routeName + " to GTFS route " + mappedRouteID);
        return mappedRouteID;
    } else {//from  w w w. j  a v a2s . co m
        _log.warn("Could not map WMATA route: " + routeName);
        return null;
    }
}

From source file:brooklyn.entity.nosql.etcd.EtcdClusterImpl.java

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

        Map<Entity, String> nodes = getAttribute(ETCD_CLUSTER_NODES);
        if (belongsInServerPool(member)) {
            if (nodes == null) {
                nodes = Maps.newLinkedHashMap();
            }/*from   w  w w . java2  s .co  m*/
            String name = Preconditions.checkNotNull(getNodeName(member));

            // Wait until node has been installed
            DynamicTasks
                    .queueIfPossible(
                            DependentConfiguration.attributeWhenReady(member, EtcdNode.ETCD_NODE_INSTALLED))
                    .orSubmitAndBlock(this).andWaitForSuccess();

            // Check for first node in the cluster.
            Entity firstNode = getAttribute(DynamicCluster.FIRST);
            if (member.equals(firstNode)) {
                nodes.put(member, name);
                recalculateClusterAddresses(nodes);
                log.info("Adding first node {}: {}; {} to cluster", new Object[] { this, member, name });
                ((EntityInternal) member).setAttribute(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE);
            } else {
                int retry = 3; // TODO use a configurable Repeater instead?
                while (retry-- > 0 && member.getAttribute(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER) == null
                        && !nodes.containsKey(member)) {
                    Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                            Predicates.and(Predicates.instanceOf(EtcdNode.class), EntityPredicates
                                    .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE)));
                    if (anyNodeInCluster.isPresent()) {
                        DynamicTasks
                                .queueIfPossible(DependentConfiguration
                                        .attributeWhenReady(anyNodeInCluster.get(), Startable.SERVICE_UP))
                                .orSubmitAndBlock(this).andWaitForSuccess();
                        Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(),
                                EtcdNode.JOIN_ETCD_CLUSTER, name, getNodeAddress(member)).blockUntilEnded();
                        nodes.put(member, name);
                        recalculateClusterAddresses(nodes);
                        log.info("Adding node {}: {}; {} to cluster", new Object[] { this, member, name });
                        ((EntityInternal) member).setAttribute(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER,
                                Boolean.TRUE);
                    } else {
                        log.info("Waiting for first node in cluster {}", this);
                        Time.sleep(Duration.seconds(15));
                    }
                }
            }
        } else {
            if (nodes != null && nodes.containsKey(member)) {
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                        Predicates.and(
                                Predicates.instanceOf(EtcdNode.class), EntityPredicates
                                        .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE),
                                Predicates.not(Predicates.equalTo(member))));
                if (anyNodeInCluster.isPresent()) {
                    Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), EtcdNode.LEAVE_ETCD_CLUSTER,
                            getNodeName(member)).blockUntilEnded();
                }
                nodes.remove(member);
                recalculateClusterAddresses(nodes);
                log.info("Removing node {}: {}; {} from cluster",
                        new Object[] { this, member, getNodeName(member) });
                ((EntityInternal) member).setAttribute(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.FALSE);
            }
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, ETCD_CLUSTER_NODES);
        log.debug("Done {} checkEntity {}", this, member);
    }
}

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

protected final EffectiveStatement<?, ?> firstEffectiveSubstatementOfType(final Class<?> type) {
    return Iterables.tryFind(substatements, Predicates.instanceOf(type)).orNull();
}

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

/** returns the first exception of the given type, or null */
@SuppressWarnings("unchecked")
public static <T extends Throwable> T getFirstThrowableOfType(Throwable from, Class<T> clazz) {
    return (T) Iterables.tryFind(getCausalChain(from), instanceOf(clazz)).orNull();
}