01: /*
02: * Copyright (C) 2003, 2004, 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 01. October 2003 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.extended;
13:
14: import com.thoughtworks.xstream.converters.Converter;
15: import com.thoughtworks.xstream.converters.MarshallingContext;
16: import com.thoughtworks.xstream.converters.UnmarshallingContext;
17: import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
18: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
19: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
20:
21: import java.awt.Color;
22: import java.util.HashMap;
23: import java.util.Map;
24:
25: /**
26: * Converts a java.awt.Color to XML, using four nested elements:
27: * red, green, blue, alpha.
28: *
29: * @author Joe Walnes
30: */
31: public class ColorConverter implements Converter {
32:
33: public boolean canConvert(Class type) {
34: // String comparison is used here because Color.class loads the class which in turns instantiates AWT,
35: // which is nasty if you don't want it.
36: return type.getName().equals("java.awt.Color");
37: }
38:
39: public void marshal(Object source, HierarchicalStreamWriter writer,
40: MarshallingContext context) {
41: Color color = (Color) source;
42: write("red", color.getRed(), writer);
43: write("green", color.getGreen(), writer);
44: write("blue", color.getBlue(), writer);
45: write("alpha", color.getAlpha(), writer);
46: }
47:
48: public Object unmarshal(HierarchicalStreamReader reader,
49: UnmarshallingContext context) {
50: Map elements = new HashMap();
51: while (reader.hasMoreChildren()) {
52: reader.moveDown();
53: elements.put(reader.getNodeName(), Integer.valueOf(reader
54: .getValue()));
55: reader.moveUp();
56: }
57: return new Color(((Integer) elements.get("red")).intValue(),
58: ((Integer) elements.get("green")).intValue(),
59: ((Integer) elements.get("blue")).intValue(),
60: ((Integer) elements.get("alpha")).intValue());
61: }
62:
63: private void write(String fieldName, int value,
64: HierarchicalStreamWriter writer) {
65: ExtendedHierarchicalStreamWriterHelper.startNode(writer,
66: fieldName, int.class);
67: writer.setValue(String.valueOf(value));
68: writer.endNode();
69: }
70:
71: }
|