01: package prefuse.data.parser;
02:
03: import java.util.StringTokenizer;
04:
05: /**
06: * DataParser instance the parses an array of int values from a text string.
07: * Values are expected to be comma separated and can be within brackets,
08: * parentheses, or curly braces.
09: *
10: * @author <a href="http://jheer.org">jeffrey heer</a>
11: */
12: public class IntArrayParser implements DataParser {
13:
14: /**
15: * Returns int[].class.
16: * @see prefuse.data.parser.DataParser#getType()
17: */
18: public Class getType() {
19: return int[].class;
20: }
21:
22: /**
23: * @see prefuse.data.parser.DataParser#format(java.lang.Object)
24: */
25: public String format(Object value) {
26: if (value == null)
27: return null;
28: if (!(value instanceof int[]))
29: throw new IllegalArgumentException(
30: "This class can only format Objects of type int[].");
31:
32: int[] values = (int[]) value;
33: StringBuffer sbuf = new StringBuffer();
34: sbuf.append('[');
35: for (int i = 0; i < values.length; ++i) {
36: if (i > 0)
37: sbuf.append(", ");
38: sbuf.append(values[i]);
39: }
40: sbuf.append(']');
41: return sbuf.toString();
42: }
43:
44: /**
45: * @see prefuse.data.parser.DataParser#canParse(java.lang.String)
46: */
47: public boolean canParse(String text) {
48: try {
49: StringTokenizer st = new StringTokenizer(text, "\"[](){}, ");
50: while (st.hasMoreTokens()) {
51: Integer.parseInt(st.nextToken());
52: }
53: return true;
54: } catch (NumberFormatException e) {
55: return false;
56: }
57: }
58:
59: /**
60: * Parse an int array from a text string.
61: * @param text the text string to parse
62: * @return the parsed integer array
63: * @throws DataParseException if an error occurs during parsing
64: */
65: public Object parse(String text) throws DataParseException {
66: try {
67: StringTokenizer st = new StringTokenizer(text, "\"[](){}, ");
68: int[] array = new int[st.countTokens()];
69: for (int i = 0; st.hasMoreTokens(); ++i) {
70: String tok = st.nextToken();
71: array[i] = Integer.parseInt(tok);
72: }
73: return array;
74: } catch (NumberFormatException e) {
75: throw new DataParseException(e);
76: }
77: }
78:
79: } // end of class IntArrayParser
|