001/*
002 * Copyright 2014 Global Biodiversity Information Facility (GBIF)
003 * Licensed under the Apache License, Version 2.0 (the "License");
004 * you may not use this file except in compliance with the License.
005 * You may obtain a copy of the License at
006 * http://www.apache.org/licenses/LICENSE-2.0
007 * Unless required by applicable law or agreed to in writing, software
008 * distributed under the License is distributed on an "AS IS" BASIS,
009 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
010 * See the License for the specific language governing permissions and
011 * limitations under the License.
012 */
013package org.gbif.api.model.occurrence.predicate;
014
015import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter;
016import org.gbif.api.util.SearchTypeValidator;
017
018import javax.validation.constraints.NotNull;
019
020import com.google.common.base.Objects;
021import com.google.common.base.Preconditions;
022import org.codehaus.jackson.annotate.JsonCreator;
023import org.codehaus.jackson.annotate.JsonProperty;
024
025/**
026 * This predicate checks if an occurrence location falls within the given WKT geometry {@code value}.
027 */
028public class WithinPredicate implements Predicate {
029
030  @NotNull
031  private final String geometry;
032
033  /**
034   * Builds a new within predicate for a single, simple geometry as
035   * <a href="http://en.wikipedia.org/wiki/Well-known_text">Well Known Text</a> (WKT).
036   * Multi geometries like MULTIPOLYGON are not supported and multiple predicates should be used instead.
037   * <br/>
038   * The validation implemented does a basic syntax check for the following simple geometries, but does not
039   * verify that the resulting geometries are topologically valid (see the OGC SFS specification).
040   * <ul>
041   *   <li>POINT</li>
042   *   <li>LINESTRING</li>
043   *   <li>POLYGON</li>
044   *   <li>LINEARRING</li>
045   * </ul>
046   * @param geometry
047   */
048  @JsonCreator
049  public WithinPredicate(@JsonProperty("geometry") String geometry) {
050    Preconditions.checkNotNull(geometry, "<geometry> may not be null");
051    // make sure its a valid WKT
052    SearchTypeValidator.validate(OccurrenceSearchParameter.GEOMETRY, geometry);
053    this.geometry = geometry;
054  }
055
056  public String getGeometry() {
057    return geometry;
058  }
059
060  @Override
061  public boolean equals(Object obj) {
062    if (this == obj) {
063      return true;
064    }
065
066    if (!(obj instanceof WithinPredicate)) {
067      return false;
068    }
069
070    WithinPredicate that = (WithinPredicate) obj;
071    return Objects.equal(this.geometry, that.geometry);
072  }
073
074  @Override
075   public int hashCode() {
076     return Objects.hashCode(geometry);
077   }
078
079   @Override
080   public String toString() {
081     return Objects.toStringHelper(this).add("geometry", geometry).toString();
082   }
083
084}