/** * Validate a bean of given declared class. * * @param bean * the bean to validate. * @param parameter * the runtime annotations of this parameter. * @param validationErrors * the errors list to fill. */ private void validate(final Object bean, final Method method, final Parameter parameter, final int index, final Set<ConstraintViolation<?>> validationErrors) { if (bean == null) { // Parameter is null, is it manually checked of managed by CXF for // multipart? // All non-body parameters are required by default final PathImpl propertyPath = PathImpl.createPathFromString(method.getName()); propertyPath.addParameterNode(parameter.getName(), index); validationErrors.add(ConstraintViolationImpl.forParameterValidation(NotNull.class.getName(), null, null, "interpolated", null, null, null, null, propertyPath, NOT_NULL_DESCRIPTOR, null, null, null)); return; } final Class<?> clazz = bean.getClass(); if (Collection.class.isAssignableFrom(clazz)) { validate((Collection<?>) bean, validationErrors); } else if (clazz.isArray()) { validate((Object[]) bean, validationErrors); } else { validateSimpleBean(bean, validationErrors); } }
@Test public void testConstraintViolationExceptionParameter() { final Wine bean = new Wine(); final Set<ConstraintViolation<?>> violations = new LinkedHashSet<>(); final ConstraintHelper helper = new ConstraintHelper(); final ConstraintDescriptor<NotEmpty> notEmptyNameDescriptor = new ConstraintDescriptorImpl<>(helper, (Member) null, getAnnotation("name", NotEmpty.class), ElementType.FIELD); PathImpl path = PathImpl.createPathFromString("name"); violations.add(ConstraintViolationImpl.<Wine> forParameterValidation("name-Empty", null, null, "interpolated", Wine.class, bean, new Object(), "value", path, notEmptyNameDescriptor, ElementType.PARAMETER, null, null)); path.addParameterNode("parameter1", 0); final ConstraintViolationException violationException = Mockito.mock(ConstraintViolationException.class); Mockito.when(violationException.getConstraintViolations()).thenReturn(violations); final ValidationJsonException validationJsonException = new ValidationJsonException(violationException); Assert.assertFalse(validationJsonException.getErrors().isEmpty()); Assert.assertEquals("{parameter1=[{rule=name-Empty}]}", validationJsonException.getErrors().toString()); }
/** * get validation error set. * * @return the validationErrorSet */ @SuppressWarnings({"unchecked"}) public final ArrayList<ConstraintViolation<?>> getValidationErrorSet(final Object pclass) { final ArrayList<ConstraintViolation<?>> violations = new ArrayList<>(this.validationErrorSet.size()); for (final SerializeableConstraintValidationImpl<?> violation : this.validationErrorSet) { final Map<String, Object> messageParameters = new HashMap<>(); final Map<String, Object> expressionVariables = new HashMap<>(); violations.add(ConstraintViolationImpl.forBeanValidation( // violation.getMessageTemplate(), // messageParameters, // expressionVariables, // violation.getMessage(), // ((SerializeableConstraintValidationImpl<Object>) violation).getRootBeanClass(), // pclass, // violation.getLeafBean(), // null, // violation.getPropertyPath(), // violation.getConstraintDescriptor(), // null, // null)); } return violations; }
/** * instantiate a ConstraintViolationImpl. * * @param streamReader serialized stream reader to take data from * @return ConstraintViolationImpl * @throws SerializationException if deserialization fails */ public static ConstraintViolationImpl<Object> instantiate( final SerializationStreamReader streamReader) throws SerializationException { final String messageTemplate = null; final String interpolatedMessage = streamReader.readString(); final Class<Object> rootBeanClass = null; final Object rootBean = null; final Object leafBeanInstance = null; final Object value = null; final Path propertyPath = (Path) streamReader.readObject(); final ConstraintDescriptor<?> constraintDescriptor = null; final ElementType elementType = null; final Map<String, Object> messageParameters = new HashMap<>(); final Map<String, Object> expressionVariables = new HashMap<>(); return (ConstraintViolationImpl<Object>) ConstraintViolationImpl.forBeanValidation( messageTemplate, messageParameters, expressionVariables, interpolatedMessage, rootBeanClass, rootBean, leafBeanInstance, value, propertyPath, constraintDescriptor, elementType, null); }
@Test public void testConstraintViolationException() { final Wine bean = new Wine(); final Set<ConstraintViolation<?>> violations = new LinkedHashSet<>(); final ConstraintHelper helper = new ConstraintHelper(); final ConstraintDescriptor<NotEmpty> notEmptyNameDescriptor = new ConstraintDescriptorImpl<>(helper, (Member) null, getAnnotation("name", NotEmpty.class), ElementType.FIELD); final ConstraintDescriptor<NotEmpty> notEmptyGrapesDescriptor = new ConstraintDescriptorImpl<>(helper, (Member) null, getAnnotation("grapes", NotEmpty.class), ElementType.FIELD); final ConstraintDescriptor<Length> lengthNameDescriptor = new ConstraintDescriptorImpl<>(helper, (Member) null, getAnnotation("name", Length.class), ElementType.FIELD); violations.add(ConstraintViolationImpl.<Wine> forBeanValidation("name-Empty", null, null, "interpolated", Wine.class, bean, new Object(), "value", PathImpl.createPathFromString("name"), notEmptyNameDescriptor, ElementType.FIELD, null)); violations.add(ConstraintViolationImpl.<Wine> forBeanValidation("name-length", null, null, "interpolated", Wine.class, bean, new Object(), "value", PathImpl.createPathFromString("name"), lengthNameDescriptor, ElementType.FIELD, null)); violations.add(ConstraintViolationImpl.<Wine> forBeanValidation("grapes-Empty", null, null, "interpolated", Wine.class, bean, new Object(), "value", PathImpl.createPathFromString("grapes"), notEmptyGrapesDescriptor, ElementType.FIELD, null)); final ConstraintViolationException violationException = Mockito.mock(ConstraintViolationException.class); Mockito.when(violationException.getConstraintViolations()).thenReturn(violations); final ValidationJsonException validationJsonException = new ValidationJsonException(violationException); Assert.assertFalse(validationJsonException.getErrors().isEmpty()); Assert.assertEquals("{name=[{rule=name-Empty}, {rule=name-length, parameters={min=0, max=50}}], grapes=[{rule=grapes-Empty}]}", validationJsonException.getErrors().toString()); }
/** * Only a subset of fields are actually serialized. * <p/> * There is no guarantee that the root bean is GWT-serializable or that it's appropriate for it to * be exposed on the client. Even if the root bean could be sent back, the lack of reflection on * the client makes it troublesome to interpret the path as a sequence of property accesses. * <p/> * The current implementation is the simplest-to-implement properties. * <ol> * <li>Message</li> * <li>Property Path</li> * </ol> */ public static void serialize(final SerializationStreamWriter streamWriter, final ConstraintViolationImpl instance) throws SerializationException { // streamWriter.writeString(instance.getMessageTemplate()); streamWriter.writeString(instance.getMessage()); // streamWriter.writeObject(instance.getRootBeanClass()); // streamWriter.writeObject(instance.getRootBean()); // streamWriter.writeObject(instance.getLeafBean()); // streamWriter.writeObject(instance.getInvalidValue()); streamWriter.writeObject(instance.getPropertyPath()); // streamWriter.writeObject(instance.getConstraintDescriptor()); // ElementType }
@Test public void testGetJsonString() throws Exception { Object bean = new Object(); Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>(); violations.add(new ConstraintViolationImpl("tmpl", "oopsie msg", Object.class, bean, bean, bean, PathImpl.createPathFromString("var1"), null, null)); violations.add(new ConstraintViolationImpl("Grote boodschap", "failure", Object.class, bean, bean, bean, PathImpl.createPathFromString("var2"), null, null)); violations.add(new ConstraintViolationImpl("Grote boodschap", "imsg", Object.class, bean, bean, bean, PathImpl.createPathFromString("var2"), null, null)); ConstraintViolationException cve = new ConstraintViolationException("problems", violations); Response res = mapper.toResponse(cve); assertThat(res.getStatus()).isEqualTo(Response.Status.PRECONDITION_FAILED.getStatusCode()); assertThat( // grr, order of elements can change res.getEntity().equals("{ \"error\" : {\"var1\":[\"oopsie msg\"],\"var2\":[\"failure\",\"imsg\"]}}") || res.getEntity().equals("{ \"error\" : {\"var1\":[\"oopsie msg\"],\"var2\":[\"imsg\",\"failure\"]}}") || res.getEntity().equals("{ \"error\" : {\"var2\":[\"failure\",\"imsg\"],\"var1\":[\"oopsie msg\"]}}") || res.getEntity().equals("{ \"error\" : {\"var2\":[\"imsg\",\"failure\"],\"var1\":[\"oopsie msg\"]}}") ).isTrue(); verify(preProcessLoggingInterceptor).postProcessError(cve, "Applicatie keerde terug met een (verwachtte) ConstraintViolation:"); }
/** * Writes the JSON form of the Constraint Violation. * * @param constraintViolation the violation * @param jsonGenerator the generator * @param serializerProvider the provider * @throws IOException if it cannot be serialized */ @Override public void serialize(ConstraintViolationImpl constraintViolation, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("message", constraintViolation.getMessage()); Object invalidValue = constraintViolation.getInvalidValue(); if (invalidValue != null) { jsonGenerator.writeStringField("invalid", invalidValue.toString()); } if (constraintViolation.getPropertyPath() != null) { jsonGenerator.writeStringField("path", constraintViolation.getPropertyPath().toString()); } jsonGenerator.writeEndObject(); }
public static void deserialize(final SerializationStreamReader streamReader, final ConstraintViolationImpl instance) throws SerializationException { // no fields }
@Override public void deserializeInstance(final SerializationStreamReader streamReader, final ConstraintViolationImpl instance) throws SerializationException { deserialize(streamReader, instance); }
@Override public ConstraintViolationImpl instantiateInstance(final SerializationStreamReader streamReader) throws SerializationException { return instantiate(streamReader); }
@Override public void serializeInstance(final SerializationStreamWriter streamWriter, final ConstraintViolationImpl instance) throws SerializationException { serialize(streamWriter, instance); }
/** * @return the serialized class. */ @Override public Class<ConstraintViolationImpl> handledType() { return ConstraintViolationImpl.class; }