Search in sources :

Example 16 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project resteasy by resteasy.

the class ConstraintTypeUtilImpl method getConstraintType.

@Override
public ConstraintType.Type getConstraintType(Object o) {
    if (!(o instanceof ConstraintViolation)) {
        throw new RuntimeException(Messages.MESSAGES.unknownObjectPassedAsConstraintViolation(o));
    }
    ConstraintViolation<?> v = ConstraintViolation.class.cast(o);
    Iterator<Node> nodes = v.getPropertyPath().iterator();
    Node firstNode = nodes.next();
    switch(firstNode.getKind()) {
        case BEAN:
            return ConstraintType.Type.CLASS;
        case CONSTRUCTOR:
        case METHOD:
            Node secondNode = nodes.next();
            if (secondNode.getKind() == ElementKind.PARAMETER || secondNode.getKind() == ElementKind.CROSS_PARAMETER) {
                return ConstraintType.Type.PARAMETER;
            } else if (secondNode.getKind() == ElementKind.RETURN_VALUE) {
                return ConstraintType.Type.RETURN_VALUE;
            } else {
                throw new RuntimeException(Messages.MESSAGES.unexpectedPathNodeViolation(secondNode.getKind()));
            }
        case PROPERTY:
            return ConstraintType.Type.PROPERTY;
        case CROSS_PARAMETER:
        case PARAMETER:
        case RETURN_VALUE:
        // we shouldn't encounter these element types at the root
        case CONTAINER_ELEMENT:
        default:
            throw new RuntimeException(Messages.MESSAGES.unexpectedPathNode(firstNode.getKind()));
    }
}
Also used : ConstraintViolation(jakarta.validation.ConstraintViolation) Node(jakarta.validation.Path.Node)

Example 17 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project resteasy by resteasy.

the class GeneralValidatorImpl method validate.

@Override
public void validate(HttpRequest request, Object object, Class<?>... groups) {
    Validator validator = getValidator(request);
    Set<ConstraintViolation<Object>> cvs = null;
    SimpleViolationsContainer violationsContainer = getViolationsContainer(request, object);
    if (alreadyFoundClassOrPropertyConstraint(violationsContainer)) {
        return;
    }
    try {
        cvs = validator.validate(object, groups);
    } catch (Exception e) {
        violationsContainer.setException(e);
        violationsContainer.setFieldsValidated(true);
        throw toValidationException(e, violationsContainer);
    }
    violationsContainer.addViolations(cvs);
    violationsContainer.setFieldsValidated(true);
}
Also used : ResteasyConstraintViolation(org.jboss.resteasy.api.validation.ResteasyConstraintViolation) ConstraintViolation(jakarta.validation.ConstraintViolation) Validator(jakarta.validation.Validator) ConstraintDeclarationException(jakarta.validation.ConstraintDeclarationException) ValidationException(jakarta.validation.ValidationException) PrivilegedActionException(java.security.PrivilegedActionException) ResteasyViolationException(org.jboss.resteasy.api.validation.ResteasyViolationException) ConstraintViolationException(jakarta.validation.ConstraintViolationException) ConstraintDefinitionException(jakarta.validation.ConstraintDefinitionException) GroupDefinitionException(jakarta.validation.GroupDefinitionException)

Example 18 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project resteasy by resteasy.

the class GeneralValidatorImpl method validateReturnValue.

@Override
public void validateReturnValue(HttpRequest request, Object object, Method method, Object returnValue, Class<?>... groups) {
    Validator validator = getValidator(request);
    SimpleViolationsContainer violationsContainer = getViolationsContainer(request, object);
    Set<ConstraintViolation<Object>> cvs = null;
    try {
        cvs = validator.forExecutables().validateReturnValue(object, method, returnValue, groups);
    } catch (Exception e) {
        violationsContainer.setException(e);
        throw toValidationException(e, violationsContainer);
    }
    violationsContainer.addViolations(cvs);
    if (violationsContainer.size() > 0) {
        throw new ResteasyViolationExceptionImpl(violationsContainer, request.getHttpHeaders().getAcceptableMediaTypes());
    }
}
Also used : ResteasyConstraintViolation(org.jboss.resteasy.api.validation.ResteasyConstraintViolation) ConstraintViolation(jakarta.validation.ConstraintViolation) Validator(jakarta.validation.Validator) ConstraintDeclarationException(jakarta.validation.ConstraintDeclarationException) ValidationException(jakarta.validation.ValidationException) PrivilegedActionException(java.security.PrivilegedActionException) ResteasyViolationException(org.jboss.resteasy.api.validation.ResteasyViolationException) ConstraintViolationException(jakarta.validation.ConstraintViolationException) ConstraintDefinitionException(jakarta.validation.ConstraintDefinitionException) GroupDefinitionException(jakarta.validation.GroupDefinitionException)

Example 19 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project org.openntf.xsp.jakartaee by OpenNTF.

the class GenericThrowableMapper method createResponseFromException.

protected Response createResponseFromException(final Throwable throwable, final int status, ResourceInfo resourceInfo, HttpServletRequest req) {
    MediaType type = getMediaType(resourceInfo);
    if (MediaType.TEXT_HTML_TYPE.isCompatible(type)) {
        // Handle as HTML
        return Response.status(status).type(MediaType.TEXT_HTML_TYPE).entity((StreamingOutput) out -> {
            try (PrintWriter w = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
                XSPErrorPage.handleException(w, throwable, req.getRequestURL().toString(), false);
            } catch (ServletException e) {
                throw new IOException(e);
            }
        }).build();
    } else {
        // Handle as JSON
        return Response.status(status).type(MediaType.APPLICATION_JSON_TYPE).entity((StreamingOutput) out -> {
            Objects.requireNonNull(out);
            String message = "";
            Throwable t = throwable;
            while ((message == null || message.length() == 0) && t != null) {
                if (t instanceof NotesException) {
                    message = ((NotesException) t).text;
                } else if (t instanceof ConstraintViolationException) {
                    message = t.getMessage();
                    if (message == null || message.isEmpty()) {
                        List<String> cvMsgList = new ArrayList<>();
                        for (@SuppressWarnings("rawtypes") ConstraintViolation cv : ((ConstraintViolationException) t).getConstraintViolations()) {
                            String cvMsg = cv.getPropertyPath() + ": " + cv.getMessage();
                            cvMsgList.add(cvMsg);
                        }
                        message = String.join(",", cvMsgList);
                    }
                } else {
                    message = t.getMessage();
                }
                t = t.getCause();
            }
            JsonGeneratorFactory jsonFac = Json.createGeneratorFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
            try (JsonGenerator json = jsonFac.createGenerator(out)) {
                json.writeStartObject();
                json.write("message", throwable.getClass().getName() + ": " + message);
                json.writeKey("stackTrace");
                json.writeStartArray();
                for (Throwable cause = throwable; cause != null; cause = cause.getCause()) {
                    json.writeStartArray();
                    json.write(cause.getClass().getName() + ": " + cause.getLocalizedMessage());
                    Arrays.stream(cause.getStackTrace()).map(String::valueOf).map(line -> "  at " + line).forEach(json::write);
                    json.writeEnd();
                }
                json.writeEnd();
                json.writeEnd();
            }
        }).build();
    }
}
Also used : Arrays(java.util.Arrays) XSPErrorPage(com.ibm.designer.runtime.domino.adapter.util.XSPErrorPage) Context(jakarta.ws.rs.core.Context) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) JsonGeneratorFactory(jakarta.json.stream.JsonGeneratorFactory) WebApplicationException(jakarta.ws.rs.WebApplicationException) ArrayList(java.util.ArrayList) Response(jakarta.ws.rs.core.Response) Controller(jakarta.mvc.Controller) OutputStreamWriter(java.io.OutputStreamWriter) Priority(jakarta.annotation.Priority) Produces(jakarta.ws.rs.Produces) Request(jakarta.ws.rs.core.Request) Method(java.lang.reflect.Method) StreamingOutput(jakarta.ws.rs.core.StreamingOutput) NotesException(lotus.domino.NotesException) PrintWriter(java.io.PrintWriter) ConstraintViolation(jakarta.validation.ConstraintViolation) NotFoundException(jakarta.ws.rs.NotFoundException) IOException(java.io.IOException) ConstraintViolationException(jakarta.validation.ConstraintViolationException) UriInfo(jakarta.ws.rs.core.UriInfo) JsonGenerator(jakarta.json.stream.JsonGenerator) StandardCharsets(java.nio.charset.StandardCharsets) Json(jakarta.json.Json) Priorities(jakarta.ws.rs.Priorities) Objects(java.util.Objects) List(java.util.List) MediaType(jakarta.ws.rs.core.MediaType) ExceptionMapper(jakarta.ws.rs.ext.ExceptionMapper) ResourceInfo(jakarta.ws.rs.container.ResourceInfo) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) StreamingOutput(jakarta.ws.rs.core.StreamingOutput) IOException(java.io.IOException) JsonGeneratorFactory(jakarta.json.stream.JsonGeneratorFactory) ServletException(javax.servlet.ServletException) NotesException(lotus.domino.NotesException) ConstraintViolation(jakarta.validation.ConstraintViolation) MediaType(jakarta.ws.rs.core.MediaType) ConstraintViolationException(jakarta.validation.ConstraintViolationException) JsonGenerator(jakarta.json.stream.JsonGenerator) OutputStreamWriter(java.io.OutputStreamWriter) ArrayList(java.util.ArrayList) List(java.util.List) PrintWriter(java.io.PrintWriter)

Example 20 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project myfaces by apache.

the class BeanValidator method validate.

/**
 * {@inheritDoc}
 */
@Override
public void validate(final FacesContext context, final UIComponent component, final Object value) {
    Assert.notNull(context, "context");
    Assert.notNull(component, "component");
    ValueExpression valueExpression = component.getValueExpression("value");
    if (valueExpression == null) {
        log.warning("cannot validate component with empty value: " + component.getClientId(context));
        return;
    }
    // Obtain a reference to the to-be-validated object and the property name.
    ValueReference reference = ValueReferenceResolver.resolve(valueExpression, context);
    if (reference == null) {
        return;
    }
    Object base = reference.getBase();
    if (base == null) {
        return;
    }
    Class<?> valueBaseClass = base.getClass();
    if (valueBaseClass == null) {
        return;
    }
    Object referenceProperty = reference.getProperty();
    if (!(referenceProperty instanceof String)) {
        // can exit bean validation here
        return;
    }
    String valueProperty = (String) referenceProperty;
    // Initialize Bean Validation.
    ValidatorFactory validatorFactory = createValidatorFactory(context);
    jakarta.validation.Validator validator = createValidator(validatorFactory, context);
    BeanDescriptor beanDescriptor = validator.getConstraintsForClass(valueBaseClass);
    if (!beanDescriptor.isBeanConstrained()) {
        return;
    }
    // Note that validationGroupsArray was initialized when createValidator was called
    Class[] validationGroupsArray = this.validationGroupsArray;
    // JSF 2.3: If the ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME application parameter is enabled and this Validator
    // instance has validation groups other than or in addition to the Default group
    boolean containsOtherValidationGroup = false;
    if (validationGroupsArray != null && validationGroupsArray.length > 0) {
        for (Class<?> clazz : validationGroupsArray) {
            if (!Default.class.equals(clazz)) {
                containsOtherValidationGroup = true;
                break;
            }
        }
    }
    // Delegate to Bean Validation.
    Set<?> constraintViolations = validator.validateValue(valueBaseClass, valueProperty, value, validationGroupsArray);
    if (!constraintViolations.isEmpty()) {
        Set<FacesMessage> messages = new LinkedHashSet<>(constraintViolations.size());
        for (Object violation : constraintViolations) {
            ConstraintViolation constraintViolation = (ConstraintViolation) violation;
            String message = constraintViolation.getMessage();
            Object[] args = new Object[] { message, MessageUtils.getLabel(context, component) };
            FacesMessage msg = MessageUtils.getErrorMessage(context, MESSAGE_ID, args);
            messages.add(msg);
        }
        if (isValidateWholeBeanEnabled(context) && containsOtherValidationGroup) {
            // JSF 2.3: record the fact that this field failed validation so that any <f:validateWholeBean />
            // 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
            // ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME is set, throw the new exception.
            context.getViewRoot().getTransientStateHelper().putTransient(BEAN_VALIDATION_FAILED, Boolean.TRUE);
        }
        throw new ValidatorException(messages);
    } else {
        // Default group
        if (isValidateWholeBeanEnabled(context) && containsOtherValidationGroup) {
            // record the fact that this field passed validation so that any <f:validateWholeBean /> component
            // later in the tree is able to allow class-level validation for the bean for which this particular
            // field is a property.
            Map<String, Object> candidatesMap = (Map<String, Object>) context.getViewRoot().getTransientStateHelper().getTransient(CANDIDATE_COMPONENT_VALUES_MAP);
            if (candidatesMap == null) {
                candidatesMap = new LinkedHashMap<>();
                context.getViewRoot().getTransientStateHelper().putTransient(CANDIDATE_COMPONENT_VALUES_MAP, candidatesMap);
            }
            candidatesMap.put(component.getClientId(context), value);
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ValidatorFactory(jakarta.validation.ValidatorFactory) Default(jakarta.validation.groups.Default) BeanDescriptor(jakarta.validation.metadata.BeanDescriptor) ValueExpression(jakarta.el.ValueExpression) ConstraintViolation(jakarta.validation.ConstraintViolation) FacesMessage(jakarta.faces.application.FacesMessage) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ValueReference(jakarta.el.ValueReference)

Aggregations

ConstraintViolation (jakarta.validation.ConstraintViolation)397 Test (org.testng.annotations.Test)309 Validator (jakarta.validation.Validator)258 TestForIssue (org.hibernate.validator.testutil.TestForIssue)134 HibernateValidator (org.hibernate.validator.HibernateValidator)123 ValidatorUtil.getValidator (org.hibernate.validator.testutils.ValidatorUtil.getValidator)70 ExecutableValidator (jakarta.validation.executable.ExecutableValidator)60 ConstraintValidator (jakarta.validation.ConstraintValidator)57 ConstraintMapping (org.hibernate.validator.cfg.ConstraintMapping)54 Method (java.lang.reflect.Method)46 ValidatorFactory (jakarta.validation.ValidatorFactory)41 Test (org.junit.Test)39 ConstraintViolationException (jakarta.validation.ConstraintViolationException)35 Path (jakarta.validation.Path)35 NotNull (jakarta.validation.constraints.NotNull)32 HibernateValidatorConfiguration (org.hibernate.validator.HibernateValidatorConfiguration)27 NotNullDef (org.hibernate.validator.cfg.defs.NotNullDef)19 SizeDef (org.hibernate.validator.cfg.defs.SizeDef)18 Size (jakarta.validation.constraints.Size)17 PropertyNode (org.hibernate.validator.path.PropertyNode)14