KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > extended > ColorConverter


1 package com.thoughtworks.xstream.converters.extended;
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.awt.*;
10 import java.util.HashMap JavaDoc;
11 import java.util.Map JavaDoc;
12
13 /**
14  * Converts a java.awt.Color to XML, using four nested elements:
15  * red, green, blue, alpha.
16  *
17  * @author Joe Walnes
18  */

19 public class ColorConverter implements Converter {
20
21     public boolean canConvert(Class JavaDoc type) {
22         return type.equals(Color.class);
23     }
24
25     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
26         Color color = (Color) source;
27         write("red", color.getRed(), writer);
28         write("green", color.getGreen(), writer);
29         write("blue", color.getBlue(), writer);
30         write("alpha", color.getAlpha(), writer);
31     }
32
33     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
34         Map JavaDoc elements = new HashMap JavaDoc();
35         while (reader.hasMoreChildren()) {
36             reader.moveDown();
37             elements.put(reader.getNodeName(), Integer.valueOf(reader.getValue()));
38             reader.moveUp();
39         }
40         Color color = new Color(((Integer JavaDoc) elements.get("red")).intValue(),
41                 ((Integer JavaDoc) elements.get("green")).intValue(),
42                 ((Integer JavaDoc) elements.get("blue")).intValue(),
43                 ((Integer JavaDoc) elements.get("alpha")).intValue());
44         return color;
45     }
46
47     private void write(String JavaDoc fieldName, int value, HierarchicalStreamWriter writer) {
48         writer.startNode(fieldName);
49         writer.setValue(String.valueOf(value));
50         writer.endNode();
51     }
52
53 }
54
Popular Tags