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