001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.api.model.predicate;
015
016import java.util.ArrayList;
017import java.util.Collection;
018import java.util.Collections;
019import java.util.Objects;
020import java.util.StringJoiner;
021
022import javax.validation.constraints.NotNull;
023
024import com.fasterxml.jackson.annotation.JsonCreator;
025import com.fasterxml.jackson.annotation.JsonProperty;
026
027import io.swagger.v3.oas.annotations.media.Schema;
028
029import static org.gbif.api.util.PreconditionUtils.checkArgument;
030
031/**
032 * A compound predicate is a Predicate that itself contains other Predicates.
033 * This is to be used as a base class because the way the containing Predicates
034 * should be combined needs to be specified (e.g. "AND", "OR").
035 */
036public class CompoundPredicate implements Predicate {
037
038  @Schema(
039    description = "The list of sub-predicates to combine"
040  )
041  @NotNull
042  private final Collection<Predicate> predicates;
043
044  @JsonCreator
045  protected CompoundPredicate(@JsonProperty("predicates") Collection<Predicate> predicates) {
046    Objects.requireNonNull(predicates, "Predicates may not be null");
047    checkArgument(!predicates.isEmpty(), "Predicates may not be empty");
048    this.predicates = Collections.unmodifiableList(new ArrayList<>(predicates));
049  }
050
051  /**
052   * Returns all the predicates this compound predicate is made out of in an <em>immutable</em> collection.
053   *
054   * @return the immutable collection of child predicates.
055   */
056  public Collection<Predicate> getPredicates() {
057    return predicates;
058  }
059
060  @Override
061  public boolean equals(Object o) {
062    if (this == o) {
063      return true;
064    }
065    if (o == null || getClass() != o.getClass()) {
066      return false;
067    }
068    CompoundPredicate that = (CompoundPredicate) o;
069    return Objects.equals(predicates, that.predicates);
070  }
071
072  @Override
073  public int hashCode() {
074    return Objects.hash(predicates);
075  }
076
077  @Override
078  public String toString() {
079    return new StringJoiner(", ", this.getClass().getSimpleName() + "[", "]")
080      .add("predicates=" + predicates)
081      .toString();
082  }
083}