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 org.gbif.api.model.common.search.SearchParameter;
017import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter;
018import org.gbif.api.util.IsoDateInterval;
019import org.gbif.api.util.SearchTypeValidator;
020
021import java.util.Date;
022import java.util.Objects;
023import java.util.Optional;
024import java.util.StringJoiner;
025
026import com.fasterxml.jackson.annotation.JsonIgnore;
027import com.fasterxml.jackson.annotation.JsonProperty;
028
029import io.swagger.v3.oas.annotations.media.Schema;
030import jakarta.annotation.Nullable;
031import jakarta.validation.constraints.NotNull;
032
033import static org.gbif.api.util.PreconditionUtils.checkArgument;
034
035public class SimplePredicate<S extends SearchParameter> implements Predicate {
036
037  @Schema(
038    description = "The search parameter to test.",
039    implementation = SearchParameter.class
040  )
041  @NotNull
042  private final S key;
043
044  @Schema(
045    description = "The value to test for."
046  )
047  @NotNull
048  private final String value;
049
050  @Schema(
051    description = "Whether to match letter case (UPPER or lower case) on string value comparisons."
052  )
053  @Nullable
054  private final Boolean matchCase;
055
056  protected SimplePredicate(boolean checkForNonEquals, S key, String value, Boolean matchCase) {
057    this.matchCase = matchCase;
058    Objects.requireNonNull(key, "<key> may not be null");
059    Objects.requireNonNull(value, "<value> may not be null");
060    checkArgument(!value.isEmpty(), "<value> may not be empty");
061    // make sure the value is of the right type according to the key given
062    SearchTypeValidator.validate(key, value);
063
064    this.key = key;
065    this.value = value;
066
067    checkPredicateAllowed();
068    if (checkForNonEquals) {
069      checkNonEqualsComparatorAllowed();
070    }
071  }
072
073  public S getKey() {
074    return key;
075  }
076
077  public String getValue() {
078    return value;
079  }
080
081  /**
082   * This flag enables the use of case-sensitive matches and aggregations on certain search parameters.
083   * <p>
084   * Fields that support this feature are: occurrenceId, recordedBy, samplingProtocol, catalogNumber, collectionCode,
085   * institutionCode, eventId, parentEventId, waterBody, stateProvince, recordNumber, identifiedBy, organismId and locality.
086   */
087  @JsonIgnore
088  public Boolean isMatchCase() {
089    return Optional.ofNullable(matchCase).orElse(Boolean.FALSE);
090  }
091
092  @JsonProperty("matchCase")
093  public Boolean getMatchCase() {
094    return matchCase;
095  }
096
097  /**
098   * @throws IllegalArgumentException if the key SearchParameter is Geometry
099   */
100  private void checkPredicateAllowed() {
101    if (OccurrenceSearchParameter.GEOMETRY == key) {
102      throw new IllegalArgumentException("Geometry parameter must use a Within predicate");
103    }
104  }
105
106  /**
107   * @throws IllegalArgumentException if the key SearchParameter allows other comparators than
108   *                                  equals
109   */
110  private void checkNonEqualsComparatorAllowed() {
111    if (!(Number.class.isAssignableFrom(key.type())
112        || Date.class.isAssignableFrom(key.type())
113        || IsoDateInterval.class.isAssignableFrom(key.type())
114        || OccurrenceSearchParameter.GEOLOGICAL_TIME == key)) {
115      throw new IllegalArgumentException(
116          "Only equals comparisons are allowed for search parameter "
117              + key
118              + " of type "
119              + key.type());
120    }
121  }
122
123  @Override
124  public boolean equals(Object o) {
125    if (this == o) {
126      return true;
127    }
128    if (o == null || getClass() != o.getClass()) {
129      return false;
130    }
131    SimplePredicate<S> that = (SimplePredicate<S>) o;
132    return key == that.key && Objects.equals(value, that.value) && matchCase == that.matchCase;
133  }
134
135  @Override
136  public int hashCode() {
137    return Objects.hash(key, value, matchCase);
138  }
139
140  @Override
141  public String toString() {
142    return new StringJoiner(", ", this.getClass().getSimpleName() + "[", "]")
143      .add("key=" + key)
144      .add("value='" + value + "'")
145      .add("matchCase='" + matchCase + "'")
146      .toString();
147  }
148}