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