Example usage for com.google.common.base Predicates and

List of usage examples for com.google.common.base Predicates and

Introduction

In this page you can find the example usage for com.google.common.base Predicates and.

Prototype

public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) 

Source Link

Document

Returns a predicate that evaluates to true if both of its components evaluate to true .

Usage

From source file:com.rockhoppertech.music.examples.Guava.java

static void and() {
    MIDITrack track = MIDITrackBuilder.create().noteString("C D E G F4").sequential().build();

    Predicate<MIDINote> and = Predicates.and(new PitchGreaterThanPredicate(Pitch.C5),
            new PitchLessThanPredicate(Pitch.F5));

    ImmutableList<MIDINote> bandpass = ImmutableList.copyOf(Iterables.filter(track, and));
    for (MIDINote in : bandpass) {
        System.out.println(in);/*from   w w w  . j a v a2 s . com*/
    }
}

From source file:org.eclipse.buildship.ui.wizard.project.WorkingSetConfigurationWidget.java

private Button findWorkingSetsSelectButton(Composite parent) {
    Predicate<Object> isButton = Predicates.instanceOf(Button.class);
    Predicate<Control> hasPushStyle = new Predicate<Control>() {

        @Override/*from   w ww .  j a va2s .  c o m*/
        public boolean apply(Control control) {
            return (control.getStyle() & SWT.PUSH) == SWT.PUSH;
        }
    };
    return (Button) findControl(parent, Predicates.and(isButton, hasPushStyle));
}

From source file:org.apache.brooklyn.core.typereg.BasicBrooklynTypeRegistry.java

@SuppressWarnings("deprecation")
private Maybe<RegisteredType> getSingle(String symbolicNameOrAliasIfNoVersion, final String versionFinal,
        final RegisteredTypeLoadingContext contextFinal) {
    RegisteredTypeLoadingContext context = contextFinal;
    if (context == null)
        context = RegisteredTypeLoadingContexts.any();
    String version = versionFinal;
    if (version == null)
        version = BrooklynCatalog.DEFAULT_VERSION;

    if (!BrooklynCatalog.DEFAULT_VERSION.equals(version)) {
        // normal code path when version is supplied

        Maybe<RegisteredType> type = getExactWithoutLegacyCatalog(symbolicNameOrAliasIfNoVersion, version,
                context);//  w  w  w . j av  a2  s  .c  o m
        if (type.isPresent())
            return type;
    }

    if (BrooklynCatalog.DEFAULT_VERSION.equals(version)) {
        // alternate code path, if version blank or default

        Iterable<RegisteredType> types = getMatching(
                Predicates.and(RegisteredTypePredicates.symbolicName(symbolicNameOrAliasIfNoVersion),
                        RegisteredTypePredicates.satisfies(context)));
        if (Iterables.isEmpty(types)) {
            // look for alias if no exact symbolic name match AND no version is specified
            types = getMatching(Predicates.and(RegisteredTypePredicates.alias(symbolicNameOrAliasIfNoVersion),
                    RegisteredTypePredicates.satisfies(context)));
            // if there are multiple symbolic names then throw?
            Set<String> uniqueSymbolicNames = MutableSet.of();
            for (RegisteredType t : types) {
                uniqueSymbolicNames.add(t.getSymbolicName());
            }
            if (uniqueSymbolicNames.size() > 1) {
                String message = "Multiple matches found for alias '" + symbolicNameOrAliasIfNoVersion + "': "
                        + uniqueSymbolicNames + "; " + "refusing to select any.";
                log.warn(message);
                return Maybe.absent(message);
            }
        }
        if (!Iterables.isEmpty(types)) {
            RegisteredType type = RegisteredTypes.getBestVersion(types);
            if (type != null)
                return Maybe.of(type);
        }
    }

    // missing case is to look for exact version in legacy catalog
    CatalogItem<?, ?> item = mgmt.getCatalog().getCatalogItem(symbolicNameOrAliasIfNoVersion, version);
    if (item != null)
        return Maybe.of(RegisteredTypes.CI_TO_RT.apply(item));

    return Maybe.absent("No matches for " + symbolicNameOrAliasIfNoVersion
            + (versionFinal != null ? ":" + versionFinal : "")
            + (contextFinal != null ? " (" + contextFinal + ")" : ""));
}

From source file:com.marvelution.hudson.plugins.apiv2.resources.impl.ActivityRestResourceImpl.java

/**
 * Get the filtered activities//from   ww w.  ja va  2  s  .co m
 * 
 * @param types the {@link ActivityType}s to filter by
 * @param jobs the jobnames to filter by
 * @param userIds the userIds to filter by
 * @return the {@link List} of {@link ActivityCache}s
 * @since 4.5.0
 */
private Collection<ActivityCache> getFilteredActivities(ActivityType[] types, String[] jobs, String[] userIds) {
    if (ArrayUtils.isEmpty(types)) {
        types = ActivityType.values();
    }
    Predicate<ActivityCache> predicates = ActivityCachePredicates.isActivity(types);
    if (jobs != null) {
        predicates = Predicates.and(predicates, ActivityCachePredicates.relatesToJobs(jobs));
    }
    if (userIds != null) {
        predicates = Predicates.and(predicates, ActivityCachePredicates.relatesToUsers(userIds));
    }
    return Collections2.filter(APIv2Plugin.getActivitiesCache().getSortedActivities(), predicates);
}

From source file:org.jclouds.providers.Providers.java

/**
 * Returns the providers that are bound to the same location as the given ISO 3166 code and of
 * the given viewableAs.//from  w w w.j a v a2  s. com
 * 
 * @param iso3166Code
 *           the ISO 3166 code to filter providers by
 * @param viewableAs
 *           the viewableAs to filter providers by
 * 
 * @return the providers bound by the given ISO 3166 code and of the proper viewableAs
 */
public static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code,
        TypeToken<? extends View> viewableAs) {
    return filter(all(), Predicates.and(ProviderPredicates.boundedByIso3166Code(iso3166Code),
            ProviderPredicates.viewableAs(viewableAs)));
}

From source file:org.apache.aurora.GuiceUtils.java

/**
 * Binds an exception trap on all interface methods of all classes bound against an interface.
 * Individual methods may opt out of trapping by annotating with {@link AllowUnchecked}.
 * Only void methods are allowed, any non-void interface methods must explicitly opt out.
 *
 * @param binder The binder to register an interceptor with.
 * @param wrapInterface Interface whose methods should be wrapped.
 * @throws IllegalArgumentException If any of the non-whitelisted interface methods are non-void.
 *///from   ww  w . j  av  a  2  s  . co m
public static void bindExceptionTrap(Binder binder, Class<?> wrapInterface) throws IllegalArgumentException {

    Set<Method> disallowed = ImmutableSet
            .copyOf(Iterables.filter(ImmutableList.copyOf(wrapInterface.getMethods()),
                    Predicates.and(Predicates.not(IS_WHITELISTED), Predicates.not(VOID_METHOD))));
    Preconditions.checkArgument(disallowed.isEmpty(),
            "Non-void methods must be explicitly whitelisted with @AllowUnchecked: %s", disallowed);

    Matcher<Method> matcher = Matchers.not(WHITELIST_MATCHER).and(interfaceMatcher(wrapInterface, false));
    binder.bindInterceptor(Matchers.subclassesOf(wrapInterface), matcher, new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            try {
                return invocation.proceed();
            } catch (RuntimeException e) {
                LOG.warn("Trapped uncaught exception: " + e, e);
                return null;
            }
        }
    });
}

From source file:org.auraframework.util.ServiceLoaderImpl.java

@SuppressWarnings("unchecked")
@Override/*from  www. j  a v  a2  s .  c o  m*/
public <T extends AuraServiceProvider> Set<T> getAll(Class<T> type) {
    Set<Method> beanMethods = Sets.newHashSet();

    Set<T> ret = Sets.newHashSet();

    Predicate<Method> pred = Predicates.and(predicate, ReflectionUtils.withReturnTypeAssignableTo(type));

    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(AuraConfiguration.class);

    /*
     * This is a better way to do it, but hits a runtime dep on Guava 12, so
     * until we upgrade to Guava 12, working around this.
     */

    for (Class<?> clazz : classes) {
        for (Method meth : clazz.getDeclaredMethods()) {
            if (pred.apply(meth)) {
                beanMethods.add(meth);
            }
        }
    }

    try {
        for (Method meth : beanMethods) {
            T val = (T) meth.invoke(null);
            if (val != null) {
                ret.add(val);
            }
        }
    } catch (Exception e) {
        throw new ServiceLocatorException(e);
    }

    return ret;
}

From source file:org.apache.whirr.cli.command.RunScriptCommand.java

private Predicate<NodeMetadata> buildFilterPredicate(String[] ids, String[] roles, ClusterSpec spec)
        throws IOException {

    Predicate<NodeMetadata> condition = Predicates.alwaysTrue();
    if (ids != null && ids.length > 0) {
        return Predicates.and(condition, withIds(ids));
    } else if (roles != null && roles.length > 0) {
        List<String> instanceIds = Lists.newArrayList();

        Cluster cluster = createClusterStateStore(spec).load();
        for (Cluster.Instance instance : cluster
                .getInstancesMatching(anyRoleIn(Sets.<String>newHashSet(roles)))) {
            instanceIds.add(instance.getId());
        }/*from w  w  w.j av a  2s .  c  o m*/

        condition = Predicates.and(condition, withIds(instanceIds.toArray(new String[0])));
        return condition;
    } else {
        return condition;
    }
}

From source file:net.sourceforge.ganttproject.GanttTreeTableModel.java

/**
 * Creates an instance of GanttTreeTableModel with a root.
 *
 * @param root// w ww .ja va2 s  . c om
 *          The root.
 * @param customColumnsManager
 * @param dirtyfier
 */
public GanttTreeTableModel(TaskManager taskManager, CustomPropertyManager customColumnsManager,
        UIFacade uiFacade, Runnable dirtyfier) {
    super(new TaskNode(taskManager.getRootTask()));
    TaskDefaultColumn.BEGIN_DATE.setIsEditablePredicate(NOT_SUPERTASK);
    TaskDefaultColumn.BEGIN_DATE.setSortComparator(new BeginDateComparator());
    TaskDefaultColumn.END_DATE.setIsEditablePredicate(Predicates.and(NOT_SUPERTASK, NOT_MILESTONE));
    TaskDefaultColumn.END_DATE.setSortComparator(new EndDateComparator());
    TaskDefaultColumn.DURATION.setIsEditablePredicate(Predicates.and(NOT_SUPERTASK, NOT_MILESTONE));
    myUiFacade = uiFacade;
    myDirtyfier = dirtyfier;
    myCustomColumnsManager = customColumnsManager;
}

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;
}