Java tutorial
/******************************************************************************* * Educational Online Test Delivery System * Copyright (c) 2013 American Institutes for Research * * Distributed under the AIR Open Source License, Version 1.0 * See accompanying file AIR-License-1_0.txt or at * http://www.smarterapp.org/documents/American_Institutes_for_Research_Open_Source_Software_License.pdf ******************************************************************************/ package org.opentestsystem.delivery.testreg.domain.constraintvalidators; import static org.apache.commons.lang.StringUtils.isNotEmpty; import java.lang.reflect.Field; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.opentestsystem.delivery.testreg.domain.Accommodation; import org.opentestsystem.delivery.testreg.domain.constraints.AtLeastOneAccommodation; import org.springframework.util.ReflectionUtils; public class AtLeastOneAccommodationValidator implements ConstraintValidator<AtLeastOneAccommodation, Accommodation> { private static final String ANY_OF_THE_ACCOMMODATION_RELATED_FIELD = "atleastOneAccommodationField"; String[] properties; @Override public void initialize(final AtLeastOneAccommodation constraintAnnotation) { properties = new String[] { "americanSignLanguage", "closedCaptioning", "colorContrast", "language", "masking", "nonEmbeddedAccommodations", "nonEmbeddedDesignatedSupports", "permissiveMode", "printOnDemand", "printSize", "streamlinedInterface", "textToSpeech", "translation", "other" }; } @Override public boolean isValid(final Accommodation accommodation, final ConstraintValidatorContext context) { // at least one of the accommodations within the Accommodation object must be non-null Object value = null; for (String property : properties) { try { /* * Uses Field access to avoid using getter which throws IllegalArgumentException for unknown values for * Enum lookups. */ Field field = ReflectionUtils.findField(Accommodation.class, property); if (field != null) { field.setAccessible(true); value = field.get(accommodation); } } catch (IllegalArgumentException | IllegalAccessException e) { } finally { if (value != null && isNotEmpty(value.toString().trim())) { return true; } } } /* * This validation is a cross-field( @ClassLevel) validation. We need to pass a field for the constraint * processor to lookup an invalid value. So lets add a node to the message. */ addConstraintViolation(context); return false; } private void addConstraintViolation(final ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()) .addPropertyNode(ANY_OF_THE_ACCOMMODATION_RELATED_FIELD).addConstraintViolation(); } }