1 33 34 package edu.rice.cs.drjava.config; 35 36 import java.util.Vector ; 37 import java.util.StringTokenizer ; 38 44 public class VectorOption<T> extends Option<Vector <T>> { 45 46 protected ParseStrategy<T> parser; 47 protected FormatStrategy<T> formatter; 48 public final String header; 49 public final char delim; 50 public final String footer; 51 52 57 private VectorOption(String key, ParseStrategy<T> parser, FormatStrategy<T> formatter, 58 String header, char delim, String footer, Vector <T> def) { 59 super(key,def); 60 this.parser = parser; 61 this.formatter = formatter; 62 this.header = header; 63 this.delim = delim; 64 this.footer = footer; 65 } 66 67 public VectorOption(String key, Option<T> strategy, String header, 68 char delim, String footer, Vector <T> def) { 69 this(key, strategy, strategy, header, delim, footer,def); 70 } 71 72 79 public VectorOption(String key, Option<T> option, Vector <T> def) { 80 this(key,option,option,"[",',',"]",def); 81 } 82 83 89 public Vector <T> parse(String s) { 90 s= s.trim(); 91 int startFirstElement = header.length(); 92 int startFooter = s.length() - footer.length(); 93 94 if (startFooter < startFirstElement || !s.startsWith(header) || ! s.endsWith(footer)) { 95 throw new OptionParseException(name, s, "Value must start with " + header + " and end " + "with " + footer + 96 " to be a valid vector."); 97 } 98 s = s.substring(startFirstElement, startFooter); 99 String d = String.valueOf(delim); 100 StringTokenizer st = new StringTokenizer (s,d,true); 101 102 Vector <T> res = new Vector <T>(); 103 boolean sawDelim = st.hasMoreTokens(); 104 105 while(st.hasMoreTokens()) { 106 String token = st.nextToken(); 107 boolean isDelim = token.equals(d); 108 109 if (!isDelim) { 110 res.add(parser.parse(token)); 111 } else if (sawDelim) { throw new OptionParseException(name, s, "Argument contains delimiter with no preceding list element."); 113 } 114 sawDelim = isDelim; 115 } 116 if (sawDelim) throw new OptionParseException(name, s, "Value shouldn't end with a delimiter."); 117 return res; 118 } 119 120 125 public String format(Vector <T> v) { 126 final StringBuilder res = new StringBuilder (header); 127 128 int size = v.size(); 129 int i = 0; 130 while (i < size) { 131 res.append(formatter.format(v.get(i))); 132 i++; 133 if (i < size) res.append(delim); 134 } 135 return res.append(footer).toString(); 136 } 137 } 138 139 | Popular Tags |