/* * * Copyright (C) 2010 Guillaume Cottenceau and MNC S.A. * * This file is part of sdbl4j, and is licensed under the Apache 2.0 license. * */ package org.gc.sdbl4j; import javax.servlet.ServletException; /** * Generic utils. * * These generic utils are not tied to DB stuff. They should probably go into a separate JAR of utils but it is * so small that it probably doesn't deserve it. */ public class DBUtils { /** Go up the chain of exception causes, and print a nice trace of that all. */ public static String prettyPrint( Exception e ) { StringBuilder out = new StringBuilder(); String causePrefix = ""; Throwable t = e; while ( t != null ) { out.append( causePrefix ) .append( "exception: " ) .append( t ) .append( " at: " ); if ( t.getCause() == null ) { // no more cause, print full backtrace now because that's the most interesting exception out.append( "\n" ) .append( backtrace( t.getStackTrace() ) ) .append( "\n" ); } else { // there's a cause, print only one line of trace because that is not the most interesting exception out.append( t.getStackTrace()[ 0 ] ) .append( "\n" ); } t = t.getCause(); // grow the cause prefix causePrefix += "...cause: "; } if ( e instanceof ServletException ) { // in case of servlet exception, normally the root cause is an interesting exception Throwable rc = ( (ServletException) e ).getRootCause(); if ( rc != null ) { out.append( "rootCause: " ) .append( rc ) .append( " at:\n" ) .append( backtrace( rc.getStackTrace() ) ) .append( "\n" ); } } return out.toString(); } public static String backtrace( StackTraceElement[] trace ) { StringBuilder out = new StringBuilder(); for ( StackTraceElement ste : trace ) { out.append( "\t" ).append( ste ).append( "\n" ); } return out.toString(); } /** * Returns the backtrace corresponding to the StackTraceElement's passed. * This is useful to get the backtrace from a catch block. */ public static String backtrace( StackTraceElement[] trace, int from ) { StringBuilder sb = new StringBuilder(); for ( int i = 2; i < trace.length && trace[i].toString().startsWith( "org" ); i++ ) { sb.append( "\t" ).append( trace[ i ].toString() ).append( "\n" ); } return sb.toString(); } /** * Returns the backtrace of the caller method, skipping n levels. */ public static String backtrace( int skip ) { return backtrace( getStackTrace(), 2 + skip ); } public static StackTraceElement[] getStackTrace() { try { throw new Exception(); } catch ( Exception e ) { return e.getStackTrace(); } } public static String backtrace() { return backtrace( getStackTrace() ); } public static String join( String separator, Iterable elements ) { StringBuilder sb = null; for ( Object elem : elements ) { if ( sb == null ) { sb = new StringBuilder(); sb.append( elem.toString() ); } else { sb.append( separator ).append( elem.toString() ); } } return sb == null ? "" : sb.toString(); } }