1 package com.thoughtworks.xstream.converters.extended; 2 3 import com.thoughtworks.xstream.converters.ConversionException; 4 import com.thoughtworks.xstream.converters.Converter; 5 import com.thoughtworks.xstream.converters.MarshallingContext; 6 import com.thoughtworks.xstream.converters.UnmarshallingContext; 7 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 8 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 9 import sun.misc.BASE64Decoder; 10 import sun.misc.BASE64Encoder; 11 import sun.misc.CharacterDecoder; 12 import sun.misc.CharacterEncoder; 13 14 import java.io.IOException ; 15 16 29 public class EncodedByteArrayConverter implements Converter { 30 31 private CharacterEncoder encoder; 32 private CharacterDecoder decoder; 33 34 37 public EncodedByteArrayConverter() { 38 this.encoder = new BASE64Encoder(); 39 this.decoder = new BASE64Decoder(); 40 } 41 42 public EncodedByteArrayConverter(CharacterEncoder encoder, CharacterDecoder decoder) { 43 this.encoder = encoder; 44 this.decoder = decoder; 45 } 46 47 public boolean canConvert(Class type) { 48 return type.isArray() && type.getComponentType().equals(byte.class); 49 } 50 51 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { 52 byte[] data = (byte[]) source; 53 writer.setValue(encoder.encode(data)); 54 } 55 56 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { 57 try { 58 return decoder.decodeBuffer(reader.getValue()); 59 } catch (IOException e) { 60 throw new ConversionException("Cannot decode binary data", e); 61 } 62 } 63 64 } 65 | Popular Tags |