1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.surefire.api.util.internal;
20
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.io.Writer;
27 import java.text.SimpleDateFormat;
28 import java.util.Date;
29
30 import static java.nio.charset.StandardCharsets.UTF_8;
31
32
33
34
35
36
37
38
39 public final class DumpFileUtils {
40 private DumpFileUtils() {
41 throw new IllegalStateException("no instantiable constructor");
42 }
43
44
45
46
47
48
49
50 public static synchronized File newDumpFile(File reportsDir, String dumpFileName) {
51 reportsDir.mkdirs();
52 return new File(reportsDir, dumpFileName);
53 }
54
55 public static void dumpException(Throwable t, File dumpFile) {
56 dumpException(t, null, dumpFile);
57 }
58
59 public static void dumpException(Throwable t, String msg, File dumpFile) {
60 try {
61 if (t != null && dumpFile != null && (dumpFile.exists() || mkdirs(dumpFile) && dumpFile.createNewFile())) {
62 try (PrintWriter pw = new PrintWriter(createWriter(dumpFile))) {
63 if (msg != null) {
64 pw.append(msg).append(StringUtils.NL);
65 }
66 t.printStackTrace(pw);
67 pw.append(StringUtils.NL).append(StringUtils.NL);
68 }
69 }
70 } catch (Exception e) {
71
72 }
73 }
74
75 public static void dumpText(String msg, File dumpFile) {
76 try {
77 if (msg != null
78 && dumpFile != null
79 && (dumpFile.exists() || mkdirs(dumpFile) && dumpFile.createNewFile())) {
80 try (Writer writer = createWriter(dumpFile)) {
81 writer.append(msg).append(StringUtils.NL).append(StringUtils.NL);
82 }
83 }
84 } catch (Exception e) {
85
86 }
87 }
88
89 public static String newFormattedDateFileName() {
90 return new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss_SSS").format(new Date());
91 }
92
93 private static Writer createWriter(File dumpFile) throws IOException {
94 return new OutputStreamWriter(new FileOutputStream(dumpFile, true), UTF_8)
95 .append("# Created at ")
96 .append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(new Date()))
97 .append(StringUtils.NL);
98 }
99
100 private static boolean mkdirs(File dumpFile) {
101 File dir = dumpFile.getParentFile();
102 return dir.exists() || dir.mkdirs();
103 }
104 }