1 package org.apache.maven.surefire.report;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import org.apache.maven.surefire.api.report.SafeThrowable;
24 import org.apache.maven.surefire.api.report.StackTraceWriter;
25 import org.apache.maven.surefire.api.util.internal.StringUtils;
26
27 import java.io.PrintWriter;
28 import java.io.StringWriter;
29 import java.util.Objects;
30
31
32
33
34
35
36 public class PojoStackTraceWriter
37 implements StackTraceWriter
38 {
39 private final Throwable t;
40
41 private final String testClass;
42
43 private final String testMethod;
44
45 public PojoStackTraceWriter( String testClass, String testMethod, Throwable t )
46 {
47 this.testClass = testClass;
48 this.testMethod = testMethod;
49 this.t = t;
50 }
51
52 @Override
53 public String writeTraceToString()
54 {
55 if ( t != null )
56 {
57 StringWriter w = new StringWriter();
58 try ( PrintWriter stackTrace = new PrintWriter( w ) )
59 {
60 t.printStackTrace( stackTrace );
61 }
62 StringBuffer builder = w.getBuffer();
63 if ( isMultiLineExceptionMessage( t ) )
64 {
65
66 String exc = t.getClass().getName() + ": ";
67 if ( StringUtils.startsWith( builder, exc ) )
68 {
69 builder.insert( exc.length(), '\n' );
70 }
71 }
72 return builder.toString();
73 }
74 return "";
75 }
76
77 @Override
78 public String smartTrimmedStackTrace()
79 {
80 return t == null ? "" : new SmartStackTraceParser( testClass, t, testMethod ).getString();
81 }
82
83 @Override
84 public String writeTrimmedTraceToString()
85 {
86 return t == null ? "" : SmartStackTraceParser.stackTraceWithFocusOnClassAsString( t, testClass );
87 }
88
89 @Override
90 public SafeThrowable getThrowable()
91 {
92 return t == null ? null : new SafeThrowable( t );
93 }
94
95 private static boolean isMultiLineExceptionMessage( Throwable t )
96 {
97 String msg = t.getLocalizedMessage();
98 if ( msg != null )
99 {
100 int countNewLines = 0;
101 for ( int i = 0, length = msg.length(); i < length; i++ )
102 {
103 if ( msg.charAt( i ) == '\n' )
104 {
105 if ( ++countNewLines == 2 )
106 {
107 break;
108 }
109 }
110 }
111 return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith( "\n" );
112 }
113 return false;
114 }
115
116 @Override
117 public boolean equals( Object o )
118 {
119 if ( this == o )
120 {
121 return true;
122 }
123 if ( o == null || getClass() != o.getClass() )
124 {
125 return false;
126 }
127 PojoStackTraceWriter that = ( PojoStackTraceWriter ) o;
128 return Objects.equals( t, that.t )
129 && Objects.equals( testClass, that.testClass )
130 && Objects.equals( testMethod, that.testMethod );
131 }
132
133 @Override
134 public int hashCode()
135 {
136 return Objects.hash( t, testClass, testMethod );
137 }
138 }