001/*
002 * Copyright 2014 Global Biodiversity Information Facility (GBIF)
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 */
016package org.gbif.api.model.occurrence.predicate;
017
018import java.util.Collection;
019import javax.validation.constraints.NotNull;
020
021import com.google.common.base.Objects;
022import com.google.common.base.Preconditions;
023import com.google.common.collect.ImmutableList;
024import org.codehaus.jackson.annotate.JsonCreator;
025import org.codehaus.jackson.annotate.JsonProperty;
026
027/**
028 * A compound predicate is a Predicate that itself contains other Predicates.
029 * This is to be used as a base class because the way the containing Predicates
030 * should be combined needs to be specified (e.g. "AND", "OR").
031 */
032public class CompoundPredicate implements Predicate {
033
034  @NotNull
035  private final Collection<Predicate> predicates;
036
037  @JsonCreator
038  protected CompoundPredicate(@JsonProperty("predicates") Collection<Predicate> predicates) {
039    Preconditions.checkNotNull(predicates, "Predicates may not be null");
040    Preconditions.checkArgument(!predicates.isEmpty(), "Predicates may not be empty");
041    this.predicates = ImmutableList.copyOf(predicates);
042  }
043
044  /**
045   * Returns all the predicates this compound predicate is made out of in an <em>immutable</em> collection.
046   *
047   * @return the immutable collection of child predicates.
048   */
049  public Collection<Predicate> getPredicates() {
050    return predicates;
051  }
052
053  @Override
054  public boolean equals(Object obj) {
055    if (this == obj) {
056      return true;
057    }
058    if (!(obj instanceof CompoundPredicate)) {
059      return true;
060    }
061
062    final CompoundPredicate other = (CompoundPredicate) obj;
063    return Objects.equal(this.predicates, other.predicates);
064  }
065
066  @Override
067  public int hashCode() {
068    return Objects.hashCode(predicates);
069  }
070
071  @Override
072  public String toString() {
073    return Objects.toStringHelper(this).add("predicates", predicates).toString();
074  }
075}