01: /*
02: * Copyright (C) 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 08. July 2004 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.HierarchicalStreamReader;
18: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
19:
20: import javax.swing.plaf.FontUIResource;
21:
22: import java.awt.Font;
23: import java.util.Map;
24:
25: public class FontConverter implements Converter {
26:
27: public boolean canConvert(Class type) {
28: // String comparison is used here because Font.class loads the class which in turns instantiates AWT,
29: // which is nasty if you don't want it.
30: return type.getName().equals("java.awt.Font")
31: || type.getName().equals(
32: "javax.swing.plaf.FontUIResource");
33: }
34:
35: public void marshal(Object source, HierarchicalStreamWriter writer,
36: MarshallingContext context) {
37: Font font = (Font) source;
38: Map attributes = font.getAttributes();
39: writer.startNode("attributes"); // <attributes>
40: context.convertAnother(attributes);
41: writer.endNode(); // </attributes>
42: }
43:
44: public Object unmarshal(HierarchicalStreamReader reader,
45: UnmarshallingContext context) {
46: reader.moveDown(); // into <attributes>
47: Map attributes = (Map) context.convertAnother(null, Map.class);
48: reader.moveUp(); // out of </attributes>
49: Font font = Font.getFont(attributes);
50: if (context.getRequiredType() == FontUIResource.class) {
51: return new FontUIResource(font);
52: } else {
53: return font;
54: }
55: }
56: }
|