KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > collections > PropertiesConverter


1 package com.thoughtworks.xstream.converters.collections;
2
3 import com.thoughtworks.xstream.converters.Converter;
4 import com.thoughtworks.xstream.converters.MarshallingContext;
5 import com.thoughtworks.xstream.converters.UnmarshallingContext;
6 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
7 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
8
9 import java.util.Iterator JavaDoc;
10 import java.util.Map JavaDoc;
11 import java.util.Properties JavaDoc;
12
13 /**
14  * Special converter for java.util.Properties that stores
15  * properties in a more compact form than java.util.Map.
16  * <p/>
17  * <p>Because all entries of a Properties instance
18  * are Strings, a single element is used for each property
19  * with two attributes; one for key and one for value.</p>
20  *
21  * @author Joe Walnes
22  */

23 public class PropertiesConverter implements Converter {
24
25     public boolean canConvert(Class JavaDoc type) {
26         return Properties JavaDoc.class.isAssignableFrom(type);
27     }
28
29     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
30         Properties JavaDoc properties = (Properties JavaDoc) source;
31         for (Iterator JavaDoc iterator = properties.entrySet().iterator(); iterator.hasNext();) {
32             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
33             writer.startNode("property");
34             writer.addAttribute("name", entry.getKey().toString());
35             writer.addAttribute("value", entry.getValue().toString());
36             writer.endNode();
37         }
38     }
39
40     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
41         Properties JavaDoc properties = new Properties JavaDoc();
42         while (reader.hasMoreChildren()) {
43             reader.moveDown();
44             String JavaDoc name = reader.getAttribute("name");
45             String JavaDoc value = reader.getAttribute("value");
46             ;
47             properties.setProperty(name, value);
48             reader.moveUp();
49         }
50         return properties;
51     }
52 }
53
Popular Tags