use of jakarta.validation.ConstraintViolation in project mojarra by eclipse-ee4j.
the class WholeBeanValidator method validate.
public void validate(FacesContext context, UIValidateWholeBean component, Object value) throws ValidatorException {
// Get parent and check if the parent of this f:validateWholeBean is a form
UIForm form = getParentForm(component);
ValueExpression wholeBeanVE = getValueExpressionNullSafe(component, "value");
// The "whole" bean that we're going to validate at the class level
Object wholeBean = wholeBeanVE.getValue(context.getELContext());
// A shortened or fully qualified class name, or EL expression pointing
// to a type that copies the target bean for validation
String copierType = (String) component.getAttributes().get("copierType");
// Inspect the status of field level validation
if (hasAnyBeanPropertyFailedValidation(context, wholeBean)) {
return;
}
AddRemainingCandidateFieldsCallback addRemainingCandidateFieldsCallback = new AddRemainingCandidateFieldsCallback(context, wholeBean);
form.visitTree(createVisitContext(context), addRemainingCandidateFieldsCallback);
Map<String, Map<String, Object>> validationCandidate = addRemainingCandidateFieldsCallback.getCandidate();
if (validationCandidate.isEmpty()) {
return;
}
// Perform the actual bean validation on a copy of the whole bean
Set<ConstraintViolation<?>> violations = doBeanValidation(getBeanValidator(context), copyBeanAndPopulateWithCandidateValues(context, wholeBeanVE, wholeBean, copierType, validationCandidate), component.getValidationGroupsArray(), wholeBeanVE);
// If there are any violations, transform them into a Faces validator exception
if (violations != null && !violations.isEmpty()) {
ValidatorException toThrow;
if (violations.size() == 1) {
ConstraintViolation<?> violation = violations.iterator().next();
toThrow = new ValidatorException(getMessage(context, MESSAGE_ID, violation.getMessage(), getLabel(context, component)));
} else {
Set<FacesMessage> messages = new LinkedHashSet<>(violations.size());
for (ConstraintViolation<?> violation : violations) {
messages.add(getMessage(context, MESSAGE_ID, violation.getMessage(), getLabel(context, component)));
}
toThrow = new ValidatorException(messages);
}
// values during updateModelValues
for (Entry<String, Map<String, Object>> validationCandidateEntry : validationCandidate.entrySet()) {
invalidateComponent(validationCandidateEntry);
}
throw toThrow;
}
}
use of jakarta.validation.ConstraintViolation in project mojarra by eclipse-ee4j.
the class BeanValidator method validate.
/**
* <p class="changed_added_2_0">
* <span class="changed_modified_2_3">Verify</span> that the value is valid according to the Bean Validation
* constraints.
* </p>
*
* <div class="changed_added_2_0">
*
* <p>
* Obtain a {@link ValidatorFactory} instance by calling
* {@link jakarta.validation.Validation#buildDefaultValidatorFactory}.
* </p>
*
* <p>
* Let <em>validationGroupsArray</em> be a <code>Class []</code> representing validator groups set on the component by
* the tag handler for this validator. The first search component terminates the search for the validation groups value.
* If no such value is found use the class name of {@link jakarta.validation.groups.Default} as the value of the
* validation groups.
* </p>
*
* <p>
* Let <em>valueExpression</em> be the return from calling {@link UIComponent#getValueExpression} on the argument
* <em>component</em>, passing the literal string “value” (without the quotes) as an argument. If this
* application is running in an environment with Jakarta Expression Language, obtain the
* <code>ValueReference</code> from <em>valueExpression</em> and let <em>valueBaseClase</em> be the return from calling
* <code>ValueReference.getBase()</code> and <em>valueProperty</em> be the return from calling
* <code>ValueReference.getProperty()</code>. If an earlier version of Jakarta Expression Language is present, use the
* appropriate methods to inspect <em>valueExpression</em> and derive values for <em>valueBaseClass</em> and
* <em>valueProperty</em>.
* </p>
*
* <p>
* If no <code>ValueReference</code> can be obtained, take no action and return.
* </p>
*
* <p>
* If <code>ValueReference.getBase()</code> return <code>null</code>, take no action and return.
* </p>
*
* <p>
* Obtain the {@link ValidatorContext} from the {@link ValidatorFactory}.
* </p>
*
* <p>
* Decorate the {@link MessageInterpolator} returned from {@link ValidatorFactory#getMessageInterpolator} with one that
* leverages the <code>Locale</code> returned from {@link jakarta.faces.component.UIViewRoot#getLocale}, and store it in
* the <code>ValidatorContext</code> using {@link ValidatorContext#messageInterpolator}.
* </p>
*
* <p>
* Obtain the {@link jakarta.validation.Validator} instance from the <code>validatorContext</code>.
* </p>
*
* <p>
* Obtain a <code>jakarta.validation.BeanDescriptor</code> from the <code>jakarta.validation.Validator</code>. If
* <code>hasConstraints()</code> on the <code>BeanDescriptor</code> returns false, take no action and return. Otherwise
* proceed.
* </p>
*
* <p>
* Call {@link jakarta.validation.Validator#validateValue}, passing <em>valueBaseClass</em>, <em>valueProperty</em>, the
* <em>value</em> argument, and <em>validatorGroupsArray</em> as arguments.
* </p>
*
* <p>
* If the returned <code>Set<{@link
* ConstraintViolation}></code> is non-empty, for each element in the <code>Set</code>, create a {@link FacesMessage}
* where the summary and detail are the return from calling {@link ConstraintViolation#getMessage}. Capture all such
* <code>FacesMessage</code> instances into a <code>Collection</code> and pass them to
* {@link ValidatorException#ValidatorException(java.util.Collection)}. <span class="changed_added_2_3">If the
* {@link #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} application parameter is enabled and this {@code Validator} instance
* has validation groups other than or in addition to the {@code Default} group, record the fact that this field failed
* validation so that any <code><f:validateWholeBean /></code> component later in the tree is able to skip
* class-level validation for the bean for which this particular field is a property. Regardless of whether or not
* {@link #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} is set, throw the new exception.</span>
* </p>
*
* <p class="changed_added_2_3">
* If the returned {@code Set} is empty, the {@link #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} application parameter is
* enabled and this {@code Validator} instance has validation groups other than or in addition to the {@code Default}
* group, record the fact that this field passed validation so that any <code><f:validateWholeBean /></code>
* component later in the tree is able to allow class-level validation for the bean for which this particular field is a
* property.
* </p>
*
* </div>
*
* @param context {@inheritDoc}
* @param component {@inheritDoc}
* @param value {@inheritDoc}
*
* @throws ValidatorException {@inheritDoc}
*/
@Override
public void validate(FacesContext context, UIComponent component, Object value) {
if (context == null) {
throw new NullPointerException();
}
if (component == null) {
throw new NullPointerException();
}
ValueExpression valueExpression = component.getValueExpression("value");
if (valueExpression == null) {
return;
}
ValueReference valueReference = getValueReference(context, component, valueExpression);
if (valueReference == null) {
return;
}
Class<?>[] validationGroupsArray = parseValidationGroups(getValidationGroups());
if (isResolvable(valueReference, valueExpression)) {
jakarta.validation.Validator beanValidator = getBeanValidator(context);
@SuppressWarnings("rawtypes") Set violationsRaw = null;
try {
violationsRaw = beanValidator.validateValue(valueReference.getBase().getClass(), valueReference.getProperty().toString(), value, validationGroupsArray);
} catch (IllegalArgumentException iae) {
LOGGER.fine("Unable to validate expression " + valueExpression.getExpressionString() + " using Bean Validation. Unable to get value of expression. " + " Message from Bean Validation: " + iae.getMessage());
}
@SuppressWarnings("unchecked") Set<ConstraintViolation<?>> violations = violationsRaw;
if (violations != null && !violations.isEmpty()) {
ValidatorException toThrow;
if (violations.size() == 1) {
ConstraintViolation<?> violation = violations.iterator().next();
toThrow = new ValidatorException(getMessage(context, MESSAGE_ID, violation.getMessage(), getLabel(context, component)));
} else {
Set<FacesMessage> messages = new LinkedHashSet<>(violations.size());
for (ConstraintViolation<?> violation : violations) {
messages.add(getMessage(context, MESSAGE_ID, violation.getMessage(), getLabel(context, component)));
}
toThrow = new ValidatorException(messages);
}
// validation is not attempted.
if (wholeBeanValidationEnabled(context, validationGroupsArray)) {
recordValidationResult(context, component, valueReference.getBase(), valueReference.getProperty().toString(), FAILED_FIELD_LEVEL_VALIDATION);
}
throw toThrow;
}
}
// validation can be performed if desired
if (wholeBeanValidationEnabled(context, validationGroupsArray)) {
recordValidationResult(context, component, valueReference.getBase(), valueReference.getProperty().toString(), value);
}
}
use of jakarta.validation.ConstraintViolation in project hibernate-validator by hibernate.
the class ProgrammaticContainerElementConstraintsForFieldTest method canDeclareDeeplyNestedContainerElementConstraintsOnMultipleDifferentTypeArgumentsForFieldProgrammatically.
@Test
@TestForIssue(jiraKey = "HV-1614")
public void canDeclareDeeplyNestedContainerElementConstraintsOnMultipleDifferentTypeArgumentsForFieldProgrammatically() {
ConstraintMapping newMapping = config.createConstraintMapping();
newMapping.type(FishTank.class).field("tagsOfFishOfTheMonth").containerElementType(0, 0).constraint(new LengthDef().min(10).max(20)).containerElementType(0, 1, 0).constraint(new NotNullDef());
config.addMapping(newMapping);
Validator validator = config.buildValidatorFactory().getValidator();
Set<ConstraintViolation<FishTank>> violations = validator.validate(new FishTank());
assertThat(violations).containsOnlyViolations(violationOf(NotNull.class).withMessage("must not be null"), violationOf(Length.class).withMessage("length must be between 10 and 20"));
}
use of jakarta.validation.ConstraintViolation in project hibernate-validator by hibernate.
the class ProgrammaticContainerElementConstraintsForFieldTest method canDeclareContainerElementConstraintsForMultiDimensionalArrayTypeFieldProgrammatically.
// HV-1428 Container element support is disabled for arrays
@Test(expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "HV000226:.*")
@TestForIssue(jiraKey = "HV-1239")
public void canDeclareContainerElementConstraintsForMultiDimensionalArrayTypeFieldProgrammatically() {
ConstraintMapping newMapping = config.createConstraintMapping();
newMapping.type(FishTank.class).field("fishNamesByMonthAsArray").containerElementType(0, 0).constraint(new SizeDef().max(5));
config.addMapping(newMapping);
Validator validator = config.buildValidatorFactory().getValidator();
Set<ConstraintViolation<FishTank>> violations = validator.validate(new FishTank());
assertThat(violations).containsOnlyViolations(violationOf(Size.class).withMessage("size must be between 0 and 5"));
}
use of jakarta.validation.ConstraintViolation in project hibernate-validator by hibernate.
the class ProgrammaticContainerElementConstraintsForFieldTest method canDeclareNestedContainerElementConstraintsForFieldProgrammatically.
@Test
@TestForIssue(jiraKey = "HV-1239")
public void canDeclareNestedContainerElementConstraintsForFieldProgrammatically() {
ConstraintMapping newMapping = config.createConstraintMapping();
newMapping.type(FishTank.class).field("fishOfTheMonth").containerElementType(1, 0).constraint(new NotNullDef());
config.addMapping(newMapping);
Validator validator = config.buildValidatorFactory().getValidator();
Set<ConstraintViolation<FishTank>> violations = validator.validate(new FishTank());
assertThat(violations).containsOnlyViolations(violationOf(NotNull.class).withMessage("must not be null"));
}
Aggregations