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.Date;
022import javax.validation.constraints.NotNull;
023
024import com.google.common.base.Objects;
025import com.google.common.base.Preconditions;
026
027public class SimplePredicate implements Predicate {
028
029  @NotNull
030  private final OccurrenceSearchParameter key;
031
032  @NotNull
033  private final String value;
034
035  protected SimplePredicate(boolean checkForNonEquals, OccurrenceSearchParameter key, String value) {
036    Preconditions.checkNotNull(key, "<key> may not be null");
037    Preconditions.checkNotNull(value, "<value> may not be null");
038    Preconditions.checkArgument(!value.isEmpty(), "<value> may not be empty");
039    // make sure the value is of the right type according to the key given
040    SearchTypeValidator.validate(key, value);
041
042    this.key = key;
043    this.value = value;
044
045    if (checkForNonEquals) {
046      checkNonEqualsComparatorAllowed();
047    }
048  }
049
050  public OccurrenceSearchParameter getKey() {
051    return key;
052  }
053
054  public String getValue() {
055    return value;
056  }
057
058  /**
059   * @throws IllegalArgumentException if the key SearchParameter allows other comparators than equals
060   */
061  private void checkNonEqualsComparatorAllowed() {
062    if (!(Number.class.isAssignableFrom(key.type()) || Date.class.isAssignableFrom(key.type()))){
063      throw new IllegalArgumentException("Only equals comparisons are allowed for search parameter " + key);
064    }
065  }
066
067  @Override
068  public int hashCode() {
069    return Objects.hashCode(key, value);
070  }
071
072  @Override
073  public String toString() {
074    return Objects.toStringHelper(this).add("key", key).add("value", value).toString();
075  }
076
077}