1 18 package org.apache.beehive.netui.util; 19 20 import org.apache.beehive.netui.util.internal.InternalStringBuilder; 21 22 import java.io.PrintWriter ; 23 import java.io.StringWriter ; 24 25 import javax.servlet.jsp.JspException ; 26 import javax.servlet.jsp.el.ELException ; 27 import javax.servlet.ServletException ; 28 29 32 public class HtmlExceptionFormatter { 33 34 37 private static final String HTML_LINE_BREAK = "<br/>"; 38 39 40 43 private static final String LINE_BREAK = "\n"; 44 45 private static final String CAUSED_BY = "caused by "; 46 47 61 public static String format(String message, Throwable t, boolean includeStackTrace) { 62 InternalStringBuilder buf = new InternalStringBuilder(); 63 64 if(message != null) { 65 buf.append(message); 66 67 Throwable cause = discoverRootCause(t); 68 if(cause != null) { 69 buf.append(HTML_LINE_BREAK); 70 buf.append(CAUSED_BY); 71 buf.append(": "); 72 buf.append(cause.toString()); 73 } 74 } 75 76 if(includeStackTrace) { 77 if(message != null) 78 buf.append(HTML_LINE_BREAK); 79 80 String st = addStackTrace(t); 81 buf.append(st); 82 83 Throwable rootCause = null; 84 Throwable tmp = t; 85 while(hasRootCause(tmp) && (rootCause = discoverRootCause(tmp)) != null) { 86 st = addStackTrace(rootCause); 87 buf.append(HTML_LINE_BREAK); 88 buf.append(st); 89 tmp = rootCause; 90 } 91 } 92 93 return buf.toString().replaceAll(LINE_BREAK, HTML_LINE_BREAK); 94 } 95 96 private static final String addStackTrace(Throwable t) { 97 InternalStringBuilder buf = new InternalStringBuilder(); 98 StringWriter sw = new StringWriter (); 99 PrintWriter pw = new PrintWriter (sw); 100 t.printStackTrace(pw); 101 pw.flush(); 102 pw.close(); 103 104 String error = sw.toString(); 105 int pos = error.indexOf(LINE_BREAK); 106 if(pos != -1) { 107 String lineOne = error.substring(0, pos); 108 String rest = error.substring(pos); 109 110 buf.append("<span class='pfErrorLineOne'>"); 111 buf.append(lineOne); 112 buf.append("</span>"); 113 buf.append(rest); 114 } else { 115 buf.append(sw.toString()); 116 } 117 118 return buf.toString(); 119 } 120 121 private static final boolean hasRootCause(Throwable t) { 122 if(t.getCause() == null && (t instanceof JspException || t instanceof ServletException || t instanceof ELException )) 123 return true; 124 else 125 return false; 126 } 127 128 private static final Throwable discoverRootCause(Throwable t) { 129 Throwable cause = null; 130 if(t instanceof JspException ) 131 cause = ((JspException )t).getRootCause(); 132 else if(t instanceof ServletException ) 133 cause = ((ServletException )t).getRootCause(); 134 else if(t instanceof ELException ) 135 cause = ((ELException )t).getRootCause(); 136 else 137 cause = t.getCause(); 138 139 return cause; 140 } 141 } 142 | Popular Tags |