@Test @SpecAssertion(section = "6.11", id = "e") public void testGetMessageTemplate() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "middleName"); String messageTemplate = descriptor.getMessageTemplate(); assertEquals(messageTemplate, "must at least be {min} characters long"); }
@Test @SpecAssertion(section = "6.11", id = "l") public void testGetValidationAppliesToReturnsNull() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "firstName"); ConstraintTarget constraintTarget = descriptor.getValidationAppliesTo(); assertNull(constraintTarget); }
@Test @SpecAssertion(section = "6.11", id = "l") public void testGetValidationAppliesTo() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "age"); ConstraintTarget constraintTarget = descriptor.getValidationAppliesTo(); assertNotNull(constraintTarget); assertEquals(constraintTarget, ConstraintTarget.RETURN_VALUE); }
@Test @SpecAssertion(section = "6.11", id = "g") public void testDefaultGroupIsReturnedIfNoGroupSpecifiedInDeclaration() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Order.class, "orderNumber"); Set<Class<?>> groups = descriptor.getGroups(); assertTrue(groups.size() == 1); assertEquals(groups.iterator().next(), Default.class, "Wrong group"); }
@Test @SpecAssertion(section = "6.11", id = "f") public void testGetGroupsOnInterface() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "lastName"); Set<Class<?>> groups = descriptor.getGroups(); assertTrue(groups.size() == 1); assertEquals(groups.iterator().next(), Default.class, "Wrong group"); }
@Test @SpecAssertion(section = "6.11", id = "c") public void testGetAttributesFromConstraintDescriptor() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Order.class, "orderNumber"); Map<String, Object> attributes = descriptor.getAttributes(); assertTrue(attributes.containsKey("message")); assertTrue(attributes.containsKey("groups")); }
@Test @SpecAssertion(section = "6.11", id = "m") public void testReportAsSingleViolation() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Order.class, "orderNumber"); assertFalse(descriptor.isReportAsSingleViolation()); descriptor = getConstraintDescriptor(Person.class, "firstName"); assertTrue(descriptor.isReportAsSingleViolation()); }
/** * Process the given JSR-303 ConstraintViolations, adding corresponding errors to the provided * Spring {@link Errors} object. * * @param violations the JSR-303 ConstraintViolation results * @param errors the Spring errors object to register to */ protected void processConstraintViolations( Set<ConstraintViolation<Object>> violations, Errors errors) { for (ConstraintViolation<Object> violation : violations) { String field = violation.getPropertyPath().toString(); FieldError fieldError = errors.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { ConstraintDescriptor<?> cd = violation.getConstraintDescriptor(); String errorCode = cd.getAnnotation().annotationType().getSimpleName(); Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd); if (errors instanceof BindingResult) { // Can do custom FieldError registration with invalid value from ConstraintViolation, // as necessary for Hibernate Validator compatibility (non-indexed set path in field) BindingResult bindingResult = (BindingResult) errors; String nestedField = bindingResult.getNestedPath() + field; if ("".equals(nestedField)) { String[] errorCodes = bindingResult.resolveMessageCodes(errorCode); bindingResult.addError( new ObjectError( errors.getObjectName(), errorCodes, errorArgs, violation.getMessage())); } else { Object invalidValue = violation.getInvalidValue(); if (!"".equals(field) && (invalidValue == violation.getLeafBean() || (field.contains(".") && !field.contains("[]")))) { // Possibly a bean constraint with property path: retrieve the actual property // value. // However, explicitly avoid this for "address[]" style paths that we can't handle. invalidValue = bindingResult.getRawFieldValue(field); } String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field); bindingResult.addError( new FieldError( errors.getObjectName(), nestedField, invalidValue, false, errorCodes, errorArgs, violation.getMessage())); } } else { // got no BindingResult - can only do standard rejectValue call // with automatic extraction of the current field value errors.rejectValue(field, errorCode, errorArgs, violation.getMessage()); } } catch (NotReadablePropertyException ex) { throw new IllegalStateException( "JSR-303 validated property '" + field + "' does not have a corresponding accessor for Spring data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex); } } } }
@Test @SpecAssertion(section = "6.11", id = "f") public void testGetGroupsWithImplicitGroup() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Man.class, "lastName"); Set<Class<?>> groups = descriptor.getGroups(); assertTrue(groups.size() == 2); for (Class<?> group : groups) { if (!(group.equals(Default.class) || group.equals(Person.class))) { fail("Invalid group."); } } }
@Test @SpecAssertion(section = "6.11", id = "l") public void testGetValidationAppliesToFromComposingConstraint() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "age"); Set<ConstraintDescriptor<?>> composingDescriptors = descriptor.getComposingConstraints(); assertEquals(composingDescriptors.size(), 1, "Wrong number of composing constraints"); ConstraintTarget constraintTarget = composingDescriptors.iterator().next().getValidationAppliesTo(); assertNotNull(constraintTarget); assertEquals(constraintTarget, ConstraintTarget.RETURN_VALUE); }
@Test @SpecAssertion(section = "6.11", id = "i") public void testPayload() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "firstName"); Set<Class<? extends Payload>> payload = descriptor.getPayload(); assertTrue(payload.size() == 1); assertEquals(payload.iterator().next(), Severity.Info.class, "Wrong payload"); descriptor = getConstraintDescriptor(Order.class, "orderNumber"); payload = descriptor.getPayload(); assertTrue(payload != null); assertTrue(payload.size() == 0); }
@Test @SpecAssertions({ @SpecAssertion(section = "6.11", id = "j"), @SpecAssertion(section = "6.11", id = "k") }) public void testComposingConstraintsPayload() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "firstName"); Set<ConstraintDescriptor<?>> composingDescriptors = descriptor.getComposingConstraints(); assertEquals(composingDescriptors.size(), 2, "Wrong number of composing constraints"); for (ConstraintDescriptor<?> desc : composingDescriptors) { assertTrue(desc.getGroups().size() == 1); assertEquals(desc.getPayload().iterator().next(), Severity.Info.class, "Wrong payload"); } }
@Test @SpecAssertions({ @SpecAssertion(section = "6.11", id = "a"), @SpecAssertion(section = "6.11", id = "b"), @SpecAssertion(section = "6.11", id = "d") }) public void testAnnotationAndMapParametersReflectParameterOverriding() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "firstName"); Set<ConstraintDescriptor<?>> composingDescriptors = descriptor.getComposingConstraints(); assertEquals(composingDescriptors.size(), 2, "Wrong number of composing constraints"); boolean hasSize = false; for (ConstraintDescriptor<?> desc : composingDescriptors) { if (desc.getAnnotation().annotationType().equals(Size.class)) { hasSize = true; Size sizeAnn = (Size) desc.getAnnotation(); assertEquals(sizeAnn.min(), 5, "The min parameter should reflect the overridden parameter"); assertEquals( desc.getAttributes().get("min"), 5, "The min parameter should reflect the overridden parameter"); } else if (desc.getAnnotation().annotationType().equals(NotNull.class)) { } else { fail("Unexpected annotation."); } } assertTrue(hasSize, "Size composed annotation not found"); }
/* * Helper method that checks for unitActive's annotation. */ private boolean checkForB2BUnitActiveAnnotation( final Set<HybrisConstraintViolation> constraintViolations) { for (final Iterator constraintIterator = constraintViolations.iterator(); constraintIterator.hasNext(); ) { final HybrisConstraintViolation hybrisConstraintViolation = (HybrisConstraintViolation) constraintIterator.next(); final ConstraintViolation constraintViolation = hybrisConstraintViolation.getConstraintViolation(); final ConstraintDescriptor descriptor = constraintViolation.getConstraintDescriptor(); final Annotation annotation = descriptor.getAnnotation(); if (annotation.getClass().getName().equals("B2BUnitActive")) { constraintViolations.remove(hybrisConstraintViolation); return true; } } return false; }
public Map<String, Object> getMetadata(ConstraintDescriptor constraintDescriptor) { Map<String, Object> metadata = new HashMap<String, Object>(); Map attrs = constraintDescriptor.getAttributes(); Object message = attrs.get("message"); metadata.put(HTML.VALIDATION_METADATA.MAX_VALUE, attrs.get("value")); if (!message.equals(MESSAGE_ID)) { metadata.put(MESSAGE_METADATA, message); } return metadata; }
protected Object[] getArgumentsForConstraint( String objectName, String field, ConstraintDescriptor<?> descriptor) { List<Object> arguments = new LinkedList<>(); String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field}; arguments.add(new DefaultMessageSourceResolvable(codes, field)); // Using a TreeMap for alphabetical ordering of attribute names Map<String, Object> attributesToExpose = new TreeMap<>(); for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) { String attributeName = entry.getKey(); Object attributeValue = entry.getValue(); if (!internalAnnotationAttributes.contains(attributeName)) { attributesToExpose.put(attributeName, attributeValue); } } arguments.addAll(attributesToExpose.values()); return arguments.toArray(new Object[arguments.size()]); }
@Test @SpecAssertion(section = "6.11", id = "n") public void testEmptyComposingConstraints() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Order.class, "orderNumber"); assertTrue(descriptor.getComposingConstraints().isEmpty()); }