ValidUrlValidator.java

/*
 * Copyright 2024 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.spring.validation.javax;

import java.net.URL;
import java.util.Collection;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author Matija Obreza
 */
public class ValidUrlValidator implements ConstraintValidator<ValidUrl, String> {

	/**
	 * Initializes the validator.
	 */
	@Override
	public void initialize(ValidUrl constraintAnnotation) {
	}

	/**
	 * Implements the validation logic.
	 * @return {@code false} if {@code value} is not a valid URL
	 */
	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if (value == null) {
			return true;
		}
		return isUrl(value);
	}

	private static boolean isUrl(String value) {
		if (value == null || !value.trim().equals(value)) return false;
		try {
			new URL(value);
			return true;
		} catch (Throwable e) {
			return false;
		}
	}


	public static class ValidUrlCollectionValidator implements ConstraintValidator<ValidUrl, Collection<String>> {
		/**
		 * Initializes the validator.
		 */
		@Override
		public void initialize(ValidUrl constraintAnnotation) {
		}
	
		/**
		 * Implements the validation logic.
		 * @return {@code false} if any {@code value} is not a valid URL
		 */
		@Override
		public boolean isValid(Collection<String> values, ConstraintValidatorContext context) {
			if (values == null || values.isEmpty()) {
				return true;
			}
			return values.stream()
				.map(ValidUrlValidator::isUrl)
				.filter(result -> result == false)
				.findFirst().isEmpty();
		}
	}
}