/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.megatim.fdxcommons.tools.exceptions; import java.util.HashMap; import java.util.Map; import javax.validation.ConstraintViolationException; import javax.ejb.Singleton; import javax.validation.ConstraintViolation; import javax.validation.Path; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * * @author Leonel FOFOU */ @Provider @Singleton public class CommonValidationExceptionMapperCustom extends WebApplicationException implements ExceptionMapper { private String key; private String message; @Override public Response toResponse(ConstraintViolationException exception) { return Response.status(422) .entity(prepareMessage(exception)) .type(MediaType.APPLICATION_JSON) .build(); } @Override public Response getResponse() { Map error = new HashMap() ; error.put(this.key, this.message); return Response.status(422).entity(error).type(MediaType.APPLICATION_JSON).build(); } public CommonValidationExceptionMapperCustom() { super(); } public CommonValidationExceptionMapperCustom(String key, String messsage) { super(); this.key = key ; this.message = messsage; } private Map prepareMessage(ConstraintViolationException exception) { Map errors = new HashMap<>(); for (ConstraintViolation cv : exception.getConstraintViolations()) { String fieldName = null; for(Path.Node node : cv.getPropertyPath()) { fieldName = node.getName(); } errors.put(fieldName, cv.getMessage()); //message.append(cv.getPropertyPath() + " " + cv.getMessage() + "\n"); } return errors; } private Map prepareSpecificMassage(String key, String value) { Map errors = new HashMap<>(); errors.put(key, value); return errors; } }