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