Kenmegne
7 days ago 23a46b4be35277e06ec89f48730eeb694e686be8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
 * 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;
    }
}