Java examples for java.lang:Exception StackTrace
Returns the stack traces of all current Threads or an empty String
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; public class Main{ public static void main(String[] argv) throws Exception{ System.out.println(getAllStackTraces()); }/*from w w w .j av a 2 s. c o m*/ /** * Constant for the java system properties. */ private static final Properties PROPS = System.getProperties(); /** * Returns the stack traces of all current Threads or an empty * String if LimeWire is running on Java 1.4 or if an error * occured. */ public static String getAllStackTraces() { if (!CommonUtils.isJava15OrLater()) { return ""; } try { Method m = Thread.class.getDeclaredMethod("getAllStackTraces", new Class[0]); Map map = (Map) m.invoke(null, new Object[0]); List sorted = new ArrayList(map.entrySet()); Collections.sort(sorted, new Comparator() { public int compare(Object a, Object b) { Thread threadA = (Thread) ((Map.Entry) a).getKey(); Thread threadB = (Thread) ((Map.Entry) b).getKey(); return threadA.getName().compareTo(threadB.getName()); } }); StringBuffer buffer = new StringBuffer(); Iterator it = sorted.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Thread key = (Thread) entry.getKey(); StackTraceElement[] value = (StackTraceElement[]) entry .getValue(); buffer.append(key.getName()).append("\n"); for (int i = 0; i < value.length; i++) { buffer.append(" ").append(value[i]).append("\n"); } buffer.append("\n"); } // Remove the last '\n' if (buffer.length() > 0) { buffer.setLength(buffer.length() - 1); } return buffer.toString(); } catch (Exception err) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("An error occured during getting the StackTraces of all active Threads"); err.printStackTrace(pw); pw.flush(); return sw.toString(); } } /** * Returns whether or not the current JVM is 1.5.x or later. */ public static boolean isJava15OrLater() { String version = CommonUtils.getJavaVersion(); return !version.startsWith("1.4") && !version.startsWith("1.3") && !version.startsWith("1.2") && !version.startsWith("1.1") && !version.startsWith("1.0"); } /** * Returns the version of java we're using. */ public static String getJavaVersion() { return PROPS.getProperty("java.version"); } }