1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package fr.inrae.agroclim.indicators.exception;
18
19 import java.io.Serializable;
20 import java.util.Collection;
21 import java.util.Locale;
22
23 import org.json.JSONObject;
24
25 import fr.inrae.agroclim.indicators.resources.I18n;
26 import lombok.EqualsAndHashCode;
27 import lombok.Getter;
28 import lombok.RequiredArgsConstructor;
29 import lombok.ToString;
30
31
32
33
34
35
36
37
38
39 @EqualsAndHashCode
40 @RequiredArgsConstructor
41 @ToString
42 public final class ErrorMessage implements Serializable {
43
44
45
46
47 private static final long serialVersionUID = 6030595237342400004L;
48
49
50
51
52
53
54
55
56
57 public static String toJSON(final String bundleName, final ErrorType errorType,
58 final Collection<Serializable> arguments) {
59 return new ErrorMessage(bundleName, errorType, arguments).toJSON();
60 }
61
62
63
64
65 @Getter
66 private final String bundleName;
67
68
69
70
71 @Getter
72 private final ErrorType type;
73
74
75
76
77 @Getter
78 private final Collection<Serializable> arguments;
79
80
81
82
83
84
85
86 public String getMessage() {
87 return getMessage(Locale.getDefault());
88 }
89
90
91
92
93
94
95
96 public String getMessage(final I18n resources) {
97 if (arguments != null) {
98 return resources.format(type.getI18nKey(), arguments.toArray());
99 } else {
100 return resources.get(type.getI18nKey());
101 }
102 }
103
104
105
106
107
108
109
110 public String getMessage(final Locale locale) {
111 return getMessage(new I18n(bundleName, locale));
112 }
113
114
115
116
117
118
119 public String toJSON() {
120 final JSONObject json = new JSONObject();
121 json.put("bundleName", bundleName);
122 if (type.getCategory() != null) {
123 final JSONObject cat = new JSONObject();
124 cat.put("code", type.getCategory().getCode());
125 cat.put("name", type.getCategory().getName());
126 json.put("category", cat);
127 }
128 final JSONObject error = new JSONObject();
129 error.put("code", type.getFullCode());
130 error.put("name", type.getName());
131 json.put("error", error);
132 if (arguments != null) {
133 json.put("arguments", arguments.stream().map(Object::toString).toList());
134 }
135 return json.toString(2);
136 }
137 }