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 java.io.PrintWriter;
24 import java.io.StringWriter;
25 import org.apache.maven.surefire.util.internal.StringUtils;
26
27
28
29
30
31
32
33 public class LegacyPojoStackTraceWriter
34 implements StackTraceWriter
35 {
36 private final Throwable t;
37
38 private final String testClass;
39
40 private final String testMethod;
41
42 public LegacyPojoStackTraceWriter( String testClass, String testMethod, Throwable t )
43 {
44 this.testClass = testClass;
45 this.testMethod = testMethod;
46 this.t = t;
47 }
48
49 public String writeTraceToString()
50 {
51 StringWriter w = new StringWriter();
52 if ( t != null )
53 {
54 t.printStackTrace( new PrintWriter( w ) );
55 w.flush();
56 }
57 return w.toString();
58 }
59
60 public String smartTrimmedStackTrace()
61 {
62 StringBuilder result = new StringBuilder();
63 result.append( testClass );
64 result.append( "#" );
65 result.append( testMethod );
66 SafeThrowable throwable = getThrowable();
67 if ( throwable.getTarget() instanceof AssertionError )
68 {
69 result.append( " " );
70 result.append( getTruncatedMessage( throwable.getMessage(), 77 - result.length() ) );
71 }
72 else
73 {
74 Throwable target = throwable.getTarget();
75 if ( target != null )
76 {
77 result.append( " " );
78 result.append( target.getClass().getSimpleName() );
79 result.append( getTruncatedMessage( throwable.getMessage(), 77 - result.length() ) );
80 }
81 }
82 return result.toString();
83 }
84
85 private static String getTruncatedMessage( String msg, int i )
86 {
87 if ( i < 0 )
88 {
89 return "";
90 }
91 if ( msg == null )
92 {
93 return "";
94 }
95 String substring = msg.substring( 0, Math.min( i, msg.length() ) );
96 if ( i < msg.length() )
97 {
98 return " " + substring + "...";
99 }
100 else
101 {
102 return " " + substring;
103 }
104 }
105
106
107 public String writeTrimmedTraceToString()
108 {
109 String text = writeTraceToString();
110
111 String marker = "at " + testClass + "." + testMethod;
112
113 String[] lines = StringUtils.split( text, "\n" );
114 int lastLine = lines.length - 1;
115 int causedByLine = -1;
116
117 for ( int i = 1; i < lines.length; i++ )
118 {
119 String line = lines[i].trim();
120 if ( line.startsWith( marker ) )
121 {
122 lastLine = i;
123 }
124 else if ( line.startsWith( "Caused by" ) )
125 {
126 causedByLine = i;
127 break;
128 }
129 }
130
131 StringBuilder trace = new StringBuilder();
132 for ( int i = 0; i <= lastLine; i++ )
133 {
134 trace.append( lines[i] );
135 trace.append( "\n" );
136 }
137
138 if ( causedByLine != -1 )
139 {
140 for ( int i = causedByLine; i < lines.length; i++ )
141 {
142 trace.append( lines[i] );
143 trace.append( "\n" );
144 }
145 }
146 return trace.toString();
147 }
148
149 public SafeThrowable getThrowable()
150 {
151 return new SafeThrowable( t );
152 }
153 }