MediumTypeValidator.java

  1. /*
  2.  * Copyright 2023 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 org.genesys.blocks.util.CurrentApplicationContext;
  18. import org.gringlobal.model.Materiel;
  19. import org.gringlobal.service.MaterielService;

  20. import javax.validation.ConstraintValidator;
  21. import javax.validation.ConstraintValidatorContext;
  22. import java.util.Objects;

  23. public class MediumTypeValidator implements ConstraintValidator<MediumTypeField, Materiel> {

  24.     private String mediumType;
  25.    
  26.     @Override
  27.     public void initialize(MediumTypeField constraintAnnotation) {
  28.         this.mediumType = constraintAnnotation.value();
  29.     }

  30.     @Override
  31.     public boolean isValid(Materiel value, ConstraintValidatorContext context) {
  32.         if (value == null) {
  33.             return true;
  34.         }
  35.         assert value.getId() != null;
  36.         if (value.getTypeCode() == null) {
  37.             var materielRepository = CurrentApplicationContext.getContext().getBean(MaterielService.class);
  38.             value = materielRepository.get(value.getId());
  39.         }
  40.         return Objects.equals(mediumType, value.getTypeCode());
  41.     }
  42. }