d225e1b01eee75512ce3c38bc1495dcc0d6e07e1
[vfc/nfvo/wfengine.git] / baseservice-i18n / src / main / java / org / openo / baseservice / i18n / DefaultErrorCodeI18n.java
1 /**
2  * Copyright 2017 ZTE Corporation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openo.baseservice.i18n;
17
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Map;
25 import java.util.Optional;
26 import java.util.concurrent.locks.Lock;
27 import java.util.concurrent.locks.ReentrantLock;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31
32 public final class DefaultErrorCodeI18n implements ErrorCodeI18n {
33
34     static final Logger logger = LoggerFactory.getLogger(DefaultErrorCodeI18n.class);
35     private static DefaultErrorCodeI18n singleton;
36     private static final Lock lock = new ReentrantLock();
37     private Map<Integer, ErrorItemImpl> errorItems;
38
39     private DefaultErrorCodeI18n() {
40         try {
41             init();
42         } catch (Exception e) {
43             logger.error("init ErrorCodeI18n failed.", e);
44         }
45     }
46
47     private void init() throws Exception {
48         final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
49         final Map<Integer, ErrorItemImpl> errorItems = new HashMap<Integer, DefaultErrorCodeI18n.ErrorItemImpl>();
50         JsonResourceScanner.findErrorCodePaths().forEach(path -> {
51             HashMap<String, Object> fileValues = null;
52             try (InputStream ins = systemClassLoader.getResourceAsStream(path)) {
53                 fileValues = I18nJsonUtil.getInstance().readFromJson(ins, HashMap.class);
54                 logger.info("load errorcode file success: " + path);
55             } catch (IOException ex) {
56                 logger.info("load errorcode file failed: " + path);
57                 logger.info(
58                         "load errorcode file failed: " + systemClassLoader.getResource(path).toString(),
59                         ex);
60                 return;
61             }
62             List<?> errcodes = (List<?>) fileValues.get("errcodes");
63             if (errcodes == null) {
64                 logger.info("none errcodes field in: " + path);
65                 return;
66             }
67
68             String fileName = null;
69             int i = path.lastIndexOf("/");
70             if (i > -1) {
71                 fileName = path.substring(i + 1);
72             } else {
73                 fileName = path;
74             }
75             i = fileName.indexOf("-errorcode-");
76             String localeSrc = fileName.substring(i + 11, fileName.lastIndexOf("."));
77             if (localeSrc.isEmpty()) {
78                 logger.info("parse errorcode file failed: locale is null");
79                 return;
80             }
81
82             String[] ss = localeSrc.replace("-", "_").split("_");
83             String tempLocale = null;
84             if (ss.length == 1) {
85                 tempLocale = new Locale(ss[0]).toString();
86             } else if (ss.length == 2) {
87                 tempLocale = new Locale(ss[0], ss[1]).toString();
88             } else {
89                 logger.info("parse i18n file failed: locale is error \"" + localeSrc + "\"");
90                 return;
91             }
92             String locale = tempLocale;
93             errcodes.forEach(errorcode -> {
94                 Map<String, String> errorConfig = (Map<String, String>) errorcode;
95                 Integer code = Integer.valueOf(errorConfig.get("code"));
96                 String level = errorConfig.get("level");
97                 String label = errorConfig.get("label");
98
99                 ErrorItemImpl errorItem = errorItems.get(Integer.valueOf(code));
100                 if (errorItem == null) {
101                     errorItem = new ErrorItemImpl();
102                     errorItem.errorCode = code.intValue();
103                     errorItem.level = ErrorCodeLevelUtil.transfer2Int(level);
104                     errorItems.put(code, errorItem);
105                 }
106                 errorItem.addLabel(locale, label);
107             });
108         });
109
110         errorItems.forEach((code, errorItem) -> {
111             errorItem.unmodifiable();
112         });
113         this.errorItems = Collections.unmodifiableMap(errorItems);
114     }
115
116
117     static DefaultErrorCodeI18n getInstance() {
118         if (singleton == null) {
119             lock.lock();
120             try {
121                 if (singleton == null) {
122                     singleton = new DefaultErrorCodeI18n();
123                 }
124             } finally {
125                 lock.unlock();
126             }
127         }
128         return singleton;
129     }
130
131
132     /*
133      * (non-Javadoc)
134      *
135      * @see com.zte.ums.zenap.i18n.ErrorCodeI18n#getErrorItem(int)
136      */
137     @Override
138     public Optional<ErrorItem> getErrorItem(int errorCode) {
139         return Optional.ofNullable(errorItems.get(Integer.valueOf(errorCode)));
140     }
141
142
143     public static class ErrorItemImpl implements ErrorItem {
144
145         private int errorCode;
146
147         private int level;
148
149         private Map<String, String> labels = new HashMap<String, String>();
150
151         private String jsonString = null;
152
153         @Override
154         public int getErrorCode() {
155             return errorCode;
156         }
157
158         @Override
159         public int getLevel() {
160             return level;
161         }
162
163         public Map<String, String> getLabels() {
164             return labels;
165         }
166
167         private void unmodifiable() {
168             if (labels != null) {
169                 labels = Collections.unmodifiableMap(labels);
170             }
171         }
172
173         private synchronized void addLabel(String locale, String label) {
174             labels.put(locale, label);
175         }
176
177         @Override
178         public String getLabel(Locale theLocale) {
179             if (theLocale == null) {
180                 return null;
181             }
182             return labels.get(I18nLocaleTransfer.transfer(theLocale, labels.keySet()));
183         }
184
185         @Override
186         public String getCanonicalLabels(int errorCode) {
187             String jsonString = this.jsonString;
188             if (jsonString == null) {
189                 ErrorItem2 errorItem2 = new ErrorItem2();
190                 errorItem2.setErrorCode(this.errorCode);
191                 errorItem2.setLevel(ErrorCodeLevelUtil.transfer2String(this.errorCode));
192                 errorItem2.setErrlabels(labels);
193                 try {
194                     jsonString = I18nJsonUtil.getInstance().writeToJson(errorItem2);
195                 } catch (Exception e) {
196                     logger.info("getCanonicalLabels failed from with param errorCode " + errorCode
197                             + " and this errorCode " + this.errorCode, e);
198                     return null;
199                 }
200                 this.jsonString = jsonString;
201             }
202             return jsonString;
203         }
204
205     }
206
207     protected static class ErrorItem2 {
208
209         private int errorCode;
210
211         private String level;
212
213         private Map<String, String> errlabels;
214
215         public ErrorItem2() {
216
217         }
218
219         public int getErrorCode() {
220             return errorCode;
221         }
222
223         public void setErrorCode(int errorCode) {
224             this.errorCode = errorCode;
225         }
226
227         public String getLevel() {
228             return level;
229         }
230
231         public void setLevel(String level) {
232             this.level = level;
233         }
234
235         public Map<String, String> getErrlabels() {
236             return errlabels;
237         }
238
239         public void setErrlabels(Map<String, String> errlabels) {
240             this.errlabels = errlabels;
241         }
242     }
243
244     protected static class ErrorCodeLevelUtil {
245
246         public static final int ERROR_LEVEL = javax.swing.JOptionPane.ERROR_MESSAGE;
247
248         public static final int WARN_LEVEL = javax.swing.JOptionPane.WARNING_MESSAGE;
249
250         public static final int INFO_LEVEL = javax.swing.JOptionPane.INFORMATION_MESSAGE;
251
252         protected static String transfer2String(int errorCode) {
253             switch (errorCode) {
254                 case ERROR_LEVEL:
255                     return "ERROR";
256                 case INFO_LEVEL:
257                     return "INFO";
258                 case WARN_LEVEL:
259                     return "WARN";
260             }
261             return null;
262         }
263
264         protected static int transfer2Int(String level) {
265             switch (level) {
266                 case "ERROR":
267                     return ERROR_LEVEL;
268                 case "INFO":
269                     return INFO_LEVEL;
270                 case "WARN":
271                     return WARN_LEVEL;
272             }
273             return -1;
274         }
275
276     }
277
278 }