/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.util;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.scytl.products.ov.commons.beans.exceptions.SemanticErrorException;
import com.scytl.products.ov.commons.beans.errors.SemanticErrorGroup;
import com.scytl.products.ov.commons.beans.exceptions.SyntaxErrorException;
import com.scytl.products.ov.commons.beans.errors.SyntaxErrorGroup;

/**
 * Class used to provide validation utilities.
 */
public final class ValidationUtils {

	private ValidationUtils() {
		// empty constructor.
	}

	/**
	 * Applies javax.validations in a programmatically way by applying the set of validations defined in the class using
	 * annotations like @NotNull, @Size, @Pattern, etc.
	 * 
	 * @param object - the object to be validated.
	 * @throws com.scytl.products.ov.commons.application.ValidationException if the object does not pass validations. This
	 *         exception is handled by ValidationExceptionHandler and returns a status code 422 for unprocessable entity.
	 */
	public static <T> void validate(T object) throws SyntaxErrorException, SemanticErrorException {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();
		Set<ConstraintViolation<T>> syntaxErrors = validator.validate(object, SyntaxErrorGroup.class);
		if (!syntaxErrors.isEmpty()) {
			throw new SyntaxErrorException(syntaxErrors);
		}

		Set<ConstraintViolation<T>> semanticErrors = validator.validate(object, SemanticErrorGroup.class);
		if (!semanticErrors.isEmpty()) {
			throw new SemanticErrorException(semanticErrors);
		}
	}
}
