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 org.gbif.api.model.occurrence.search.OccurrenceSearchParameter;
019import org.gbif.api.util.SearchTypeValidator;
020
021import java.util.Collection;
022import javax.validation.constraints.NotNull;
023import javax.validation.constraints.Size;
024
025import com.google.common.base.Objects;
026import com.google.common.base.Preconditions;
027import com.google.common.collect.ImmutableList;
028import org.codehaus.jackson.annotate.JsonCreator;
029import org.codehaus.jackson.annotate.JsonProperty;
030
031/**
032 * This predicate checks if its {@code key} contains any of its {@code values}.
033 */
034public class InPredicate implements Predicate {
035
036  @NotNull
037  private final OccurrenceSearchParameter key;
038
039  @NotNull
040  @Size(min = 1)
041  private final Collection<String> values;
042
043  @JsonCreator
044  public InPredicate(@JsonProperty("key") OccurrenceSearchParameter key, @JsonProperty("values") Collection<String> values) {
045    Preconditions.checkNotNull(key, "<key> may not be null");
046    Preconditions.checkNotNull(values, "<values> may not be null");
047    Preconditions.checkArgument(!values.isEmpty(), "<values> may not be empty");
048    // make sure the value is of the right type according to the key given
049    for (String value : values) {
050      SearchTypeValidator.validate(key, value);
051    }
052
053    this.key = key;
054    this.values = ImmutableList.copyOf(values);
055  }
056
057  public OccurrenceSearchParameter getKey() {
058    return key;
059  }
060
061  public Collection<String> getValues() {
062    return values;
063  }
064
065  @Override
066  public boolean equals(Object obj) {
067    if (this == obj) {
068      return true;
069    }
070
071    if (!(obj instanceof InPredicate)) {
072      return false;
073    }
074
075    InPredicate that = (InPredicate) obj;
076    return Objects.equal(this.key, that.getKey()) && Objects.equal(this.values, that.getValues());
077  }
078
079  @Override
080  public int hashCode() {
081    return Objects.hashCode(key, values);
082  }
083
084  @Override
085  public String toString() {
086    return Objects.toStringHelper(this).add("key", key).add("values", values).toString();
087  }
088}