01: /*
02: * Created on Nov 17, 2005
03: */
04: package uk.org.ponder.conversion;
05:
06: import uk.org.ponder.saxalizer.SAXalXMLProvider;
07:
08: /**
09: * Converts objects to and from strings, using an XML format for composite objects,
10: * but a simple String rendering for leaf objects. In the latter case, type
11: * information must be maintained separately after serialization if you expect
12: * to be able to reconstruct the object.
13: * <p>
14: * This class is a slight kludge until we think of some sensible reform of the
15: * serialization morass. The point is we are really disinclined to construct XML
16: * parsers just to parse, for example, String objects. We also note that the
17: * SAXalizer/DeSAXalizer infrastructure is just not geared up for dealing with
18: * documents where the root node is actually a leaf.
19: * <p>
20: * Finally, we note that in every practical case we should be able to determine
21: * on delivery whether a given target property actually *IS* a leaf type or not,
22: * meaning armature such as <string>Yes it's a string</string>
23: * *ought* to be unnecessary.
24: * <p>
25: * This should all be solved once we move over to some sort of mature framework
26: * like JAXB 2.0 or JiBX.
27: *
28: * @author Antranig Basman (antranig@caret.cam.ac.uk)
29: *
30: */
31: public class ConvertUtil {
32: public static String render(Object torender,
33: SAXalXMLProvider xmlprovider) {
34: StaticLeafParser leafparser = xmlprovider.getMappingContext().saxleafparser;
35: if (leafparser.isLeafType(torender.getClass())) {
36: return leafparser.render(torender);
37: } else {
38: return xmlprovider.toString(torender);
39: }
40: }
41:
42: /** If the class argument is null, the string will be interpreted as XML.
43: */
44: public static Object parse(String toparse,
45: SAXalXMLProvider xmlprovider, Class targetclass) {
46: StaticLeafParser leafparser = xmlprovider.getMappingContext().saxleafparser;
47: if (targetclass != null && leafparser.isLeafType(targetclass)) {
48: return leafparser.parse(targetclass, toparse);
49: } else {
50: return xmlprovider.fromString(toparse);
51: }
52: }
53: }
|