1 package net.sourceforge.jparam.parser;
2
3 import java.util.ArrayList;
4 import java.util.Iterator;
5 import java.util.LinkedList;
6 import java.util.List;
7 import java.util.StringTokenizer;
8
9 import net.sourceforge.jparam.JParamException;
10 import net.sourceforge.jparam.conversion.ConverterRegistry;
11 import net.sourceforge.jparam.conversion.weights.ScalarConversionWeight;
12
13 /***
14 * A description of class CompositeTreeNode
15 */
16 public class VectorLeaf implements TreeNode {
17 private List elements;
18
19 public final static int LIST = 0;
20
21 public final static int VECTOR = 1;
22
23 /***
24 * Create a new Vector object, with the given TreeNodes as items
25 */
26 public VectorLeaf(List elements, int vectorType) {
27 this.elements = elements;
28 if (vectorType != LIST && vectorType != VECTOR) {
29 throw new IllegalArgumentException(
30 "Vector type must be either LIST or VECTOR, invalid type: "
31 + vectorType);
32 }
33 }
34
35 public Object getConstructedValue(Class expectedType)
36 throws JParamException {
37 List vector;
38 if (expectedType.equals(ArrayList.class)) {
39 vector = new ArrayList(elements.size());
40 } else {
41 vector = new LinkedList();
42 }
43
44 Iterator itr = elements.iterator();
45 while (itr.hasNext()) {
46 vector.add(((TreeNode) itr.next())
47 .getConstructedValue(Object.class));
48 }
49 return vector;
50 }
51
52 public String toString() {
53 StringBuffer res = new StringBuffer("VectorLeaf, items=[");
54 boolean isFirst = true;
55 Iterator itr = elements.iterator();
56 while (itr.hasNext()) {
57 if (isFirst) {
58 isFirst = false;
59 } else {
60 res.append(" ,");
61 }
62 res.append(itr.next().toString());
63 }
64 res.append(']');
65 return res.toString();
66 }
67
68 public static VectorLeaf fromShellStrings(String shellString) {
69 StringTokenizer st = new StringTokenizer(shellString, String
70 .valueOf((char) 1));
71
72 List args = new LinkedList();
73
74
75 while (st.hasMoreTokens()) {
76 args.add(new SimpleLeaf(st.nextToken(), SimpleLeaf.DECODED_STRING));
77 }
78
79 return new VectorLeaf(args, VECTOR);
80 }
81
82 public ScalarConversionWeight getConversionWeight(Class expectedClass) {
83 if ((expectedClass.equals(ArrayList.class))
84 || (expectedClass.equals(LinkedList.class))) {
85 return ScalarConversionWeight.CONV_EXACT;
86 }
87
88 return ConverterRegistry.getInstance().getConversionWeight(
89 LinkedList.class, expectedClass);
90 }
91 }