KickJava   Java API By Example, From Geeks To Geeks.

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


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 JavaDoc;
15
16 /**
17  * Converts a byte array to a single encoding string (such as base64).
18  * Because this uses Sun specific classes it is not registered in XStream by default.
19  * <p/>
20  * The following CharacterEncoder/CharacterDecoders pairs are available.
21  * <ul>
22  * <li> sun.misc.BASE64Encoder, sun.mis.BASE64Decoder (default) </li>
23  * <li> sun.misc.UCEncoder, sun.misc.UCDecoder </li>
24  * <li> sun.misc.UUEncoder, sun.misc.UUDecoder </li>
25  * </ul>
26  *
27  * @author Joe Walnes
28  */

29 public class EncodedByteArrayConverter implements Converter {
30
31     private CharacterEncoder encoder;
32     private CharacterDecoder decoder;
33
34     /**
35      * Default converter uses BASE64 encoding.
36      */

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 JavaDoc type) {
48         return type.isArray() && type.getComponentType().equals(byte.class);
49     }
50
51     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
52         byte[] data = (byte[]) source;
53         writer.setValue(encoder.encode(data));
54     }
55
56     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
57         try {
58             return decoder.decodeBuffer(reader.getValue());
59         } catch (IOException JavaDoc e) {
60             throw new ConversionException("Cannot decode binary data", e);
61         }
62     }
63
64 }
65
Popular Tags