KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.thoughtworks.xstream.core;
2
3 import com.thoughtworks.xstream.alias.ClassMapper;
4 import com.thoughtworks.xstream.converters.Converter;
5 import com.thoughtworks.xstream.converters.ConverterLookup;
6 import com.thoughtworks.xstream.converters.MarshallingContext;
7 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
8
9 import java.util.Collection JavaDoc;
10 import java.util.HashSet JavaDoc;
11
12 public class TreeMarshaller implements MarshallingContext {
13
14     protected HierarchicalStreamWriter writer;
15     protected ConverterLookup converterLookup;
16     protected ClassMapper classMapper;
17     private Collection JavaDoc parentObjects = new HashSet JavaDoc();
18
19     public TreeMarshaller(HierarchicalStreamWriter writer, ConverterLookup converterLookup,
20                                      ClassMapper classMapper) {
21         this.writer = writer;
22         this.converterLookup = converterLookup;
23         this.classMapper = classMapper;
24     }
25
26     public void convertAnother(Object JavaDoc item) {
27         Integer JavaDoc id = new Integer JavaDoc(System.identityHashCode(item));
28         if (parentObjects.contains(id)) {
29             throw new CircularReferenceException();
30         }
31         parentObjects.add(id);
32         Converter converter = converterLookup.lookupConverterForType(item.getClass());
33         converter.marshal(item, writer, this);
34         parentObjects.remove(id);
35     }
36
37     public void start(Object JavaDoc item) {
38         if (item == null) {
39             writer.startNode(classMapper.lookupName(ClassMapper.Null.class));
40             writer.endNode();
41         } else {
42             writer.startNode(classMapper.lookupName(item.getClass()));
43             convertAnother(item);
44             writer.endNode();
45         }
46     }
47
48     public class CircularReferenceException extends RuntimeException JavaDoc {
49     }
50
51 }
52
Popular Tags