KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > core > TreeUnmarshaller


1 package com.thoughtworks.xstream.core;
2
3 import com.thoughtworks.xstream.alias.ClassMapper;
4 import com.thoughtworks.xstream.converters.*;
5 import com.thoughtworks.xstream.core.util.ClassStack;
6 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
7
8 public class TreeUnmarshaller implements UnmarshallingContext {
9
10     private Object JavaDoc root;
11     protected HierarchicalStreamReader reader;
12     private ConverterLookup converterLookup;
13     private ClassMapper classMapper;
14     private String JavaDoc classAttributeIdentifier;
15     private ClassStack types = new ClassStack(16);
16
17     public TreeUnmarshaller(Object JavaDoc root, HierarchicalStreamReader reader,
18                             ConverterLookup converterLookup, ClassMapper classMapper,
19                             String JavaDoc classAttributeIdentifier) {
20         this.root = root;
21         this.reader = reader;
22         this.converterLookup = converterLookup;
23         this.classMapper = classMapper;
24         this.classAttributeIdentifier = classAttributeIdentifier;
25     }
26
27     public Object JavaDoc convertAnother(Object JavaDoc current, Class JavaDoc type) {
28         try {
29             Converter converter = converterLookup.lookupConverterForType(type);
30             types.push(type);
31             Object JavaDoc result = converter.unmarshal(reader, this);
32             types.popSilently();
33             return result;
34         } catch (ConversionException conversionException) {
35             addInformationTo(conversionException, type);
36             throw conversionException;
37         } catch (RuntimeException JavaDoc e) {
38             ConversionException conversionException = new ConversionException(e);
39             addInformationTo(conversionException, type);
40             throw conversionException;
41         }
42     }
43
44     private void addInformationTo(ErrorWriter errorWriter, Class JavaDoc type) {
45         errorWriter.add("class", type.getName());
46         errorWriter.add("required-type", getRequiredType().getName());
47         reader.appendErrors(errorWriter);
48     }
49
50     public Object JavaDoc currentObject() {
51         return root;
52     }
53
54     public Class JavaDoc getRequiredType() {
55         return types.peek();
56     }
57
58     public Object JavaDoc start() {
59         String JavaDoc classAttribute = reader.getAttribute(classAttributeIdentifier);
60         Class JavaDoc type;
61         if (classAttribute == null) {
62             type = classMapper.lookupType(reader.getNodeName());
63         } else {
64             type = classMapper.lookupType(classAttribute);
65         }
66         return convertAnother(root, type);
67     }
68
69 }
70
Popular Tags