/*
|
* 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<ConstraintViolationException> {
|
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<String ,String> error = new HashMap<String, String>() ;
|
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<String, String> 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<String, String> errors = new HashMap<>();
|
errors.put(key, value);
|
|
return errors;
|
}
|
}
|