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 ; 11 import java.util.Map ; 12 13 19 public class ColorConverter implements Converter { 20 21 public boolean canConvert(Class type) { 22 return type.equals(Color.class); 23 } 24 25 public void marshal(Object 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 unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { 34 Map elements = new HashMap (); 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 ) elements.get("red")).intValue(), 41 ((Integer ) elements.get("green")).intValue(), 42 ((Integer ) elements.get("blue")).intValue(), 43 ((Integer ) elements.get("alpha")).intValue()); 44 return color; 45 } 46 47 private void write(String fieldName, int value, HierarchicalStreamWriter writer) { 48 writer.startNode(fieldName); 49 writer.setValue(String.valueOf(value)); 50 writer.endNode(); 51 } 52 53 } 54 | Popular Tags |