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 07. March 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.collections;
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 java.util.BitSet;
21: import java.util.StringTokenizer;
22:
23: /**
24: * Converts a java.util.BitSet to XML, as a compact
25: * comma delimited list of ones and zeros.
26: *
27: * @author Joe Walnes
28: */
29: public class BitSetConverter implements Converter {
30:
31: public boolean canConvert(Class type) {
32: return type.equals(BitSet.class);
33: }
34:
35: public void marshal(Object source, HierarchicalStreamWriter writer,
36: MarshallingContext context) {
37: BitSet bitSet = (BitSet) source;
38: StringBuffer buffer = new StringBuffer();
39: boolean seenFirst = false;
40: for (int i = 0; i < bitSet.length(); i++) {
41: if (bitSet.get(i)) {
42: if (seenFirst) {
43: buffer.append(',');
44: } else {
45: seenFirst = true;
46: }
47: buffer.append(i);
48: }
49: }
50: writer.setValue(buffer.toString());
51: }
52:
53: public Object unmarshal(HierarchicalStreamReader reader,
54: UnmarshallingContext context) {
55: BitSet result = new BitSet();
56: StringTokenizer tokenizer = new StringTokenizer(reader
57: .getValue(), ",", false);
58: while (tokenizer.hasMoreTokens()) {
59: int index = Integer.parseInt(tokenizer.nextToken());
60: result.set(index);
61: }
62: return result;
63: }
64: }
|