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 root; 11 protected HierarchicalStreamReader reader; 12 private ConverterLookup converterLookup; 13 private ClassMapper classMapper; 14 private String classAttributeIdentifier; 15 private ClassStack types = new ClassStack(16); 16 17 public TreeUnmarshaller(Object root, HierarchicalStreamReader reader, 18 ConverterLookup converterLookup, ClassMapper classMapper, 19 String 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 convertAnother(Object current, Class type) { 28 try { 29 Converter converter = converterLookup.lookupConverterForType(type); 30 types.push(type); 31 Object 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 e) { 38 ConversionException conversionException = new ConversionException(e); 39 addInformationTo(conversionException, type); 40 throw conversionException; 41 } 42 } 43 44 private void addInformationTo(ErrorWriter errorWriter, Class type) { 45 errorWriter.add("class", type.getName()); 46 errorWriter.add("required-type", getRequiredType().getName()); 47 reader.appendErrors(errorWriter); 48 } 49 50 public Object currentObject() { 51 return root; 52 } 53 54 public Class getRequiredType() { 55 return types.peek(); 56 } 57 58 public Object start() { 59 String classAttribute = reader.getAttribute(classAttributeIdentifier); 60 Class 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 |