001    /*
002     * Copyright (C) 2007 Google Inc.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005     * use this file except in compliance with the License. You may obtain a copy of
006     * 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, WITHOUT
012     * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013     * License for the specific language governing permissions and limitations under
014     * 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        public boolean apply(T t) {
292          return !predicate.apply(t);
293        }
294        @Override public int hashCode() {
295          return ~predicate.hashCode();
296        }
297        @Override public boolean equals(@Nullable Object obj) {
298          if (obj instanceof NotPredicate) {
299            NotPredicate<?> that = (NotPredicate<?>) obj;
300            return predicate.equals(that.predicate);
301          }
302          return false;
303        }
304        @Override public String toString() {
305          return "Not(" + predicate.toString() + ")";
306        }
307        private static final long serialVersionUID = 0;
308      }
309    
310      private static final Joiner COMMA_JOINER = Joiner.on(",");
311    
312      /** @see Predicates#and(Iterable) */
313      private static class AndPredicate<T> implements Predicate<T>, Serializable {
314        private final List<? extends Predicate<? super T>> components;
315    
316        private AndPredicate(List<? extends Predicate<? super T>> components) {
317          this.components = components;
318        }
319        public boolean apply(T t) {
320          for (Predicate<? super T> predicate : components) {
321            if (!predicate.apply(t)) {
322              return false;
323            }
324          }
325          return true;
326        }
327        @Override public int hashCode() {
328          // 0x12472c2c is a random number to help avoid collisions with OrPredicate
329          return components.hashCode() + 0x12472c2c;
330        }
331        @Override public boolean equals(@Nullable Object obj) {
332          if (obj instanceof AndPredicate) {
333            AndPredicate<?> that = (AndPredicate<?>) obj;
334            return components.equals(that.components);
335          }
336          return false;
337        }
338        @Override public String toString() {
339          return "And(" + COMMA_JOINER.join(components) + ")";
340        }
341        private static final long serialVersionUID = 0;
342      }
343    
344      /** @see Predicates#or(Iterable) */
345      private static class OrPredicate<T> implements Predicate<T>, Serializable {
346        private final List<? extends Predicate<? super T>> components;
347    
348        private OrPredicate(List<? extends Predicate<? super T>> components) {
349          this.components = components;
350        }
351        public boolean apply(T t) {
352          for (Predicate<? super T> predicate : components) {
353            if (predicate.apply(t)) {
354              return true;
355            }
356          }
357          return false;
358        }
359        @Override public int hashCode() {
360          // 0x053c91cf is a random number to help avoid collisions with AndPredicate
361          return components.hashCode() + 0x053c91cf;
362        }
363        @Override public boolean equals(@Nullable Object obj) {
364          if (obj instanceof OrPredicate) {
365            OrPredicate<?> that = (OrPredicate<?>) obj;
366            return components.equals(that.components);
367          }
368          return false;
369        }
370        @Override public String toString() {
371          return "Or(" + COMMA_JOINER.join(components) + ")";
372        }
373        private static final long serialVersionUID = 0;
374      }
375    
376      /** @see Predicates#equalTo(Object) */
377      private static class IsEqualToPredicate<T>
378          implements Predicate<T>, Serializable {
379        private final T target;
380    
381        private IsEqualToPredicate(T target) {
382          this.target = target;
383        }
384        public boolean apply(T t) {
385          return target.equals(t);
386        }
387        @Override public int hashCode() {
388          return target.hashCode();
389        }
390        @Override public boolean equals(@Nullable Object obj) {
391          if (obj instanceof IsEqualToPredicate) {
392            IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
393            return target.equals(that.target);
394          }
395          return false;
396        }
397        @Override public String toString() {
398          return "IsEqualTo(" + target + ")";
399        }
400        private static final long serialVersionUID = 0;
401      }
402    
403      /** @see Predicates#instanceOf(Class) */
404      private static class InstanceOfPredicate
405          implements Predicate<Object>, Serializable {
406        private final Class<?> clazz;
407    
408        private InstanceOfPredicate(Class<?> clazz) {
409          this.clazz = checkNotNull(clazz);
410        }
411        public boolean apply(@Nullable Object o) {
412          return Platform.isInstance(clazz, o);
413        }
414        @Override public int hashCode() {
415          return clazz.hashCode();
416        }
417        @Override public boolean equals(@Nullable Object obj) {
418          if (obj instanceof InstanceOfPredicate) {
419            InstanceOfPredicate that = (InstanceOfPredicate) obj;
420            return clazz == that.clazz;
421          }
422          return false;
423        }
424        @Override public String toString() {
425          return "IsInstanceOf(" + clazz.getName() + ")";
426        }
427        private static final long serialVersionUID = 0;
428      }
429    
430      /** @see Predicates#in(Collection) */
431      private static class InPredicate<T> implements Predicate<T>, Serializable {
432        private final Collection<?> target;
433    
434        private InPredicate(Collection<?> target) {
435          this.target = checkNotNull(target);
436        }
437    
438        public boolean apply(T t) {
439          try {
440            return target.contains(t);
441          } catch (NullPointerException e) {
442            return false;
443          } catch (ClassCastException e) {
444            return false;
445          }
446        }
447    
448        @Override public boolean equals(@Nullable Object obj) {
449          if (obj instanceof InPredicate) {
450            InPredicate<?> that = (InPredicate<?>) obj;
451            return target.equals(that.target);
452          }
453          return false;
454        }
455    
456        @Override public int hashCode() {
457          return target.hashCode();
458        }
459    
460        @Override public String toString() {
461          return "In(" + target + ")";
462        }
463        private static final long serialVersionUID = 0;
464      }
465    
466      /** @see Predicates#compose(Predicate, Function) */
467      private static class CompositionPredicate<A, B>
468          implements Predicate<A>, Serializable {
469        final Predicate<B> p;
470        final Function<A, ? extends B> f;
471    
472        private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
473          this.p = checkNotNull(p);
474          this.f = checkNotNull(f);
475        }
476    
477        public boolean apply(A a) {
478          return p.apply(f.apply(a));
479        }
480    
481        @Override public boolean equals(@Nullable Object obj) {
482          if (obj instanceof CompositionPredicate) {
483            CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
484            return f.equals(that.f) && p.equals(that.p);
485          }
486          return false;
487        }
488    
489        @Override public int hashCode() {
490          return f.hashCode() ^ p.hashCode();
491        }
492    
493        @Override public String toString() {
494          return p.toString() + "(" + f.toString() + ")";
495        }
496    
497        private static final long serialVersionUID = 0;
498      }
499    
500      /**
501       * @see Predicates#contains(Pattern)
502       * @see Predicates#containsPattern(String)
503       */
504      @GwtIncompatible("Only used by other GWT-incompatible code.")
505      private static class ContainsPatternPredicate
506          implements Predicate<CharSequence>, Serializable {
507        final Pattern pattern;
508    
509        ContainsPatternPredicate(Pattern pattern) {
510          this.pattern = checkNotNull(pattern);
511        }
512    
513        ContainsPatternPredicate(String patternStr) {
514          this(Pattern.compile(patternStr));
515        }
516    
517        public boolean apply(CharSequence t) {
518          return pattern.matcher(t).find();
519        }
520    
521        @Override public int hashCode() {
522          // Pattern uses Object.hashCode, so we have to reach
523          // inside to build a hashCode consistent with equals.
524    
525          return Objects.hashCode(pattern.pattern(), pattern.flags());
526        }
527    
528        @Override public boolean equals(@Nullable Object obj) {
529          if (obj instanceof ContainsPatternPredicate) {
530            ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
531    
532            // Pattern uses Object (identity) equality, so we have to reach
533            // inside to compare individual fields.
534            return Objects.equal(pattern.pattern(), that.pattern.pattern())
535                && Objects.equal(pattern.flags(), that.pattern.flags());
536          }
537          return false;
538        }
539    
540        @Override public String toString() {
541          return Objects.toStringHelper(this)
542              .add("pattern", pattern)
543              .add("pattern.flags", Integer.toHexString(pattern.flags()))
544              .toString();
545        }
546    
547        private static final long serialVersionUID = 0;
548      }
549    
550      @SuppressWarnings("unchecked")
551      private static <T> List<Predicate<? super T>> asList(
552          Predicate<? super T> first, Predicate<? super T> second) {
553        return Arrays.<Predicate<? super T>>asList(first, second);
554      }
555    
556      private static <T> List<T> defensiveCopy(T... array) {
557        return defensiveCopy(Arrays.asList(array));
558      }
559    
560      static <T> List<T> defensiveCopy(Iterable<T> iterable) {
561        ArrayList<T> list = new ArrayList<T>();
562        for (T element : iterable) {
563          list.add(checkNotNull(element));
564        }
565        return list;
566      }
567    }