CodeValueValidator.java

  1. /*
  2.  * Copyright 2020 Global Crop Diversity Trust
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *   http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. package org.gringlobal.custom.validation.javax;

  17. import javax.validation.ConstraintValidator;
  18. import javax.validation.ConstraintValidatorContext;

  19. import org.apache.commons.lang3.StringUtils;
  20. import org.gringlobal.component.elastic.AppContextHelper;

  21. /**
  22.  * @author Maxym Borodenko
  23.  */
  24. public class CodeValueValidator implements ConstraintValidator<CodeValueField, String> {

  25.     /**
  26.      * Specified group.
  27.      */
  28.     private String groupName;

  29.     /**
  30.      * When not strict then validation is skipped.
  31.      */
  32.     private boolean strict;

  33.     /**
  34.      * Initializes the validator.
  35.      */
  36.     @Override
  37.     public void initialize(CodeValueField constraintAnnotation) {
  38.         this.groupName = constraintAnnotation.value();
  39.         this.strict = constraintAnnotation.strict();
  40.     }

  41.     /**
  42.      * Implements the validation logic.
  43.      * @return {@code false} if {@code value} isn't defined in the specified group
  44.      */
  45.     @Override
  46.     public boolean isValid(String value, ConstraintValidatorContext context) {
  47.         if (StringUtils.isBlank(value) || !strict) {
  48.             return true; // nothing to validate here
  49.         }

  50.         if (! AppContextHelper.validateCodeValue(groupName, value)) {
  51.             context.disableDefaultConstraintViolation();
  52.             String message = value + " is not a valid CodeValue of " + groupName;
  53.             context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
  54.             return false;
  55.         }

  56.         return true;
  57.     }

  58. }