KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > extended > StackTraceElementConverter


1 package com.thoughtworks.xstream.converters.extended;
2
3 import com.thoughtworks.xstream.converters.MarshallingContext;
4 import com.thoughtworks.xstream.converters.ConversionException;
5 import com.thoughtworks.xstream.converters.basic.AbstractBasicConverter;
6 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
7
8 import java.lang.reflect.Field JavaDoc;
9 import java.util.regex.Matcher JavaDoc;
10 import java.util.regex.Pattern JavaDoc;
11
12 /**
13  * Converter for StackTraceElement (the lines of a stack trace) - JDK 1.4+ only.
14  *
15  * @author <a HREF="mailto:boxley@thoughtworks.com">B. K. Oxley (binkley)</a>
16  * @author Joe Walnes
17  */

18 public class StackTraceElementConverter extends AbstractBasicConverter {
19
20     // Regular expression to parse a line of a stack trace. Returns 4 groups.
21
//
22
// Example: com.blah.MyClass.doStuff(MyClass.java:123)
23
// |-------1------| |--2--| |----3-----| |4|
24
// (Note group 4 is optional is optional and only present if a colon char exists.)
25

26     private static final Pattern JavaDoc PATTERN = Pattern.compile("^(.+)\\.([^\\(]+)\\(([^:]*)(:(\\d+))?\\)$");
27
28     private final StackTraceElementFactory factory = new StackTraceElementFactory();
29
30     public boolean canConvert(Class JavaDoc type) {
31         return StackTraceElement JavaDoc.class.equals(type);
32     }
33
34     protected Object JavaDoc fromString(String JavaDoc str) {
35         Matcher JavaDoc matcher = PATTERN.matcher(str);
36         if (matcher.matches()) {
37             String JavaDoc declaringClass = matcher.group(1);
38             String JavaDoc methodName = matcher.group(2);
39             String JavaDoc fileName = matcher.group(3);
40             if (fileName.equals("Unknown Source")) {
41                 return factory.unknownSourceElement(declaringClass, methodName);
42             } else if (fileName.equals("Native Method")) {
43                 return factory.nativeMethodElement(declaringClass, methodName);
44             } else {
45                 if (matcher.group(4) != null) {
46                     int lineNumber = Integer.parseInt(matcher.group(5));
47                     return factory.element(declaringClass, methodName, fileName, lineNumber);
48                 } else {
49                     return factory.element(declaringClass, methodName, fileName);
50                 }
51             }
52         } else {
53             throw new ConversionException("Could not parse StackTraceElement : " + str);
54         }
55     }
56
57 }
58
Popular Tags