01: /*
02: * Copyright (C) 2004 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 29. May 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.extended;
13:
14: import com.thoughtworks.xstream.converters.Converter;
15: import com.thoughtworks.xstream.converters.MarshallingContext;
16: import com.thoughtworks.xstream.converters.UnmarshallingContext;
17: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
18: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
19:
20: /**
21: * Converter for Throwable (and Exception) that retains stack trace, for JDK1.4 only.
22: *
23: * @author <a href="mailto:boxley@thoughtworks.com">B. K. Oxley (binkley)</a>
24: * @author Joe Walnes
25: */
26: public class ThrowableConverter implements Converter {
27:
28: private Converter defaultConverter;
29:
30: public ThrowableConverter(Converter defaultConverter) {
31: this .defaultConverter = defaultConverter;
32: }
33:
34: public boolean canConvert(final Class type) {
35: return Throwable.class.isAssignableFrom(type);
36: }
37:
38: public void marshal(Object source, HierarchicalStreamWriter writer,
39: MarshallingContext context) {
40: Throwable throwable = (Throwable) source;
41: if (throwable.getCause() == null) {
42: try {
43: throwable.initCause(null);
44: } catch (IllegalStateException e) {
45: // ignore, initCause failed, cause was already set
46: }
47: }
48: throwable.getStackTrace(); // Force stackTrace field to be lazy loaded by special JVM native witchcraft (outside our control).
49: defaultConverter.marshal(throwable, writer, context);
50: }
51:
52: public Object unmarshal(HierarchicalStreamReader reader,
53: UnmarshallingContext context) {
54: return defaultConverter.unmarshal(reader, context);
55: }
56: }
|