001package org.gbif.api.util;
002
003import java.net.URI;
004import javax.validation.ConstraintValidator;
005import javax.validation.ConstraintValidatorContext;
006
007/**
008 * Constrain validator that validates URI objects with a @HttpURI annotation.
009 */
010public class URIValidator implements ConstraintValidator<HttpURI, URI> {
011
012  private static final String HTTP_PROTOCOL = "http";
013  private static final String HTTPS_PROTOCOL = "https";
014
015  /**
016   * Initializes the validator in preparation for
017   * {@link #isValid(Object, javax.validation.ConstraintValidatorContext)} calls.
018   * The constraint annotation for a given constraint declaration
019   * is passed.
020   * This method is guaranteed to be called before any use of this instance for
021   * validation.
022   *
023   * @param uri annotation instance for a given constraint declaration
024   */
025  @Override
026  public void initialize(HttpURI uri) {
027  }
028
029  /**
030   * Implements the validation logic, checking if a URI is valid or not.
031   * The state of {@code value} must not be altered.
032   * This method can be accessed concurrently, thread-safety must be ensured
033   * by the implementation.
034   *
035   * @param uri   object to validate
036   * @param context context in which the constraint is evaluated
037   *
038   * @return {@code false} if {@code value} does not pass the constraint
039   */
040  @Override
041  public boolean isValid(URI uri, ConstraintValidatorContext context) {
042    // only validate non-null URIs
043    if (uri == null) {
044      return true;
045    }
046
047    // URI scheme can not be null
048    if (uri.getScheme() == null) {
049      return false;
050    }
051
052    // URI must begin with either: http or https
053    if (uri.getScheme().equalsIgnoreCase(HTTP_PROTOCOL) || uri.getScheme().equalsIgnoreCase(HTTPS_PROTOCOL)) {
054      return true;
055    }
056
057    // otherwise, the URI is invalid
058    return false;
059  }
060}