View Javadoc

1   /**
2    * LOGBack: the reliable, fast and flexible logging library for Java.
3    * 
4    * Copyright (C) 1999-2005, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  package ch.qos.logback.core.helpers;
11  
12  import java.util.LinkedList;
13  import java.util.List;
14  
15  import ch.qos.logback.core.CoreConstants;
16  
17  public class ThrowableToStringArray {
18  
19    public static String[] convert(Throwable t) {
20      List<String> strList = new LinkedList<String>();
21      extract(strList, t, null);
22      return strList.toArray(new String[0]);
23  
24    }
25  
26    private static void extract(List<String> strList, Throwable t,
27        StackTraceElement[] parentSTE) {
28  
29      StackTraceElement[] ste = t.getStackTrace();
30      final int numberOfcommonFrames = findNumberOfCommonFrames(ste, parentSTE);
31  
32      strList.add(formatFirstLine(t, parentSTE));
33      for (int i = 0; i < (ste.length - numberOfcommonFrames); i++) {
34        strList.add("\tat "+ste[i].toString());
35      }
36  
37      if (numberOfcommonFrames != 0) {
38        strList.add("\t... "+numberOfcommonFrames + " common frames omitted");
39      }
40  
41      Throwable cause = t.getCause();
42      if (cause != null) {
43        ThrowableToStringArray.extract(strList, cause, ste);
44      }
45    }
46  
47    private static String formatFirstLine(Throwable t,
48        StackTraceElement[] parentSTE) {
49      String prefix = "";
50      if (parentSTE != null) {
51        prefix = CoreConstants.CAUSED_BY;
52      }
53  
54      String result = prefix + t.getClass().getName();
55      if (t.getMessage() != null) {
56        result += ": " + t.getMessage();
57      }
58      return result;
59    }
60  
61    private static int findNumberOfCommonFrames(StackTraceElement[] ste,
62        StackTraceElement[] parentSTE) {
63      if (parentSTE == null) {
64        return 0;
65      }
66  
67      int steIndex = ste.length - 1;
68      int parentIndex = parentSTE.length - 1;
69      int count = 0;
70      while (steIndex >= 0 && parentIndex >= 0) {
71        if (ste[steIndex].equals(parentSTE[parentIndex])) {
72          count++;
73        } else {
74          break;
75        }
76        steIndex--;
77        parentIndex--;
78      }
79      return count;
80    }
81  
82  }