1 package org.apache.maven.surefire.api.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 reportsDir.mkdirs();
56 return new File( reportsDir, dumpFileName );
57 }
58
59 public static void dumpException( Throwable t, File dumpFile )
60 {
61 dumpException( t, null, dumpFile );
62 }
63
64 public static void dumpException( Throwable t, String msg, File dumpFile )
65 {
66 try
67 {
68 if ( t != null && dumpFile != null
69 && ( dumpFile.exists() || mkdirs( dumpFile ) && dumpFile.createNewFile() ) )
70 {
71 try ( PrintWriter pw = new PrintWriter( createWriter( dumpFile ) ) )
72 {
73 if ( msg != null )
74 {
75 pw.append( msg )
76 .append( StringUtils.NL );
77 }
78 t.printStackTrace( pw );
79 pw.append( StringUtils.NL )
80 .append( StringUtils.NL );
81 }
82 }
83 }
84 catch ( Exception e )
85 {
86
87 }
88 }
89
90 public static void dumpText( String msg, File dumpFile )
91 {
92 try
93 {
94 if ( msg != null && dumpFile != null
95 && ( dumpFile.exists() || mkdirs( dumpFile ) && dumpFile.createNewFile() ) )
96 {
97 try ( Writer writer = createWriter( dumpFile ) )
98 {
99 writer.append( msg )
100 .append( StringUtils.NL )
101 .append( StringUtils.NL );
102 }
103 }
104 }
105 catch ( Exception e )
106 {
107
108 }
109 }
110
111 public static String newFormattedDateFileName()
112 {
113 return new SimpleDateFormat( "yyyy-MM-dd'T'HH-mm-ss_SSS" ).format( new Date() );
114 }
115
116 private static Writer createWriter( File dumpFile ) throws IOException
117 {
118 return new OutputStreamWriter( new FileOutputStream( dumpFile, true ), UTF_8 )
119 .append( "# Created at " )
120 .append( new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS" ).format( new Date() ) )
121 .append( StringUtils.NL );
122 }
123
124 private static boolean mkdirs( File dumpFile )
125 {
126 File dir = dumpFile.getParentFile();
127 return dir.exists() || dir.mkdirs();
128 }
129 }