CodeValueValidator.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.custom.validation.javax;

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

import org.gringlobal.component.elastic.AppContextHelper;
import org.gringlobal.service.CodeValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Maxym Borodenko
 */
@Component
public class CodeValueValidator implements ConstraintValidator<CodeValueField, String> {

	@Autowired
	private CodeValueService codeValueService;

	/**
	 * Specified group.
	 */
	private String groupName;

	/**
	 * When not strict then validation is skipped.
	 */
	private boolean strict;

	/**
	 * Initializes the validator.
	 */
	@Override
	public void initialize(CodeValueField constraintAnnotation) {
		this.groupName = constraintAnnotation.value();
		this.strict = constraintAnnotation.strict();
	}

	/**
	 * Implements the validation logic.
	 * @return {@code false} if {@code value} isn't defined in the specified group
	 */
	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if (value == null || !strict) {
			return true; // nothing to validate here
		}

		if (codeValueService != null) {
			if (!codeValueService.validate(groupName, value)) {
				context.disableDefaultConstraintViolation();
				String message = value + " is not a valid CodeValue of " + groupName;
				context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
				return false;
			}
		} else if (! AppContextHelper.validateCodeValue(groupName, value)) {
			context.disableDefaultConstraintViolation();
			String message = value + " is not a valid CodeValue of " + groupName;
			context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
			return false;
		}

		return true;
	}

}