public static void raiseException(Throwable t) { error(t + ":\n" + StrUtils.join(t.getStackTrace(), "\n")); t = t.getCause(); if (t != null) error("Caused by " + t + ":\n" + StrUtils.join(t.getStackTrace(), "\n")); Execution.putOutput("exec.status", "exception"); exitCode = 1; }
// // Examine a single method to see if it raises SQLFeatureNotSupportedException. // private void vetMethod( Object candidate, Class iface, Method method, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { try { method.invoke(candidate, getNullArguments(method.getParameterTypes())); // it's ok for the method to succeed } catch (Throwable e) { if (!(e instanceof InvocationTargetException)) { recordUnexpectedError(candidate, iface, method, notUnderstoodList, e); } else { Throwable cause = e.getCause(); if (cause instanceof SQLFeatureNotSupportedException) { boolean isExcludable = isExcludable(method); if (!isExcludable) { StackTraceElement[] stack = cause.getStackTrace(); int i = 0; while (i < stack.length && !stack[i].getMethodName().equals("notImplemented")) { ++i; } while (i < stack.length && stack[i].getMethodName().equals("notImplemented")) { ++i; } if (i == stack.length) { // cause.printStackTrace(); } unsupportedList.add( candidate.getClass().getName() + ": " + method + "@" + (i == stack.length ? "no source" : cause.getStackTrace()[i])); } else { } } else if (cause instanceof SQLException) { // swallow other SQLExceptions, caused by bogus args } else if (cause instanceof NullPointerException) { // swallow other NPEs, caused by bogus args } else if (cause instanceof ArrayIndexOutOfBoundsException) { // swallow these, caused by bogus args } else { recordUnexpectedError(candidate, iface, method, notUnderstoodList, cause); } } } }
/** Checks all of the methods in gen for consistency */ public static void checkMgens(final ClassGen gen) { if (skip_checks) return; Method[] methods = gen.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; // System.out.println ("Checking method " + method + " in class " // + gen.getClassName()); checkMgen(new MethodGen(method, gen.getClassName(), gen.getConstantPool())); } if (false) { Throwable t = new Throwable(); t.fillInStackTrace(); StackTraceElement[] ste = t.getStackTrace(); StackTraceElement caller = ste[1]; System.out.printf( "%s.%s (%s line %d)", caller.getClassName(), caller.getMethodName(), caller.getFileName(), caller.getLineNumber()); for (int ii = 2; ii < ste.length; ii++) System.out.printf(" [%s line %d]", ste[ii].getFileName(), ste[ii].getLineNumber()); System.out.printf("\n"); dump_methods(gen); } }
/** * Returns an string array representation of the specified throwable. * * @param th throwable * @return string array */ private static String[] toArray(final Throwable th) { final StackTraceElement[] st = th.getStackTrace(); final String[] obj = new String[st.length + 1]; obj[0] = th.toString(); for (int i = 0; i < st.length; i++) obj[i + 1] = " " + st[i]; return obj; }
private static String getStackTraceAsText(Throwable t) { StringBuilder builder = new StringBuilder(); StackTraceElement[] stackTraceElements = t.getStackTrace(); for (int index = 0; index < stackTraceElements.length; index++) { StackTraceElement stackTraceElement = stackTraceElements[index]; builder.append(" ").append(stackTraceElement.toString()).append('\n'); } return builder.toString(); }
protected static String printException(Throwable ex) throws IOException { if (ex == null) return null; StackTraceElement[] stack_trace = ex.getStackTrace(); StringBuilder sb = new StringBuilder(); sb.append("\n<" + CDATA + "\n"); sb.append(ex.getClass().getName() + " \n"); for (int i = 0; i < stack_trace.length; i++) { StackTraceElement frame = stack_trace[i]; sb.append("at " + frame.toString() + " \n"); } sb.append("\n]]>"); return sb.toString(); }
public static String getCompressedStackTrace( Throwable t, int frames_to_skip, int iMaxLines, boolean showErrString) { StringBuffer sbStackTrace = new StringBuffer(showErrString ? (t.toString() + "; ") : ""); StackTraceElement[] st = t.getStackTrace(); if (iMaxLines < 0) { iMaxLines = st.length + iMaxLines; if (iMaxLines < 0) { iMaxLines = 1; } } int iMax = Math.min(st.length, iMaxLines + frames_to_skip); for (int i = frames_to_skip; i < iMax; i++) { if (i > frames_to_skip) { sbStackTrace.append(", "); } String classname = st[i].getClassName(); String cnShort = classname.substring(classname.lastIndexOf(".") + 1); if (Constants.IS_CVS_VERSION) { if (STOP_AT_INITIALIZER && st[i].getClassName().equals("com.aelitis.azureus.ui.swt.Initializer")) { sbStackTrace.append("Initializer"); break; } // Formatted so it's clickable in eclipse sbStackTrace.append(st[i].getMethodName()); sbStackTrace.append(" ("); sbStackTrace.append(classname); sbStackTrace.append(".java:"); sbStackTrace.append(st[i].getLineNumber()); sbStackTrace.append(')'); } else { sbStackTrace.append("::"); sbStackTrace.append(st[i].getMethodName()); sbStackTrace.append("::"); sbStackTrace.append(st[i].getLineNumber()); } } Throwable cause = t.getCause(); if (cause != null) { sbStackTrace.append("\n\tCaused By: "); sbStackTrace.append(getCompressedStackTrace(cause, 0)); } return sbStackTrace.toString(); }
protected String getTitle(Throwable t) { String message = t.getMessage(); String tit = message; if (tit == null) { StackTraceElement el = t.getStackTrace()[0]; tit = t.getClass().getName().substring(t.getClass().getPackage().getName().length() + 1) + " " + el.getFileName() + ":" + el.getLineNumber(); } return tit; }
private void dumpInnerCauses(StringBuilder sb, Throwable innerCause, int indent) { if (innerCause == null) { return; } for (int i = 0; i < indent; i++) { sb.append(INDENT_STRING); } sb.append("Caused by "); sb.append(innerCause.getClass().getName()); sb.append(": "); sb.append(innerCause.getMessage()); sb.append("\n"); dumpStackTrace(sb, innerCause.getStackTrace(), indent + 1); dumpInnerCauses(sb, innerCause.getCause(), indent); }
private static void printThrowable(OutputStream stream, Throwable throwable) { printBytes(stream, ("Exception " + throwable.toString()).getBytes()); printNewLine(stream); StackTraceElement[] stackTraceElements = throwable.getStackTrace(); for (int i = stackTraceElements.length - 1; i >= 0; i--) { StackTraceElement element = stackTraceElements[i]; printBytes(stream, element.getFileName().getBytes()); printBytes(stream, ":".getBytes()); printBytes(stream, String.valueOf(element.getLineNumber()).getBytes()); printNewLine(stream); } if (throwable.getCause() != null) { printBytes(stream, "Caused by:\n".getBytes()); printThrowable(stream, throwable.getCause()); } }
private void dumpIndent(StringBuilder sb, int indent, boolean printStackTrace) { for (int i = 0; i < indent; i++) { sb.append(INDENT_STRING); } sb.append("*op* "); sb.append(operation); sb.append(", st: "); sb.append(status); if (minor) { sb.append(", MINOR"); } sb.append(", msg: "); sb.append(message); if (count > 1) { sb.append(" x"); sb.append(count); } sb.append("\n"); for (Map.Entry<String, Serializable> entry : getParams().entrySet()) { for (int i = 0; i < indent + 2; i++) { sb.append(INDENT_STRING); } sb.append("[p]"); sb.append(entry.getKey()); sb.append("="); sb.append(dumpEntry(indent + 2, entry.getValue())); sb.append("\n"); } for (Map.Entry<String, Serializable> entry : getContext().entrySet()) { for (int i = 0; i < indent + 2; i++) { sb.append(INDENT_STRING); } sb.append("[c]"); sb.append(entry.getKey()); sb.append("="); sb.append(dumpEntry(indent + 2, entry.getValue())); sb.append("\n"); } for (Map.Entry<String, Serializable> entry : getReturns().entrySet()) { for (int i = 0; i < indent + 2; i++) { sb.append(INDENT_STRING); } sb.append("[r]"); sb.append(entry.getKey()); sb.append("="); sb.append(dumpEntry(indent + 2, entry.getValue())); sb.append("\n"); } for (String line : details) { for (int i = 0; i < indent + 2; i++) { sb.append(INDENT_STRING); } sb.append("[d]"); sb.append(line); sb.append("\n"); } if (cause != null) { for (int i = 0; i < indent + 2; i++) { sb.append(INDENT_STRING); } sb.append("[cause]"); sb.append(cause.getClass().getSimpleName()); sb.append(":"); sb.append(cause.getMessage()); sb.append("\n"); if (printStackTrace) { dumpStackTrace(sb, cause.getStackTrace(), indent + 4); dumpInnerCauses(sb, cause.getCause(), indent + 3); } } for (OperationResult sub : getSubresults()) { sub.dumpIndent(sb, indent + 1, printStackTrace); } }
private OperationResultType createOperationResultType(OperationResult opResult) { OperationResultType result = new OperationResultType(); result.setToken(opResult.getToken()); result.setStatus(OperationResultStatus.createStatusType(opResult.getStatus())); if (opResult.getCount() != 1) { result.setCount(opResult.getCount()); } result.setOperation(opResult.getOperation()); result.setMessage(opResult.getMessage()); result.setMessageCode(opResult.getMessageCode()); if (opResult.getCause() != null || !opResult.details.isEmpty()) { StringBuilder detailsb = new StringBuilder(); // Record text messages in details (if present) if (!opResult.details.isEmpty()) { for (String line : opResult.details) { detailsb.append(line); detailsb.append("\n"); } } // Record stack trace in details if a cause is present if (opResult.getCause() != null) { Throwable ex = opResult.getCause(); detailsb.append(ex.getClass().getName()); detailsb.append(": "); detailsb.append(ex.getMessage()); detailsb.append("\n"); StackTraceElement[] stackTrace = ex.getStackTrace(); for (int i = 0; i < stackTrace.length; i++) { detailsb.append(stackTrace[i].toString()); detailsb.append("\n"); } } result.setDetails(detailsb.toString()); } if (StringUtils.isNotEmpty(opResult.getLocalizationMessage())) { LocalizedMessageType message = new LocalizedMessageType(); message.setKey(opResult.getLocalizationMessage()); if (opResult.getLocalizationArguments() != null) { message.getArgument().addAll(opResult.getLocalizationArguments()); } result.setLocalizedMessage(message); } // Set<Entry<String, Serializable>> params = opResult.getParams(); // if (!params.isEmpty()) { ParamsType paramsType = ParamsTypeUtil.toParamsType(opResult.getParams()); result.setParams(paramsType); // for (Entry<String, Serializable> entry : params) { // paramsType.getEntry().add(createEntryElement(entry.getKey(),entry.getValue())); // } // } // Set<Entry<String, Serializable>> context = opResult.getContext().entrySet(); // if (!context.isEmpty()) { paramsType = ParamsTypeUtil.toParamsType(opResult.getContext()); result.setContext(paramsType); // for (Entry<String, Serializable> entry : context) { // paramsType.getEntry().add(createEntryElement(entry.getKey(),entry.getValue())); // } // } // Set<Entry<String, Serializable>> returns = opResult.getReturns().entrySet(); // if (!returns.isEmpty()) { paramsType = ParamsTypeUtil.toParamsType(opResult.getReturns()); result.setReturns(paramsType); // for (Entry<String, Serializable> entry : returns) { // paramsType.getEntry().add(createEntryElement(entry.getKey(),entry.getValue())); // } // } for (OperationResult subResult : opResult.getSubresults()) { result.getPartialResults().add(opResult.createOperationResultType(subResult)); } return result; }
public Writer getErrorReport( Writer to, final HttpServletRequest request, CharTransformer escape) throws IOException { final Writer logMsg = new StringWriter(); final Writer tee = new org.mmbase.util.ChainedWriter(to, logMsg); Writer msg = tee; LinkedList<Throwable> stack = getStack(); String ticket = new Date().toString(); Map<String, String> props; try { props = org.mmbase.util.ApplicationContextReader.getProperties("mmbase_errorpage"); } catch (javax.naming.NamingException ne) { props = Collections.emptyMap(); log.info(ne); } if (request != null) { { msg.append("Headers\n----------\n"); // request properties for (Object name : Collections.list(request.getHeaderNames())) { msg.append( escape.transform( name + ": " + escape.transform(request.getHeader((String) name)) + "\n")); } } { msg.append("\nAttributes\n----------\n"); Pattern p = requestIgnore; if (p == null && props.get("request_ignore") != null) { p = Pattern.compile(props.get("request_ignore")); } for (Object name : Collections.list(request.getAttributeNames())) { if (p == null || !p.matcher((String) name).matches()) { msg.append( escape.transform(name + ": " + request.getAttribute((String) name) + "\n")); } } } if (Boolean.TRUE.equals(showSession) || (showSession == null && !"false".equals(props.get("show_session")))) { HttpSession ses = request.getSession(false); if (ses != null) { msg.append("\nSession\n----------\n"); Pattern p = sessionIgnore; if (p == null && props.get("session_ignore") != null) { p = Pattern.compile(props.get("session_ignore")); } for (Object name : Collections.list(ses.getAttributeNames())) { if (p == null || !p.matcher((String) name).matches()) { msg.append(escape.transform(name + ": " + ses.getAttribute((String) name) + "\n")); } } } } } msg.append("\n"); msg.append("Misc. properties\n----------\n"); if (request != null) { msg.append("method: ").append(escape.transform(request.getMethod())).append("\n"); msg.append("querystring: ").append(escape.transform(request.getQueryString())).append("\n"); msg.append("requesturl: ") .append(escape.transform(request.getRequestURL().toString())) .append("\n"); } if (Boolean.TRUE.equals(showMMBaseVersion) || (showMMBaseVersion == null && !"false".equals(props.get("show_mmbase_version")))) { msg.append("mmbase version: ").append(org.mmbase.Version.get()).append("\n"); } msg.append("status: ").append("").append(String.valueOf(status)).append("\n\n"); if (request != null) { msg.append("Parameters\n----------\n"); // request parameters Enumeration en = request.getParameterNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); msg.append(name) .append(": ") .append(escape.transform(request.getParameter(name))) .append("\n"); } } msg.append("\nException ") .append(ticket) .append("\n----------\n\n") .append( exception != null ? (escape.transform(exception.getClass().getName())) : "NO EXCEPTION") .append(": "); int wroteCauses = 0; while (!stack.isEmpty()) { Throwable t = stack.removeFirst(); // add stack stacktraces if (t != null) { if (stack.isEmpty()) { // write last message always msg = tee; } String message = t.getMessage(); if (msg != tee) { to.append("\n=== skipped(see log) : ") .append(escape.transform(t.getClass().getName())) .append(": ") .append(message) .append("\n"); } msg.append("\n\n").append(escape.transform(t.getClass().getName() + ": " + message)); StackTraceElement[] stackTrace = t.getStackTrace(); for (StackTraceElement e : stackTrace) { msg.append("\n at ").append(escape.transform(e.toString())); } if (!stack.isEmpty()) { msg.append("\n-------caused:\n"); } wroteCauses++; if (wroteCauses >= MAX_CAUSES) { msg = logMsg; } } } // write errors to log if (status == 500) { try { if (props.get("to") != null && props.get("to").length() > 0) { javax.naming.Context initCtx = new javax.naming.InitialContext(); javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env"); Object mailSession = envCtx.lookup("mail/Session"); Class sessionClass = Class.forName("javax.mail.Session"); Class recipientTypeClass = Class.forName("javax.mail.Message$RecipientType"); Class messageClass = Class.forName("javax.mail.internet.MimeMessage"); Object mail = messageClass.getConstructor(sessionClass).newInstance(mailSession); messageClass .getMethod("addRecipients", recipientTypeClass, String.class) .invoke(mail, recipientTypeClass.getDeclaredField("TO").get(null), props.get("to")); messageClass.getMethod("setSubject", String.class).invoke(mail, ticket); mail.getClass().getMethod("setText", String.class).invoke(mail, logMsg.toString()); Class.forName("javax.mail.Transport") .getMethod("send", Class.forName("javax.mail.Message")) .invoke(null, mail); tee.append("\nmailed to (").append(String.valueOf(props)).append(")"); } } catch (Exception nnfe) { tee.append("\nnot mailed (").append(String.valueOf(nnfe)).append(")"); if (log.isDebugEnabled()) { log.debug(nnfe.getMessage(), nnfe); } } log.error("TICKET " + ticket + ":\n" + logMsg); } return to; }
/** * Format the given message to XML. * * @param record the log record to be formatted. * @return a formatted log record */ public String format(LogRecord record0) { if (!(record0 instanceof TopLinkLogRecord)) { return super.format(record0); } else { TopLinkLogRecord record = (TopLinkLogRecord) record0; StringBuffer sb = new StringBuffer(500); sb.append("<record>\n"); if (record.shouldPrintDate()) { sb.append(" <date>"); appendISO8601(sb, record.getMillis()); sb.append("</date>\n"); sb.append(" <millis>"); sb.append(record.getMillis()); sb.append("</millis>\n"); } sb.append(" <sequence>"); sb.append(record.getSequenceNumber()); sb.append("</sequence>\n"); String name = record.getLoggerName(); if (name != null) { sb.append(" <logger>"); escape(sb, name); sb.append("</logger>\n"); } sb.append(" <level>"); escape(sb, record.getLevel().toString()); sb.append("</level>\n"); if (record.getSourceClassName() != null) { sb.append(" <class>"); escape(sb, record.getSourceClassName()); sb.append("</class>\n"); } if (record.getSourceMethodName() != null) { sb.append(" <method>"); escape(sb, record.getSourceMethodName()); sb.append("</method>\n"); } if (record.getSessionString() != null) { sb.append(" <session>"); sb.append(record.getSessionString()); sb.append("</session>\n"); } if (record.getConnection() != null) { sb.append(" <connection>"); sb.append(String.valueOf(System.identityHashCode(record.getConnection()))); sb.append("</connection>\n"); } if (record.shouldPrintThread()) { sb.append(" <thread>"); sb.append(record.getThreadID()); sb.append("</thread>\n"); } if (record.getMessage() != null) { // Format the message string and its accompanying parameters. String message = formatMessage(record); sb.append(" <message>"); escape(sb, message); sb.append("</message>"); sb.append("\n"); } // If the message is being localized, output the key, resource // bundle name, and params. ResourceBundle bundle = record.getResourceBundle(); try { if ((bundle != null) && (bundle.getString(record.getMessage()) != null)) { sb.append(" <key>"); escape(sb, record.getMessage()); sb.append("</key>\n"); sb.append(" <catalog>"); escape(sb, record.getResourceBundleName()); sb.append("</catalog>\n"); Object[] parameters = record.getParameters(); for (int i = 0; i < parameters.length; i++) { sb.append(" <param>"); try { escape(sb, parameters[i].toString()); } catch (Exception ex) { sb.append("???"); } sb.append("</param>\n"); } } } catch (Exception ex) { // The message is not in the catalog. Drop through. } if (record.getThrown() != null) { // Report on the state of the throwable. Throwable th = record.getThrown(); sb.append(" <exception>\n"); sb.append(" <message>"); escape(sb, th.toString()); sb.append("</message>\n"); if ((record.getLevel().intValue() == Level.SEVERE.intValue()) || ((record.getLevel().intValue() <= Level.WARNING.intValue()) && record.shouldLogExceptionStackTrace())) { StackTraceElement[] trace = th.getStackTrace(); for (int i = 0; i < trace.length; i++) { StackTraceElement frame = trace[i]; sb.append(" <frame>\n"); sb.append(" <class>"); escape(sb, frame.getClassName()); sb.append("</class>\n"); sb.append(" <method>"); escape(sb, frame.getMethodName()); sb.append("</method>\n"); // Check for a line number. if (frame.getLineNumber() >= 0) { sb.append(" <line>"); sb.append(frame.getLineNumber()); sb.append("</line>\n"); } sb.append(" </frame>\n"); } } sb.append(" </exception>\n"); } sb.append("</record>\n"); return sb.toString(); } }