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()));
}
}
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);
}
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());
}
}
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();
}
}
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);
}
}
}
Aggregations