com.github.panchitoboy.common.rest.EJBExceptionMapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of common-rest Show documentation
Show all versions of common-rest Show documentation
Libreria de ayuda la generacion de servicios REST
package com.github.panchitoboy.common.rest;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import javax.ejb.EJBException;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.apache.deltaspike.core.api.config.ConfigProperty;
@Provider
public class EJBExceptionMapper implements ExceptionMapper {
@Context
HttpServletRequest req;
@Inject
@ConfigProperty(name = "ejb.exception.messages.file", defaultValue = "messages")
String resourceBundleFile;
@Override
public Response toResponse(EJBException exception) {
Exception ex = exception.getCausedByException();
if (ex instanceof ConstraintViolationException) {
JsonArrayBuilder array = Json.createArrayBuilder();
ConstraintViolationException cve = (ConstraintViolationException) ex;
Set> violations = cve.getConstraintViolations();
violations.stream().forEach((violation) -> {
array.add(getMessage(violation.getMessage(), req));
});
return Response.status(Response.Status.BAD_REQUEST).entity(array.build()).type(MediaType.APPLICATION_JSON).build();
}
if (ex instanceof ValidationException) {
JsonArrayBuilder array = Json.createArrayBuilder();
ValidationException ve = (ValidationException) ex;
array.add(getMessage(ve.getMessage(), req));
return Response.status(Response.Status.BAD_REQUEST).entity(array.build()).type(MediaType.APPLICATION_JSON).build();
}
return customResponse(ex.getMessage());
}
private String getMessage(String key, HttpServletRequest req) {
Locale currentLocale = req.getLocale().stripExtensions();
try {
ResourceBundle resourceBundle = ResourceBundle.getBundle(resourceBundleFile, currentLocale);
String message = resourceBundle.getString(key);
return message;
} catch (MissingResourceException ex) {
return key;
}
}
protected Response customResponse(String message) {
JsonArrayBuilder array = Json.createArrayBuilder();
array.add(message);
return Response.status(Response.Status.BAD_REQUEST).entity(array.build()).type(MediaType.APPLICATION_JSON).build();
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy