01: /*
02: * Copyright (C) 2004 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 03. March 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.converters.basic.ByteConverter;
18: import com.thoughtworks.xstream.core.util.Base64Encoder;
19: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
20: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
21:
22: import java.util.ArrayList;
23: import java.util.Iterator;
24: import java.util.List;
25:
26: /**
27: * Converts a byte array to a single Base64 encoding string.
28: *
29: * @author Joe Walnes
30: */
31: public class EncodedByteArrayConverter implements Converter {
32:
33: private static final Base64Encoder base64 = new Base64Encoder();
34: private static final ByteConverter byteConverter = new ByteConverter();
35:
36: public boolean canConvert(Class type) {
37: return type.isArray()
38: && type.getComponentType().equals(byte.class);
39: }
40:
41: public void marshal(Object source, HierarchicalStreamWriter writer,
42: MarshallingContext context) {
43: writer.setValue(base64.encode((byte[]) source));
44: }
45:
46: public Object unmarshal(HierarchicalStreamReader reader,
47: UnmarshallingContext context) {
48: String data = reader.getValue(); // needs to be called before hasMoreChildren.
49: if (!reader.hasMoreChildren()) {
50: return base64.decode(data);
51: } else {
52: // backwards compatability ... try to unmarshal byte arrays that haven't been encoded
53: return unmarshalIndividualByteElements(reader, context);
54: }
55: }
56:
57: private Object unmarshalIndividualByteElements(
58: HierarchicalStreamReader reader,
59: UnmarshallingContext context) {
60: List bytes = new ArrayList(); // have to create a temporary list because don't know the size of the array
61: boolean firstIteration = true;
62: while (firstIteration || reader.hasMoreChildren()) { // hangover from previous hasMoreChildren
63: reader.moveDown();
64: //bytes.add(byteConverter.unmarshal(reader, context));
65: bytes.add(byteConverter.fromString(reader.getValue()));
66: reader.moveUp();
67: firstIteration = false;
68: }
69: // copy into real array
70: byte[] result = new byte[bytes.size()];
71: int i = 0;
72: for (Iterator iterator = bytes.iterator(); iterator.hasNext();) {
73: Byte b = (Byte) iterator.next();
74: result[i] = b.byteValue();
75: i++;
76: }
77: return result;
78: }
79:
80: }
|