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>... components) 

Source Link

Document

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

Usage

From source file:org.apache.brooklyn.util.text.StringPredicates.java

public static <T extends CharSequence> Predicate<T> containsAllLiterals(final String... fragments) {
    List<Predicate<CharSequence>> fragmentPredicates = Lists.newArrayList();
    for (String fragment : fragments) {
        fragmentPredicates.add(containsLiteral(fragment));
    }//from w w  w. j  a  va  2 s .c o m
    return Predicates.and(fragmentPredicates);
}

From source file:com.madvay.tools.android.perf.apat.CommandLine.java

private static Predicate<StackTraceElement> parseSteP(String s) {
    return Predicates.and(
            Lists.transform(CONJ_SPLIT.splitToList(s), new Function<String, Predicate<StackTraceElement>>() {
                @Override// ww  w .ja v a  2  s .c o m
                public Predicate<StackTraceElement> apply(String input) {
                    return parseStePOperator(input);
                }
            }));
}

From source file:de.iteratec.iteraplan.elasticeam.operator.filter.predicate.FilterPredicates.java

/**
 * Creates an AND/OR/NOT predicate.//from  ww w .j  a v  a 2s .c  o  m
 * 
 * @param operation
 *    The operation of choice.
 * @param subPredicates
 *    A list with sub-predicates. In case of NOT, the list should contain only one element.
 * @return
 *    The compiled predicate which can later be used to evaluate universal model expressions.
 */
public static Predicate<UniversalModelExpression> buildCompositePredicate(
        final CompositePredicateOperation operation,
        final List<Predicate<UniversalModelExpression>> subPredicates) {
    return new Predicate<UniversalModelExpression>() {
        public boolean apply(UniversalModelExpression modelExpression) {
            if (operation.equals(CompositePredicateOperation.AND)) {
                return Predicates.and(subPredicates).apply(modelExpression);
            } else if (operation.equals(CompositePredicateOperation.OR)) {
                return Predicates.or(subPredicates).apply(modelExpression);
            } else {
                return Predicates.not(subPredicates.get(0)).apply(modelExpression);
            }
        }

        public String toString() {
            return operation.getValue() + "(" + subPredicates + ")";
        }

        @SuppressWarnings("unused")
        @ConfigParameter
        public CompositePredicateOperation getOperation() {
            return operation;
        }

        @SuppressWarnings("unused")
        @ConfigParameter
        public List<Predicate<UniversalModelExpression>> getSubPredicates() {
            return Collections.unmodifiableList(subPredicates);
        }
    };
}

From source file:com.eucalyptus.cloud.run.VerifyMetadata.java

public static Predicate<Allocation> get() {
    return Predicates.and(Lists.transform(verifiers, AsPredicate.INSTANCE));
}

From source file:org.apache.brooklyn.util.text.StringPredicates.java

/** @deprecated since 0.7.0 kept only to allow conversion of anonymous inner classes */
@SuppressWarnings("unused")
@Deprecated//from w  w w  .ja v a 2 s .c  o  m
private static Predicate<CharSequence> containsAllLiteralsOld(final String... fragments) {
    return Predicates
            .and(Iterables.transform(Arrays.asList(fragments), new Function<String, Predicate<CharSequence>>() {
                @Override
                public Predicate<CharSequence> apply(String input) {
                    return containsLiteral(input);
                }
            }));
}

From source file:org.apache.brooklyn.rest.resources.TypeResource.java

@Override
public List<TypeSummary> list(String supertype, String versions, String regex, String fragment) {
    List<Predicate<RegisteredType>> filters = MutableList.<Predicate<RegisteredType>>of()
            .append(RegisteredTypePredicates.entitledToSee(mgmt()));
    if (Strings.isNonBlank(supertype)) {
        // rewrite certain well known ones
        // (in future this should happen automatically as Entity.class should be known as user-friendly name 'entity') 
        if ("entity".equals(supertype))
            supertype = Entity.class.getName();
        else if ("enricher".equals(supertype))
            supertype = Enricher.class.getName();
        else if ("policy".equals(supertype))
            supertype = Policy.class.getName();
        else if ("location".equals(supertype))
            supertype = Location.class.getName();
        // TODO application probably isn't at all interesting; keep it for backward compatibility,
        // and meanwhile sort out things like "template" vs "quick launch"
        // (probably adding tags on the API)
        else if ("application".equals(supertype))
            supertype = Application.class.getName();

        filters.add(RegisteredTypePredicates.subtypeOf(supertype));
    }//from  w ww . j  a  va 2  s  .co m
    if (TypeResource.isLatestOnly(versions, true)) {
        // TODO inefficient - does n^2 comparisons where n is sufficient
        // create RegisteredTypes.filterBestVersions to do a list after the initial parse
        // (and javadoc in predicate method below)
        filters.add(RegisteredTypePredicates.isBestVersion(mgmt()));
    }
    if (Strings.isNonEmpty(regex)) {
        filters.add(RegisteredTypePredicates.nameOrAlias(StringPredicates.containsRegex(regex)));
    }
    if (Strings.isNonEmpty(fragment)) {
        filters.add(RegisteredTypePredicates.nameOrAlias(StringPredicates.containsLiteralIgnoreCase(fragment)));
    }
    Predicate<RegisteredType> filter = Predicates.and(filters);

    ImmutableList<RegisteredType> sortedItems = FluentIterable
            .from(brooklyn().getTypeRegistry().getMatching(filter))
            .toSortedList(RegisteredTypes.RegisteredTypeNameThenBestFirstComparator.INSTANCE);
    return toTypeSummary(brooklyn(), sortedItems, ui.getBaseUriBuilder());
}

From source file:com.google.caliper.memory.ObjectGraphMeasurer.java

/**
 * Measures the footprint of the specified object graph.
 * The object graph is defined by a root object and whatever object can be
 * reached through that, excluding static fields, {@code Class} objects,
 * and fields defined in {@code enum}s (all these are considered shared
 * values, which should not contribute to the cost of any single object
 * graph), and any object for which the user-provided predicate returns
 * {@code false}./* w w w .  j  av  a 2s .co m*/
 *
 * @param rootObject the root object of the object graph
 * @param objectAcceptor a predicate that returns {@code true} for objects
 * to be explored (and treated as part of the footprint), or {@code false}
 * to forbid the traversal to traverse the given object
 * @return the footprint of the object graph
 */
public static Footprint measure(Object rootObject, Predicate<Object> objectAcceptor) {
    Preconditions.checkNotNull(objectAcceptor, "predicate");

    Predicate<Chain> completePredicate = Predicates.and(
            ImmutableList.of(ObjectExplorer.notEnumFieldsOrClasses, new ObjectExplorer.AtMostOncePredicate(),
                    Predicates.compose(objectAcceptor, ObjectExplorer.chainToObject)));

    return ObjectExplorer.exploreObject(rootObject, new ObjectGraphVisitor(completePredicate),
            EnumSet.of(Feature.VISIT_PRIMITIVES, Feature.VISIT_NULL));
}

From source file:name.marmar.gf.greplog.GrepLogCommand.java

@Override
public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    //Create predicate from parameters
    Collection<Predicate<LogRecord>> predicates = new ArrayList<>(3);
    if (StringUtils.ok(search)) {
        if (fixedStrings) {
            predicates.add(new LogMessagePredicate(search));
        } else {//from w w  w  . j  a va  2  s. c  o  m
            predicates.add(new LogRegexpPredicate(Pattern.compile(".*" + search + ".*")));
        }
    }
    if (StringUtils.ok(minLevel)) {
        predicates.add(new LogMinLevelPredicate(minLevel));
    }
    if (StringUtils.ok(pckg)) {
        predicates.add(new LogPackagePredicate(pckg));
    }
    Predicate<LogRecord> predicate = Predicates.and(predicates);
    //Find logging directory
    String sourceDirName;
    try {
        sourceDirName = loggingConfig.getLoggingFileDetails();
        sourceDirName = sourceDirName.replace("${com.sun.aas.instanceRoot}", env.getInstanceRoot().getPath());
        sourceDirName = sourceDirName.substring(0, sourceDirName.lastIndexOf(File.separator));
    } catch (Exception exc) {
        //Configuration for the server probably does not exists. Try to locate by convention
        File logDir = new File(env.getInstanceRoot(), "logs");
        //logger.log(Level.INFO, "Hard generated logging directory: " + logDir.getPath());
        if (logDir.exists() && logDir.isDirectory()) {
            sourceDirName = logDir.getPath();
        } else {
            logger.log(Level.WARNING, "Generated log dir name [" + logDir.getPath() + "] does not exists");
            report.setMessage("Can not locate log files directory");
            report.setFailureCause(exc);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    //Find files
    File sourceDir = new File(sourceDirName);
    if (!sourceDir.exists()) {
        report.setMessage("Logging directory does not exists [" + sourceDirName + "]");
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    File[] logFiles = sourceDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File f) {
            return f.isFile();
        }
    });
    //Grep all valid logfiles
    report.setMessage(
            "** On server (" + env.getInstanceName() + ") greps " + logFiles.length + " logging file(s)");
    for (File logFile : logFiles) {
        report.appendMessage("\n**** " + logFile.getName());
        try {
            GrepResult grep = grep(logFile, predicate);
            grep.addToReport(report);
        } catch (Exception e) {
            report.appendMessage(" [Can NOT process file!]");
            logger.log(Level.WARNING, "Can not process file " + logFile.getPath() + ".", e);
        }
    }
    //Result
    report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
}

From source file:br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentCommand.java

public EnvironmentDescription executeInternal(WaitForEnvironmentContext context) throws Exception {
    // Those are invariants
    long timeoutMins = context.getTimeoutMins();

    Date expiresAt = new Date(System.currentTimeMillis() + MINS_TO_MSEC * timeoutMins);
    Date lastMessageRecord = new Date();

    info("Environment Lookup");

    List<Predicate<EnvironmentDescription>> envPredicates = getEnvironmentDescriptionPredicate(context);
    Predicate<EnvironmentDescription> corePredicate = envPredicates.get(0);
    Predicate<EnvironmentDescription> fullPredicate = Predicates.and(envPredicates);

    do {/*w ww .j  a  v  a 2 s  .c o  m*/
        DescribeEnvironmentsRequest req = new DescribeEnvironmentsRequest()
                .withApplicationName(context.getApplicationName()).withIncludeDeleted(true);

        final List<EnvironmentDescription> envs = parentMojo.getService().describeEnvironments(req)
                .getEnvironments();

        Collection<EnvironmentDescription> validEnvironments = Collections2.filter(envs, fullPredicate);

        debug("There are %d environments", validEnvironments.size());

        if (1 == validEnvironments.size()) {
            EnvironmentDescription foundEnvironment = validEnvironments.iterator().next();

            debug("Found environment %s", foundEnvironment);

            return foundEnvironment;
        } else {
            debug("Found %d environments. No good. Ignoring.", validEnvironments.size());

            for (EnvironmentDescription d : validEnvironments) {
                debug(" ... %s", d);
            }

            // ... but have we've got any closer match? If so, dump recent events

            Collection<EnvironmentDescription> foundEnvironments = Collections2.filter(envs, corePredicate);

            if (1 == foundEnvironments.size()) {
                EnvironmentDescription foundEnvironment = foundEnvironments.iterator().next();

                DescribeEventsResult events = service.describeEvents(
                        new DescribeEventsRequest().withApplicationName(foundEnvironment.getApplicationName())
                                .withStartTime(new Date(1000 + lastMessageRecord.getTime()))
                                .withEnvironmentId(foundEnvironment.getEnvironmentId()).withSeverity("TRACE"));

                Set<EventDescription> eventList = new TreeSet<EventDescription>(
                        new EventDescriptionComparator());

                eventList.addAll(events.getEvents());

                for (EventDescription d : eventList) {
                    info(String.format("%s %s %s", d.getSeverity(), d.getEventDate(), d.getMessage()));

                    if (d.getSeverity().equals(("ERROR"))) {
                        throw new MojoExecutionException(
                                "Something went wrong in while waiting for the environment setup to complete : "
                                        + d.getMessage());
                    }
                    lastMessageRecord = d.getEventDate();
                }
            }
        }

        sleepInterval(POLL_INTERVAL);
    } while (!timedOutP(expiresAt));

    throw new MojoExecutionException("Timed out");
}

From source file:dynamicrefactoring.domain.metadata.imp.ElementCatalog.java

/**
 * Devuelve un predicado con todas las condiciones del filtro juntas.
 * //from   w  w w  .  ja va2  s  .c om
 * @return predicado con todas las condiciones
 */
private Predicate<K> getPredicateForAllConditions() {
    return Predicates.and(filter);
}