001    /*
002     * Copyright (C) 2007 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.base;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    
021    import com.google.common.annotations.GwtCompatible;
022    import com.google.common.annotations.GwtIncompatible;
023    
024    import java.io.Serializable;
025    import java.util.ArrayList;
026    import java.util.Arrays;
027    import java.util.Collection;
028    import java.util.List;
029    import java.util.regex.Pattern;
030    
031    import javax.annotation.Nullable;
032    
033    /**
034     * Static utility methods pertaining to {@code Predicate} instances.
035     *
036     * <p>All methods returns serializable predicates as long as they're given
037     * serializable parameters.
038     *
039     * @author Kevin Bourrillion
040     * @since 2 (imported from Google Collections Library)
041     */
042    @GwtCompatible(emulated = true)
043    public final class Predicates {
044      private Predicates() {}
045    
046      // TODO(kevinb): considering having these implement a VisitablePredicate
047      // interface which specifies an accept(PredicateVisitor) method.
048    
049      /**
050       * Returns a predicate that always evaluates to {@code true}.
051       */
052      @GwtCompatible(serializable = true)
053      public static <T> Predicate<T> alwaysTrue() {
054        return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
055      }
056    
057      /**
058       * Returns a predicate that always evaluates to {@code false}.
059       */
060      @GwtCompatible(serializable = true)
061      public static <T> Predicate<T> alwaysFalse() {
062        return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
063      }
064    
065      /**
066       * Returns a predicate that evaluates to {@code true} if the object reference
067       * being tested is null.
068       */
069      @GwtCompatible(serializable = true)
070      public static <T> Predicate<T> isNull() {
071        return ObjectPredicate.IS_NULL.withNarrowedType();
072      }
073    
074      /**
075       * Returns a predicate that evaluates to {@code true} if the object reference
076       * being tested is not null.
077       */
078      @GwtCompatible(serializable = true)
079      public static <T> Predicate<T> notNull() {
080        return ObjectPredicate.NOT_NULL.withNarrowedType();
081      }
082    
083      /**
084       * Returns a predicate that evaluates to {@code true} if the given predicate
085       * evaluates to {@code false}.
086       */
087      public static <T> Predicate<T> not(Predicate<T> predicate) {
088        return new NotPredicate<T>(predicate);
089      }
090    
091      /**
092       * Returns a predicate that evaluates to {@code true} if each of its
093       * components evaluates to {@code true}. The components are evaluated in
094       * order, and evaluation will be "short-circuited" as soon as a false
095       * predicate is found. It defensively copies the iterable passed in, so future
096       * changes to it won't alter the behavior of this predicate. If {@code
097       * components} is empty, the returned predicate will always evaluate to {@code
098       * true}.
099       */
100      public static <T> Predicate<T> and(
101          Iterable<? extends Predicate<? super T>> components) {
102        return new AndPredicate<T>(defensiveCopy(components));
103      }
104    
105      /**
106       * Returns a predicate that evaluates to {@code true} if each of its
107       * components evaluates to {@code true}. The components are evaluated in
108       * order, and evaluation will be "short-circuited" as soon as a false
109       * predicate is found. It defensively copies the array passed in, so future
110       * changes to it won't alter the behavior of this predicate. If {@code
111       * components} is empty, the returned predicate will always evaluate to {@code
112       * true}.
113       */
114      public static <T> Predicate<T> and(Predicate<? super T>... components) {
115        return new AndPredicate<T>(defensiveCopy(components));
116      }
117    
118      /**
119       * Returns a predicate that evaluates to {@code true} if both of its
120       * components evaluate to {@code true}. The components are evaluated in
121       * order, and evaluation will be "short-circuited" as soon as a false
122       * predicate is found.
123       */
124      public static <T> Predicate<T> and(Predicate<? super T> first,
125          Predicate<? super T> second) {
126        return new AndPredicate<T>(Predicates.<T>asList(
127            checkNotNull(first), checkNotNull(second)));
128      }
129    
130      /**
131       * Returns a predicate that evaluates to {@code true} if any one of its
132       * components evaluates to {@code true}. The components are evaluated in
133       * order, and evaluation will be "short-circuited" as soon as a
134       * true predicate is found. It defensively copies the iterable passed in, so
135       * future changes to it won't alter the behavior of this predicate. If {@code
136       * components} is empty, the returned predicate will always evaluate to {@code
137       * false}.
138       */
139      public static <T> Predicate<T> or(
140          Iterable<? extends Predicate<? super T>> components) {
141        return new OrPredicate<T>(defensiveCopy(components));
142      }
143    
144      /**
145       * Returns a predicate that evaluates to {@code true} if any one of its
146       * components evaluates to {@code true}. The components are evaluated in
147       * order, and evaluation will be "short-circuited" as soon as a
148       * true predicate is found. It defensively copies the array passed in, so
149       * future changes to it won't alter the behavior of this predicate. If {@code
150       * components} is empty, the returned predicate will always evaluate to {@code
151       * false}.
152       */
153      public static <T> Predicate<T> or(Predicate<? super T>... components) {
154        return new OrPredicate<T>(defensiveCopy(components));
155      }
156    
157      /**
158       * Returns a predicate that evaluates to {@code true} if either of its
159       * components evaluates to {@code true}. The components are evaluated in
160       * order, and evaluation will be "short-circuited" as soon as a
161       * true predicate is found.
162       */
163      public static <T> Predicate<T> or(
164          Predicate<? super T> first, Predicate<? super T> second) {
165        return new OrPredicate<T>(Predicates.<T>asList(
166            checkNotNull(first), checkNotNull(second)));
167      }
168    
169      /**
170       * Returns a predicate that evaluates to {@code true} if the object being
171       * tested {@code equals()} the given target or both are null.
172       */
173      public static <T> Predicate<T> equalTo(@Nullable T target) {
174        return (target == null)
175            ? Predicates.<T>isNull()
176            : new IsEqualToPredicate<T>(target);
177      }
178    
179      /**
180       * Returns a predicate that evaluates to {@code true} if the object being
181       * tested is an instance of the given class. If the object being tested
182       * is {@code null} this predicate evaluates to {@code false}.
183       *
184       * <p>If you want to filter an {@code Iterable} to narrow its type, consider
185       * using {@link com.google.common.collect.Iterables#filter(Iterable, Class)}
186       * in preference.
187       *
188       * <p><b>Warning:</b> contrary to the typical assumptions about predicates (as
189       * documented at {@link Predicate#apply}), the returned predicate may not be
190       * <i>consistent with equals</i>. For example, {@code
191       * instanceOf(ArrayList.class)} will yield different results for the two equal
192       * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}.
193       */
194      @GwtIncompatible("Class.isInstance")
195      public static Predicate<Object> instanceOf(Class<?> clazz) {
196        return new InstanceOfPredicate(clazz);
197      }
198    
199      /**
200       * Returns a predicate that evaluates to {@code true} if the object reference
201       * being tested is a member of the given collection. It does not defensively
202       * copy the collection passed in, so future changes to it will alter the
203       * behavior of the predicate.
204       *
205       * This method can technically accept any Collection<?>, but using a typed
206       * collection helps prevent bugs. This approach doesn't block any potential
207       * users since it is always possible to use {@code Predicates.<Object>in()}.
208       *
209       * @param target the collection that may contain the function input
210       */
211      public static <T> Predicate<T> in(Collection<? extends T> target) {
212        return new InPredicate<T>(target);
213      }
214    
215      /**
216       * Returns the composition of a function and a predicate. For every {@code x},
217       * the generated predicate returns {@code predicate(function(x))}.
218       *
219       * @return the composition of the provided function and predicate
220       */
221      public static <A, B> Predicate<A> compose(
222          Predicate<B> predicate, Function<A, ? extends B> function) {
223        return new CompositionPredicate<A, B>(predicate, function);
224      }
225    
226      /**
227       * Returns a predicate that evaluates to {@code true} if the
228       * {@code CharSequence} being tested contains any match for the given
229       * regular expression pattern. The test used is equivalent to
230       * {@code Pattern.compile(pattern).matcher(arg).find()}
231       *
232       * @throws java.util.regex.PatternSyntaxException if the pattern is invalid
233       * @since 3
234       */
235      @GwtIncompatible(value = "java.util.regex.Pattern")
236      public static Predicate<CharSequence> containsPattern(String pattern) {
237        return new ContainsPatternPredicate(pattern);
238      }
239    
240      /**
241       * Returns a predicate that evaluates to {@code true} if the
242       * {@code CharSequence} being tested contains any match for the given
243       * regular expression pattern. The test used is equivalent to
244       * {@code regex.matcher(arg).find()}
245       *
246       * @since 3
247       */
248      @GwtIncompatible(value = "java.util.regex.Pattern")
249      public static Predicate<CharSequence> contains(Pattern pattern) {
250        return new ContainsPatternPredicate(pattern);
251      }
252    
253      // End public API, begin private implementation classes.
254    
255      // Package private for GWT serialization.
256      enum ObjectPredicate implements Predicate<Object> {
257        ALWAYS_TRUE {
258          @Override public boolean apply(@Nullable Object o) {
259            return true;
260          }
261        },
262        ALWAYS_FALSE {
263          @Override public boolean apply(@Nullable Object o) {
264            return false;
265          }
266        },
267        IS_NULL {
268          @Override public boolean apply(@Nullable Object o) {
269            return o == null;
270          }
271        },
272        NOT_NULL {
273          @Override public boolean apply(@Nullable Object o) {
274            return o != null;
275          }
276        };
277        
278        @SuppressWarnings("unchecked") // these Object predicates work for any T
279        <T> Predicate<T> withNarrowedType() {
280          return (Predicate<T>) this;
281        }
282      }
283    
284      /** @see Predicates#not(Predicate) */
285      private static class NotPredicate<T> implements Predicate<T>, Serializable {
286        final Predicate<T> predicate;
287    
288        NotPredicate(Predicate<T> predicate) {
289          this.predicate = checkNotNull(predicate);
290        }
291        @Override
292        public boolean apply(T t) {
293          return !predicate.apply(t);
294        }
295        @Override public int hashCode() {
296          return ~predicate.hashCode();
297        }
298        @Override public boolean equals(@Nullable Object obj) {
299          if (obj instanceof NotPredicate) {
300            NotPredicate<?> that = (NotPredicate<?>) obj;
301            return predicate.equals(that.predicate);
302          }
303          return false;
304        }
305        @Override public String toString() {
306          return "Not(" + predicate.toString() + ")";
307        }
308        private static final long serialVersionUID = 0;
309      }
310    
311      private static final Joiner COMMA_JOINER = Joiner.on(",");
312    
313      /** @see Predicates#and(Iterable) */
314      private static class AndPredicate<T> implements Predicate<T>, Serializable {
315        private final List<? extends Predicate<? super T>> components;
316    
317        private AndPredicate(List<? extends Predicate<? super T>> components) {
318          this.components = components;
319        }
320        @Override
321        public boolean apply(T t) {
322          for (Predicate<? super T> predicate : components) {
323            if (!predicate.apply(t)) {
324              return false;
325            }
326          }
327          return true;
328        }
329        @Override public int hashCode() {
330          // 0x12472c2c is a random number to help avoid collisions with OrPredicate
331          return components.hashCode() + 0x12472c2c;
332        }
333        @Override public boolean equals(@Nullable Object obj) {
334          if (obj instanceof AndPredicate) {
335            AndPredicate<?> that = (AndPredicate<?>) obj;
336            return components.equals(that.components);
337          }
338          return false;
339        }
340        @Override public String toString() {
341          return "And(" + COMMA_JOINER.join(components) + ")";
342        }
343        private static final long serialVersionUID = 0;
344      }
345    
346      /** @see Predicates#or(Iterable) */
347      private static class OrPredicate<T> implements Predicate<T>, Serializable {
348        private final List<? extends Predicate<? super T>> components;
349    
350        private OrPredicate(List<? extends Predicate<? super T>> components) {
351          this.components = components;
352        }
353        @Override
354        public boolean apply(T t) {
355          for (Predicate<? super T> predicate : components) {
356            if (predicate.apply(t)) {
357              return true;
358            }
359          }
360          return false;
361        }
362        @Override public int hashCode() {
363          // 0x053c91cf is a random number to help avoid collisions with AndPredicate
364          return components.hashCode() + 0x053c91cf;
365        }
366        @Override public boolean equals(@Nullable Object obj) {
367          if (obj instanceof OrPredicate) {
368            OrPredicate<?> that = (OrPredicate<?>) obj;
369            return components.equals(that.components);
370          }
371          return false;
372        }
373        @Override public String toString() {
374          return "Or(" + COMMA_JOINER.join(components) + ")";
375        }
376        private static final long serialVersionUID = 0;
377      }
378    
379      /** @see Predicates#equalTo(Object) */
380      private static class IsEqualToPredicate<T>
381          implements Predicate<T>, Serializable {
382        private final T target;
383    
384        private IsEqualToPredicate(T target) {
385          this.target = target;
386        }
387        @Override
388        public boolean apply(T t) {
389          return target.equals(t);
390        }
391        @Override public int hashCode() {
392          return target.hashCode();
393        }
394        @Override public boolean equals(@Nullable Object obj) {
395          if (obj instanceof IsEqualToPredicate) {
396            IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
397            return target.equals(that.target);
398          }
399          return false;
400        }
401        @Override public String toString() {
402          return "IsEqualTo(" + target + ")";
403        }
404        private static final long serialVersionUID = 0;
405      }
406    
407      /** @see Predicates#instanceOf(Class) */
408      private static class InstanceOfPredicate
409          implements Predicate<Object>, Serializable {
410        private final Class<?> clazz;
411    
412        private InstanceOfPredicate(Class<?> clazz) {
413          this.clazz = checkNotNull(clazz);
414        }
415        @Override
416        public boolean apply(@Nullable Object o) {
417          return Platform.isInstance(clazz, o);
418        }
419        @Override public int hashCode() {
420          return clazz.hashCode();
421        }
422        @Override public boolean equals(@Nullable Object obj) {
423          if (obj instanceof InstanceOfPredicate) {
424            InstanceOfPredicate that = (InstanceOfPredicate) obj;
425            return clazz == that.clazz;
426          }
427          return false;
428        }
429        @Override public String toString() {
430          return "IsInstanceOf(" + clazz.getName() + ")";
431        }
432        private static final long serialVersionUID = 0;
433      }
434    
435      /** @see Predicates#in(Collection) */
436      private static class InPredicate<T> implements Predicate<T>, Serializable {
437        private final Collection<?> target;
438    
439        private InPredicate(Collection<?> target) {
440          this.target = checkNotNull(target);
441        }
442    
443        @Override
444        public boolean apply(T t) {
445          try {
446            return target.contains(t);
447          } catch (NullPointerException e) {
448            return false;
449          } catch (ClassCastException e) {
450            return false;
451          }
452        }
453    
454        @Override public boolean equals(@Nullable Object obj) {
455          if (obj instanceof InPredicate) {
456            InPredicate<?> that = (InPredicate<?>) obj;
457            return target.equals(that.target);
458          }
459          return false;
460        }
461    
462        @Override public int hashCode() {
463          return target.hashCode();
464        }
465    
466        @Override public String toString() {
467          return "In(" + target + ")";
468        }
469        private static final long serialVersionUID = 0;
470      }
471    
472      /** @see Predicates#compose(Predicate, Function) */
473      private static class CompositionPredicate<A, B>
474          implements Predicate<A>, Serializable {
475        final Predicate<B> p;
476        final Function<A, ? extends B> f;
477    
478        private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
479          this.p = checkNotNull(p);
480          this.f = checkNotNull(f);
481        }
482    
483        @Override
484        public boolean apply(A a) {
485          return p.apply(f.apply(a));
486        }
487    
488        @Override public boolean equals(@Nullable Object obj) {
489          if (obj instanceof CompositionPredicate) {
490            CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
491            return f.equals(that.f) && p.equals(that.p);
492          }
493          return false;
494        }
495    
496        @Override public int hashCode() {
497          return f.hashCode() ^ p.hashCode();
498        }
499    
500        @Override public String toString() {
501          return p.toString() + "(" + f.toString() + ")";
502        }
503    
504        private static final long serialVersionUID = 0;
505      }
506    
507      /**
508       * @see Predicates#contains(Pattern)
509       * @see Predicates#containsPattern(String)
510       */
511      @GwtIncompatible("Only used by other GWT-incompatible code.")
512      private static class ContainsPatternPredicate
513          implements Predicate<CharSequence>, Serializable {
514        final Pattern pattern;
515    
516        ContainsPatternPredicate(Pattern pattern) {
517          this.pattern = checkNotNull(pattern);
518        }
519    
520        ContainsPatternPredicate(String patternStr) {
521          this(Pattern.compile(patternStr));
522        }
523    
524        @Override
525        public boolean apply(CharSequence t) {
526          return pattern.matcher(t).find();
527        }
528    
529        @Override public int hashCode() {
530          // Pattern uses Object.hashCode, so we have to reach
531          // inside to build a hashCode consistent with equals.
532    
533          return Objects.hashCode(pattern.pattern(), pattern.flags());
534        }
535    
536        @Override public boolean equals(@Nullable Object obj) {
537          if (obj instanceof ContainsPatternPredicate) {
538            ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
539    
540            // Pattern uses Object (identity) equality, so we have to reach
541            // inside to compare individual fields.
542            return Objects.equal(pattern.pattern(), that.pattern.pattern())
543                && Objects.equal(pattern.flags(), that.pattern.flags());
544          }
545          return false;
546        }
547    
548        @Override public String toString() {
549          return Objects.toStringHelper(this)
550              .add("pattern", pattern)
551              .add("pattern.flags", Integer.toHexString(pattern.flags()))
552              .toString();
553        }
554    
555        private static final long serialVersionUID = 0;
556      }
557    
558      @SuppressWarnings("unchecked")
559      private static <T> List<Predicate<? super T>> asList(
560          Predicate<? super T> first, Predicate<? super T> second) {
561        return Arrays.<Predicate<? super T>>asList(first, second);
562      }
563    
564      private static <T> List<T> defensiveCopy(T... array) {
565        return defensiveCopy(Arrays.asList(array));
566      }
567    
568      static <T> List<T> defensiveCopy(Iterable<T> iterable) {
569        ArrayList<T> list = new ArrayList<T>();
570        for (T element : iterable) {
571          list.add(checkNotNull(element));
572        }
573        return list;
574      }
575    }