1 | /** |
---|
2 | * MailArchiver is an application that provides services for storing and managing e-mail messages through a Web Services SOAP interface. |
---|
3 | * Copyright (C) 2012 Marcio Andre Scholl Levien and Fernando Alberto Reuter Wendt and Jose Ronaldo Nogueira Fonseca Junior |
---|
4 | * |
---|
5 | * This program is free software: you can redistribute it and/or modify |
---|
6 | * it under the terms of the GNU Affero General Public License as |
---|
7 | * published by the Free Software Foundation, either version 3 of the |
---|
8 | * License, or (at your option) any later version. |
---|
9 | * |
---|
10 | * This program is distributed in the hope that it will be useful, |
---|
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
13 | * GNU Affero General Public License for more details. |
---|
14 | * |
---|
15 | * You should have received a copy of the GNU Affero General Public License |
---|
16 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
---|
17 | */ |
---|
18 | |
---|
19 | /******************************************************************************\ |
---|
20 | * |
---|
21 | * This product was developed by |
---|
22 | * |
---|
23 | * SERVIÃO FEDERAL DE PROCESSAMENTO DE DADOS (SERPRO), |
---|
24 | * |
---|
25 | * a government company established under Brazilian law (5.615/70), |
---|
26 | * at Department of Development of Porto Alegre. |
---|
27 | * |
---|
28 | \******************************************************************************/ |
---|
29 | |
---|
30 | package serpro.mailarchiver.util; |
---|
31 | |
---|
32 | import java.io.File; |
---|
33 | import java.io.IOException; |
---|
34 | import java.io.PrintWriter; |
---|
35 | import java.nio.file.FileVisitResult; |
---|
36 | import java.nio.file.FileVisitor; |
---|
37 | import java.nio.file.Files; |
---|
38 | import java.nio.file.Path; |
---|
39 | import java.nio.file.Paths; |
---|
40 | import java.nio.file.StandardCopyOption; |
---|
41 | import java.nio.file.attribute.BasicFileAttributes; |
---|
42 | import java.util.Map; |
---|
43 | import java.util.TreeMap; |
---|
44 | |
---|
45 | import static com.google.common.base.Strings.isNullOrEmpty; |
---|
46 | |
---|
47 | import javax.servlet.ServletException; |
---|
48 | import javax.servlet.http.HttpServlet; |
---|
49 | import javax.servlet.http.HttpServletRequest; |
---|
50 | import javax.servlet.http.HttpServletResponse; |
---|
51 | |
---|
52 | import de.schlichtherle.truezip.file.TFile; |
---|
53 | import de.schlichtherle.truezip.nio.file.TPath; |
---|
54 | |
---|
55 | import org.springframework.beans.factory.annotation.Autowired; |
---|
56 | import org.springframework.beans.factory.annotation.Configurable; |
---|
57 | |
---|
58 | import serpro.mailarchiver.service.dto.TFolder; |
---|
59 | import serpro.mailarchiver.service.web.ArchiveServices; |
---|
60 | import serpro.mailarchiver.service.web.ServiceFault; |
---|
61 | |
---|
62 | @Configurable |
---|
63 | public class ImportServlet extends HttpServlet { |
---|
64 | |
---|
65 | private static final Logger log = Logger.getLocalLogger(); |
---|
66 | private Integer _filescounter = 0; |
---|
67 | private Integer _filesok = 0; |
---|
68 | private Integer _filesnok = 0; |
---|
69 | |
---|
70 | @Autowired |
---|
71 | private ArchiveServices archiveServices; |
---|
72 | |
---|
73 | @Override |
---|
74 | protected void doGet(HttpServletRequest req, HttpServletResponse resp){ |
---|
75 | try { |
---|
76 | log.info("ImportServlet inicializado: carregando mensagens de arquivo ZIP para o meta arquivamento..."); |
---|
77 | String foldername = "fid"; |
---|
78 | String sessname = "sid"; |
---|
79 | String protocol = "prt"; |
---|
80 | String port = "por"; |
---|
81 | String lang = "lng"; |
---|
82 | String base_folder = ""; |
---|
83 | |
---|
84 | String foldervalue = req.getParameter(foldername); |
---|
85 | String sessvalue = req.getParameter(sessname); |
---|
86 | String protocolvalue = req.getParameter(protocol); |
---|
87 | String portvalue = req.getParameter(port); |
---|
88 | String langvalue = req.getParameter(lang); |
---|
89 | |
---|
90 | //validates folder import destination. Defaults will be "inbox" |
---|
91 | |
---|
92 | if(foldervalue == null) { |
---|
93 | // The request parameter 'folder id' was not present in the query string. So, default import dir will be setted to 'inbox' folder |
---|
94 | log.debug("ImportServlet -> pasta de destino nula. Utilizando o padrão \"inbox\" (caixa de entrada) para destino da importação."); |
---|
95 | base_folder = "inbox"; |
---|
96 | } |
---|
97 | else if(foldervalue.isEmpty()) { |
---|
98 | // The request parameter 'param' was present in the query string but has no value. Same policy. |
---|
99 | log.debug("ImportServlet -> pasta de destino vazia. Utilizando o padrão \"inbox\" (caixa de entrada) para destino da importação."); |
---|
100 | base_folder = "inbox"; |
---|
101 | } |
---|
102 | else { |
---|
103 | //OK, user has passed a folder name. |
---|
104 | log.debug("ImportServlet -> pasta de destino da importação é \"" + foldervalue + "\"."); |
---|
105 | base_folder = foldervalue; |
---|
106 | } |
---|
107 | |
---|
108 | //validates the session id string handler |
---|
109 | if(isNullOrEmpty(sessvalue)) { |
---|
110 | //todo -> sess handler |
---|
111 | log.debug("ImportServlet -> identificador da sessão nulo ou inválido. Utilizando \"fakesessid\" para a importação."); |
---|
112 | sessvalue = "fakesessid"; |
---|
113 | } |
---|
114 | |
---|
115 | //validates protocol entry: defaults, points to HTTPS |
---|
116 | if(isNullOrEmpty(protocolvalue) || (!"http".equals(protocolvalue) && (!"https".equals(protocolvalue)))) { |
---|
117 | protocolvalue = "https"; |
---|
118 | } |
---|
119 | log.debug("ImportServlet -> protocolo em uso é \"" + protocolvalue + "\"."); |
---|
120 | |
---|
121 | //validates port entry: defaults, points to HTTPS default port (4334) |
---|
122 | if(isNullOrEmpty(portvalue)) { |
---|
123 | portvalue = "4334"; |
---|
124 | } |
---|
125 | log.debug("ImportServlet -> porta em uso é \"" + portvalue + "\"."); |
---|
126 | |
---|
127 | //validates lang entry: defaults PT-BR |
---|
128 | if(isNullOrEmpty(langvalue)) { |
---|
129 | langvalue = "pt-BR"; |
---|
130 | } |
---|
131 | log.debug("ImportServlet -> idioma em uso é \"" + langvalue + "\"."); |
---|
132 | |
---|
133 | resp.setContentType("text/html"); |
---|
134 | PrintWriter out = resp.getWriter(); |
---|
135 | StringBuilder htmlpage = new StringBuilder(); |
---|
136 | htmlpage.append( |
---|
137 | "<html>\n" |
---|
138 | + " <head>\n" |
---|
139 | + " <title>Import local messages package</title>\n" |
---|
140 | + " <script type=\"text/javascript\">\n" |
---|
141 | + " <!--\n" |
---|
142 | + " var text_timer;\n" |
---|
143 | |
---|
144 | + " function showLoader() {\n" |
---|
145 | + " var div_loader = document.createElement('div');\n" |
---|
146 | + " div_loader.id = 'div_loader';\n" |
---|
147 | + " window.document.getElementsByTagName('body')[0].appendChild(div_loader);\n" |
---|
148 | + " var odiv = document.getElementById('div_loader');\n" |
---|
149 | + " var div_loader_content = document.createTextNode('');\n" |
---|
150 | + " odiv.appendChild(div_loader_content);\n" |
---|
151 | + " odiv.style.backgroundColor = 'transparent';\n" |
---|
152 | + " odiv.style.width = '99%';\n" |
---|
153 | + " odiv.style.height = '99%';\n" |
---|
154 | + " odiv.style.display = 'block';\n" |
---|
155 | + " odiv.style.position = 'absolute';\n" |
---|
156 | + " odiv.style.zIndex = '1000';\n" |
---|
157 | + " odiv.style.margin = 0;\n" |
---|
158 | + " odiv.style.padding = '10px';\n" |
---|
159 | + " odiv.style.marginTop = '-95px';\n" |
---|
160 | + " odiv.style.marginLeft = '0px';\n" |
---|
161 | + " odiv.style.fontFamily = 'Verdana,Arial,Helvetica,sans-serif';\n" |
---|
162 | + " odiv.style.fontSize = '10pt';\n" |
---|
163 | + " odiv.style.fontWeight = 'bold';\n" |
---|
164 | + " odiv.style.color = 'black';\n" |
---|
165 | + " odiv.style.textAlign = 'left';\n" |
---|
166 | + " odiv.style.textIndent = '30px';\n" |
---|
167 | + " AguardeText();\n" |
---|
168 | + " document.getElementById('ma_impor_ifr').style.zIndex = '500';\n" |
---|
169 | + " document.getElementById('ma_impor_ifr').style.visibility = 'hidden';\n" |
---|
170 | + " }\n" |
---|
171 | |
---|
172 | + " function AguardeText() {\n" |
---|
173 | + " var b = [\" \", \".\", \"..\", \"...\" ];\n" |
---|
174 | + " var i = 0;\n" |
---|
175 | + " text_timer = setInterval(function () {\n" |
---|
176 | + " if(document.getElementById('div_loader').childNodes.length > 0) {\n" |
---|
177 | + " document.getElementById('div_loader').removeChild(document.getElementById('div_loader').firstChild);\n" |
---|
178 | + " }\n" |
---|
179 | + " var div_loader_content = document.createTextNode('").append(LocalizedString.LoadingData.get(lang)).append("' + b[i++]);\n" |
---|
180 | + " if (i == 4) {\n" |
---|
181 | + " i = 0;\n" |
---|
182 | + " }\n" |
---|
183 | + " document.getElementById('div_loader').appendChild(div_loader_content);\n" |
---|
184 | + " }, 800);\n" |
---|
185 | + " }\n" |
---|
186 | |
---|
187 | + " function hideLoader() {\n" |
---|
188 | + " if(window.document.getElementById('div_loader')) {\n" |
---|
189 | + " window.clearInterval(text_timer);\n" |
---|
190 | + " window.document.getElementsByTagName('body')[0].removeChild(window.document.getElementById('div_loader'));\n" |
---|
191 | + " document.getElementById('ma_impor_ifr').style.visibility = 'visible';\n" |
---|
192 | + " }\n" |
---|
193 | + " }\n" |
---|
194 | + " -->\n" |
---|
195 | + " </script>\n" |
---|
196 | + " <style>\n" |
---|
197 | + " body {\n" |
---|
198 | + " padding: 0;\n" |
---|
199 | + " margin: 0;\n" |
---|
200 | + " }\n" |
---|
201 | + " </style>\n" |
---|
202 | + " </head>\n" |
---|
203 | |
---|
204 | + " <body>\n" |
---|
205 | + " <iframe id=\"ma_impor_ifr\" name=\"ma_import_ifr\" src=\"") |
---|
206 | .append(protocolvalue).append("://127.0.0.1:").append(portvalue) |
---|
207 | .append("/arcservutil/form_upload.html?basevalue=").append(base_folder) |
---|
208 | .append("&sessvalue=").append(sessvalue) |
---|
209 | .append("&serprotocol=").append(protocolvalue) |
---|
210 | .append("&serport=").append(portvalue) |
---|
211 | .append("&langvalue=").append(langvalue) |
---|
212 | .append("\" width=\"510px\" height=\"120px\" frameborder=\"0\" scrolling=\"no\" style=\"padding: 0; margin: 0;\">\n" |
---|
213 | + " </iframe>\n" |
---|
214 | + " </body>\n" |
---|
215 | + "</html>"); |
---|
216 | |
---|
217 | out.println(htmlpage.toString()); |
---|
218 | log.debug("ImportServlet -> página web estática repassada ao cliente com a seguinte URL: \"" + protocolvalue + "://127.0.0.1:" + portvalue + "/arcservutil/form_upload.html?basevalue=" + base_folder + "&sessvalue=" + sessvalue + "&serprotocol=" + protocolvalue + "&serport=" + portvalue + "&langvalue=" + langvalue + "\"."); |
---|
219 | } |
---|
220 | catch(IOException ex) { |
---|
221 | resp.setContentType("text/html"); |
---|
222 | PrintWriter out = null; |
---|
223 | try { |
---|
224 | out = resp.getWriter(); |
---|
225 | } |
---|
226 | catch(IOException ex1) { |
---|
227 | log.error(ex1); |
---|
228 | } |
---|
229 | StringBuilder htmlpage = new StringBuilder(""); |
---|
230 | htmlpage.append( |
---|
231 | "<html>\n" |
---|
232 | + " <head>\n" |
---|
233 | + " </head>\n" |
---|
234 | + " <body>\n" |
---|
235 | + " <p style=\"font-family: Arial,Helvetica,sans-serif !important; font-size: 11px !important;\">MailArchiver</p>\n" |
---|
236 | + " </body>\n" |
---|
237 | + "</html>"); |
---|
238 | |
---|
239 | out.println(htmlpage.toString()); |
---|
240 | } |
---|
241 | } |
---|
242 | |
---|
243 | @Override |
---|
244 | protected void doPost(HttpServletRequest req, HttpServletResponse resp) { |
---|
245 | try { |
---|
246 | log.debug("ImportServlet -> processamento de HTTP POST data inicializado."); |
---|
247 | _doPost(req, resp); |
---|
248 | |
---|
249 | String lang = req.getParameter("lang"); |
---|
250 | |
---|
251 | resp.setContentType("text/html"); |
---|
252 | PrintWriter out = resp.getWriter(); |
---|
253 | StringBuilder htmlpage = new StringBuilder(""); |
---|
254 | |
---|
255 | htmlpage.append( |
---|
256 | "<html>\n" |
---|
257 | + " <head>\n" |
---|
258 | + " <script type=\"text/javascript\">\n" |
---|
259 | + " <!--\n" |
---|
260 | + " /*\n" |
---|
261 | + " * This script is invoked at the onload file import upload post.\n" |
---|
262 | + " * How we are at a CORS/XDR issue, it will try to set parent iframe\n" |
---|
263 | + " * longdesc property value - wich one is being watched by a intervaler\n" |
---|
264 | + " * function, intended to work as a listener to this handler. Lets try.\n" |
---|
265 | + " */\n" |
---|
266 | + "\n" |
---|
267 | |
---|
268 | + "/*\n" |
---|
269 | + " function signalParent() {\n" |
---|
270 | + " if(window.parent) {\n" |
---|
271 | + " if(window.parent.frames) {\n" |
---|
272 | + " if(window.parent.frames.length > 0) {\n" |
---|
273 | + " if(window.parent.frames[0].name == 'ma_import_local') {\n" |
---|
274 | + " var fooNode = window.parent.frames[0].document.createElement('div');\n" |
---|
275 | + " fooNode.id = 'foonode';\n" |
---|
276 | + " window.parent.frames[0].document.appendChild(fooNode);\n" |
---|
277 | + " }\n" |
---|
278 | + " }\n" |
---|
279 | + " }\n" |
---|
280 | + " }\n" |
---|
281 | + " }\n" |
---|
282 | + " window.onload = signalParent;\n" |
---|
283 | + " */\n" |
---|
284 | |
---|
285 | + " function updateScreen() {\n" |
---|
286 | + " if(window.parent) {\n" |
---|
287 | + " window.parent.hideLoader();\n" |
---|
288 | + " }\n" |
---|
289 | + " }\n" |
---|
290 | + " -->\n" |
---|
291 | + " </script>\n" |
---|
292 | + " <style>\n" |
---|
293 | + " body {\n" |
---|
294 | + " padding: 0;\n" |
---|
295 | + " margin: 0;\n" |
---|
296 | + " }\n" |
---|
297 | + " </style>\n" |
---|
298 | + " </head>\n" |
---|
299 | |
---|
300 | + " <body onload=\"updateScreen();\">\n" |
---|
301 | + " <p style=\"font-family: Arial,Helvetica,sans-serif !important; font-size: 11px !important;\">"); |
---|
302 | |
---|
303 | if((_filescounter == _filesok) && (_filescounter > 0 )) |
---|
304 | htmlpage.append(LocalizedString.ImportSuccessful.get(lang)); |
---|
305 | else if((_filescounter == _filesnok) && (_filescounter > 0)) |
---|
306 | htmlpage.append(LocalizedString.ImportFailure.get(lang)); |
---|
307 | else if((_filescounter != _filesok) && (_filesnok > 0)) |
---|
308 | htmlpage.append(LocalizedString.ImportPartialSucess.get(lang)); |
---|
309 | |
---|
310 | |
---|
311 | htmlpage.append("</p>\n" |
---|
312 | + "<dl>\n" |
---|
313 | + " <dt style=\"font-family: Arial,Helvetica,sans-serif !important; font-size: 10px !important;\">Resumo do processamento:</dt>\n" |
---|
314 | + " <dl style=\"display: list-item;list-style-type: square; font-family: Arial,Helvetica,sans-serif !important; font-size: 10px !important;color: black;\">").append(LocalizedString.TotalCounterData.get(lang)).append(_filescounter).append("</dl>\n" |
---|
315 | + " <dl style=\"display: list-item;list-style-type: square; font-family: Arial,Helvetica,sans-serif !important; font-size: 10px !important;color: blue;\">").append(LocalizedString.CounterDataOK.get(lang)).append(_filesok).append("</dl>\n" |
---|
316 | + " <dl style=\"display: list-item;list-style-type: square; font-family: Arial,Helvetica,sans-serif !important; font-size: 10px !important;color: red;\">").append(LocalizedString.CounterDataNOK.get(lang)).append(_filesnok).append("</dl>\n" |
---|
317 | + "</dl>\n" |
---|
318 | + " </body>\n" |
---|
319 | + "</html>"); |
---|
320 | |
---|
321 | out.println(htmlpage.toString()); |
---|
322 | } |
---|
323 | catch(ServletException ex) { |
---|
324 | resp.setContentType("text/html"); |
---|
325 | PrintWriter out = null; |
---|
326 | try { |
---|
327 | out = resp.getWriter(); |
---|
328 | } |
---|
329 | catch(IOException ex1) { |
---|
330 | log.error(ex1); |
---|
331 | } |
---|
332 | |
---|
333 | StringBuilder htmlpage = new StringBuilder(""); |
---|
334 | htmlpage.append( |
---|
335 | "<html>\n" |
---|
336 | + " <head>\n" |
---|
337 | + " <script type=\"text/javascript\">\n" |
---|
338 | + " <!--\n" |
---|
339 | + " function updateScreen() {\n" |
---|
340 | + " if(window.parent) {\n" |
---|
341 | + " window.parent.hideLoader();\n" |
---|
342 | + " }\n" |
---|
343 | + " }\n" |
---|
344 | + " -->\n" |
---|
345 | + " </script>\n" |
---|
346 | + " </head>\n" |
---|
347 | + " <body onload=\"updateScreen();\">\n" |
---|
348 | + " <p style=\"font-family: Arial,Helvetica,sans-serif !important; font-size: 11px !important;\">") |
---|
349 | .append(ex.getMessage()).append("</p>\n" |
---|
350 | + " </body>\n" |
---|
351 | + "</html>"); |
---|
352 | |
---|
353 | out.println(htmlpage.toString()); |
---|
354 | |
---|
355 | } |
---|
356 | catch(IOException ex) { |
---|
357 | resp.setContentType("text/html"); |
---|
358 | PrintWriter out = null; |
---|
359 | try { |
---|
360 | out = resp.getWriter(); |
---|
361 | } |
---|
362 | catch(IOException ex1) { |
---|
363 | log.error(ex1); |
---|
364 | } |
---|
365 | |
---|
366 | StringBuilder htmlpage = new StringBuilder(""); |
---|
367 | htmlpage.append( |
---|
368 | "<html>\n" |
---|
369 | + " <head>\n" |
---|
370 | + " <script type=\"text/javascript\">\n" |
---|
371 | + " <!--\n" |
---|
372 | + " function updateScreen() {\n" |
---|
373 | + " if(window.parent) {\n" |
---|
374 | + " window.parent.hideLoader();\n" |
---|
375 | + " }\n" |
---|
376 | + " }\n" |
---|
377 | + " -->\n" |
---|
378 | + " </script>\n" |
---|
379 | + " </head>\n" |
---|
380 | + " <body onload=\"updateScreen();\">\n" |
---|
381 | + " <p style=\"font-family: Arial,Helvetica,sans-serif !important; font-size: 11px !important;\">") |
---|
382 | .append(ex.getMessage()).append("</p>\n" |
---|
383 | + " </body>\n" |
---|
384 | + "</html>"); |
---|
385 | |
---|
386 | out.println(htmlpage.toString()); |
---|
387 | } |
---|
388 | } |
---|
389 | |
---|
390 | private void _doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { |
---|
391 | |
---|
392 | final String _sessionId = req.getParameter("sessionId"); |
---|
393 | final String _base = req.getParameter("base"); |
---|
394 | final String _flat = req.getParameter("flat"); |
---|
395 | final String _mailarc = req.getParameter("file_1"); |
---|
396 | final String _lang = req.getParameter("lang"); |
---|
397 | |
---|
398 | |
---|
399 | log.info("ImportServlet -> doPost data dumping ---\n\tsessionId: %s\n\tbase: %s\n\tflat: %s\n\tfile_1: %s", |
---|
400 | _sessionId, _base, _flat, _mailarc); |
---|
401 | |
---|
402 | log.debug("ImportServlet: reinicializando contador de files"); |
---|
403 | _filescounter = 0; |
---|
404 | _filesok = 0; |
---|
405 | _filesnok = 0; |
---|
406 | |
---|
407 | //TODO: validar sessão |
---|
408 | |
---|
409 | Path base0 = Paths.get(""); |
---|
410 | if(_base != null) { |
---|
411 | String[] names = _base.split("/|\\\\"); |
---|
412 | for(String name : names) { |
---|
413 | if(name.isEmpty()) { |
---|
414 | continue; |
---|
415 | } |
---|
416 | base0 = base0.resolve(name); |
---|
417 | } |
---|
418 | } |
---|
419 | final TPath base = new TPath(base0); |
---|
420 | |
---|
421 | final Map<Path, String> folderMap = new TreeMap<Path, String>(); |
---|
422 | |
---|
423 | if(base.toString().isEmpty()) { |
---|
424 | folderMap.put(base, null); |
---|
425 | } |
---|
426 | else { |
---|
427 | try { |
---|
428 | TFolder folderDto = archiveServices.createAbsoluteFolder(_sessionId, base.toString()); |
---|
429 | String folderId = folderDto.getId(); |
---|
430 | folderMap.put(base, folderId); |
---|
431 | } |
---|
432 | catch(ServiceFault e) { |
---|
433 | //log.error(e); |
---|
434 | } |
---|
435 | } |
---|
436 | |
---|
437 | final boolean flat = "true".equalsIgnoreCase(_flat); |
---|
438 | |
---|
439 | if((!_mailarc.endsWith(".zip")) |
---|
440 | && (!_mailarc.endsWith(".jar")) |
---|
441 | && (!_mailarc.endsWith(".tar")) |
---|
442 | && (!_mailarc.endsWith(".tar.gz")) |
---|
443 | && (!_mailarc.endsWith(".tgz")) |
---|
444 | && (!_mailarc.endsWith(".tar.bz2")) |
---|
445 | && (!_mailarc.endsWith(".tb2")) |
---|
446 | && (!_mailarc.endsWith(".tbz"))) { |
---|
447 | |
---|
448 | log.warn("ImportServlet: unsupported package file format at import event [" + _mailarc + "]"); |
---|
449 | |
---|
450 | throw new IOException(LocalizedString.InvalidPackageFormat.get(_lang)); |
---|
451 | } |
---|
452 | log.debug("ImportServlet: seguindo com pacote postado: \"" +_mailarc + "\""); |
---|
453 | Path tmpPath0 = ((File) req.getAttribute("file_1")).toPath(); |
---|
454 | log.debug("ImportServlet: tmp file path: \"" +tmpPath0.toString() + "\""); |
---|
455 | Path tmpPath = Files.move(tmpPath0, tmpPath0.resolveSibling(_mailarc), StandardCopyOption.REPLACE_EXISTING); |
---|
456 | log.debug("ImportServlet: path temporário após o files.move: \""+ tmpPath.toString() + "\""); |
---|
457 | |
---|
458 | final TPath zip = new TPath(tmpPath); |
---|
459 | |
---|
460 | Files.walkFileTree(zip, new FileVisitor<Path>() { |
---|
461 | |
---|
462 | |
---|
463 | @Override |
---|
464 | public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { |
---|
465 | log.debug("ImportServlet: acessando diretório de destino da importação"); |
---|
466 | |
---|
467 | Path rel = zip.relativize(dir); |
---|
468 | |
---|
469 | if(flat) { |
---|
470 | return FileVisitResult.CONTINUE; |
---|
471 | } |
---|
472 | |
---|
473 | Path folderPath = base.resolve(rel); |
---|
474 | |
---|
475 | if(folderPath.getNameCount() > base.getNameCount()) { |
---|
476 | try { |
---|
477 | log.debug("ImportServlet: invocando o serviço \"createAbsoluteFolder\" com o folder \"" + folderPath.toString() + "\""); |
---|
478 | TFolder folderDto = archiveServices.createAbsoluteFolder(_sessionId, folderPath.toString()); |
---|
479 | String folderId = folderDto.getId(); |
---|
480 | log.debug("ImportServlet: folderId \"" + folderId + "\""); |
---|
481 | folderMap.put(folderPath, folderId); |
---|
482 | } |
---|
483 | catch(ServiceFault e) { |
---|
484 | log.error("ImportServlet: falha ao invocar o serviço \"createAbsoluteFolder\". StackTrace:\n" + e.getStackTrace()+ "\""); |
---|
485 | } |
---|
486 | } |
---|
487 | |
---|
488 | return FileVisitResult.CONTINUE; |
---|
489 | } |
---|
490 | |
---|
491 | @Override |
---|
492 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { |
---|
493 | _filescounter++; |
---|
494 | Path rel = zip.relativize(file); |
---|
495 | |
---|
496 | Path folderPath = (flat) ? base : base.resolve(rel).getParent(); |
---|
497 | String folderId = folderMap.get(folderPath); |
---|
498 | |
---|
499 | log.debug("ImportServlet: navegando pelo conteúdo do pacote EML -> \"" + file.toString() + "\"."); |
---|
500 | |
---|
501 | //just "eml" files visitor |
---|
502 | if(file.toString().endsWith(".eml")) { |
---|
503 | String message = new String(Files.readAllBytes(file), Charsets.Windows_1252); |
---|
504 | |
---|
505 | try { |
---|
506 | log.info("ImportServlet: invocando serviço de arquivamento para \"" + file.toString() + "\""); |
---|
507 | archiveServices.archive(_sessionId, folderId, message); |
---|
508 | _filesok++; |
---|
509 | } |
---|
510 | catch(ServiceFault e) { |
---|
511 | log.error("ImportServlet: falha ao invocar serviço de arquivamento para \"" + file.toString() + "\" \n\t ---> " + e.getStackTrace()); |
---|
512 | _filesnok++; |
---|
513 | } |
---|
514 | } |
---|
515 | else { |
---|
516 | log.warn("ImportServlet: desconsiderando arquivo presente no pacote que não é EML[" + file.toString() + "]"); |
---|
517 | _filesnok++; |
---|
518 | } |
---|
519 | return FileVisitResult.CONTINUE; |
---|
520 | } |
---|
521 | |
---|
522 | @Override |
---|
523 | public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { |
---|
524 | //Path rel = zip.relativize(file); |
---|
525 | log.debug("ImportServlet: falha ao visitar o arquivo [" + file.toString() + "]:\n\t" + exc.getStackTrace()); |
---|
526 | _filesnok++; |
---|
527 | return FileVisitResult.CONTINUE; |
---|
528 | } |
---|
529 | |
---|
530 | @Override |
---|
531 | public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { |
---|
532 | //Path rel = zip.relativize(dir); |
---|
533 | return FileVisitResult.CONTINUE; |
---|
534 | } |
---|
535 | }); |
---|
536 | log.info("ImportServlet: contabilização de processamento\n\t ---> total de arquivos no pacote: " + _filescounter + "\n\t ---> total de arquivos importados: " + _filesok + "\n\t ---> total de arquivos falhos/inválidos: " + _filesnok); |
---|
537 | TFile.umount(zip.toFile(), true); |
---|
538 | log.debug("ImportServlet: servlet de importação encerrado"); |
---|
539 | } |
---|
540 | |
---|
541 | enum LocalizedString { |
---|
542 | |
---|
543 | InvalidPackageFormat( |
---|
544 | "<b>Falha na importação:</b><br/>O formato do pacote enviado é inválido.", |
---|
545 | "<b>Import failure:</b><br/>File format from sent package is invalid.", |
---|
546 | "<b>La importaciõn ha fallado:</b><br/>El formato del paquete enviado no es válido." |
---|
547 | ), |
---|
548 | |
---|
549 | InvalidMessageFormat( |
---|
550 | "<b>Falha na importação:</b><br/>Somente arquivos no formato "eml" são suportados.", |
---|
551 | "<b>Import failure:</b><br/>Only "eml" files are supported.", |
---|
552 | "<b>La importaciõn ha fallado:</b><br/>Sõlo archivos "eml" son compatibles." |
---|
553 | ), |
---|
554 | |
---|
555 | |
---|
556 | ImportFailure( |
---|
557 | "<b>A importação local não carregou mensagens</b><br/>Verifique o conteúdo dos dados do pacote: somente arquivos "eml" são suportados.", |
---|
558 | "<b>The import data is not loaded:</b><br/>Take a look at the package data: only "eml" files are supported.", |
---|
559 | "<b>La importaciõn de datos no está cargado:</b><br/>Revise el contenido del paquete: "eml" sólo son compatibles." |
---|
560 | ), |
---|
561 | |
---|
562 | ImportPartialSucess( |
---|
563 | "<b>A importação local carregou algumas mensagens</b><br/>É possível que outros arquivos de outros formatos estejam presentes no pacote.", |
---|
564 | "<b>Import succed partially:</b><br/>It is possible the package contains others files format plus messages data.", |
---|
565 | "<b>La importaciõn fue parcial:</b><br/>Puede haber otros formatos de archivo en el paquete." |
---|
566 | ), |
---|
567 | |
---|
568 | ImportSuccessful( |
---|
569 | "<b>Importação local realizada com sucesso!</b><br/>Lembre-se de atualizar a sua visualização do navegador para conferir o resultado.", |
---|
570 | "<b>Local import gracefull finished!</b><br/>Remember to refresh your page view in order to get the operation result.", |
---|
571 | "<b>La importación se completó con éxito!</b><br/>Recuerde actualizar su pantalla para ver los resultados." |
---|
572 | ), |
---|
573 | |
---|
574 | LoadingData( |
---|
575 | "Aguarde", |
---|
576 | "Loading", |
---|
577 | "Esperar" |
---|
578 | ), |
---|
579 | |
---|
580 | TotalCounterData( |
---|
581 | "Total de arquivos no pacote: ", |
---|
582 | "Total files in the package: ", |
---|
583 | "Total de archivos en el paquete: " |
---|
584 | ), |
---|
585 | |
---|
586 | CounterDataOK( |
---|
587 | "Carregados com êxito: ", |
---|
588 | "Successfully loaded: ", |
---|
589 | "Se ha cargado satisfactoriamente: " |
---|
590 | ), |
---|
591 | |
---|
592 | CounterDataNOK( |
---|
593 | "Não carregados: ", |
---|
594 | "Uncharged: ", |
---|
595 | "Sin carga: " |
---|
596 | ); |
---|
597 | |
---|
598 | private final String pt_BR; |
---|
599 | private final String en_US; |
---|
600 | private final String es_ES; |
---|
601 | |
---|
602 | LocalizedString(String pt_BR, String en_US, String es_ES) { |
---|
603 | this.pt_BR = pt_BR; |
---|
604 | this.en_US = en_US; |
---|
605 | this.es_ES = es_ES; |
---|
606 | } |
---|
607 | |
---|
608 | public String get(String lang) { |
---|
609 | if("en-US".equals(lang) || "en_US".equals(lang)) { |
---|
610 | return en_US; |
---|
611 | } |
---|
612 | else if("es-ES".equals(lang) || "es_ES".equals(lang)) { |
---|
613 | return es_ES; |
---|
614 | } |
---|
615 | else { |
---|
616 | return pt_BR; |
---|
617 | } |
---|
618 | } |
---|
619 | } |
---|
620 | |
---|
621 | } |
---|