KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > collections > BitSetConverter


1 package com.thoughtworks.xstream.converters.collections;
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.util.BitSet JavaDoc;
10 import java.util.StringTokenizer JavaDoc;
11
12 /**
13  * Converts a java.util.BitSet to XML, as a compact
14  * comma delimited list of ones and zeros.
15  *
16  * @author Joe Walnes
17  */

18 public class BitSetConverter implements Converter {
19
20     public boolean canConvert(Class JavaDoc type) {
21         return type.equals(BitSet JavaDoc.class);
22     }
23
24     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
25         BitSet JavaDoc bitSet = (BitSet JavaDoc) source;
26         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
27         boolean seenFirst = false;
28         for (int i = 0; i < bitSet.length(); i++) {
29             if (bitSet.get(i)) {
30                 if (seenFirst) {
31                     buffer.append(',');
32                 } else {
33                     seenFirst = true;
34                 }
35                 buffer.append(i);
36             }
37         }
38         writer.setValue(buffer.toString());
39     }
40
41     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
42         BitSet JavaDoc result = new BitSet JavaDoc();
43         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(reader.getValue(), ",", false);
44         while (tokenizer.hasMoreTokens()) {
45             int index = Integer.parseInt(tokenizer.nextToken());
46             result.set(index);
47         }
48         return result;
49     }
50 }
51
Popular Tags