1
2
3
4
5
6
7
8
9
10
11 package de.jaret.util.ui.datechooser;
12
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.StringTokenizer;
16
17 /***
18 * Simple implementation of the FieldIdentifier interface for the jaret datechooser.
19 *
20 * @author Peter Kliem
21 * @version $Id: SimpleFieldIdentifier.java 498 2007-06-18 22:14:29Z olk $
22 */
23 public class SimpleFieldIdentifier implements IFieldIdentifier {
24 /*** default separators. */
25 protected String _separators = "/.";
26
27 /*** field mapping. */
28 protected int[] _fields;
29
30 /***
31 * Construct a new instance. To identfy fields in a date like "dd.mm.yyyy" you would use it like that:
32 * <pre>
33 * FieldIdentifier fi = new SimpleFieldIdentifier(".", new int[] {Calendar.DAY_OF_MONTH, Calendar.MONTH, Calendar.YEAR});
34 * </pre>
35 *
36 * @param separators characters used as field seperators. Default is "./" (used if the argument is <code>null</code>.
37 * @param fields array of field identifying int values. Parsing will only be succesful if the number of fields is matched exactly.
38 */
39 public SimpleFieldIdentifier(String separators, int[] fields) {
40 if (separators != null) {
41 _separators = separators;
42 }
43 _fields = fields;
44 }
45
46 /***
47 * See {@link #SimpleFieldIdentifier(String, int[])}.
48 * Default separators will be used.
49 *
50 * @param fields field mappings
51 */
52 public SimpleFieldIdentifier(int[] fields) {
53 this(null, fields);
54 }
55
56 /***
57 * {@inheritDoc}
58 */
59 public int getField(String dateString, int pos) {
60 List<String> fields = new ArrayList<String>(5);
61 StringTokenizer tokenizer = new StringTokenizer(dateString, _separators);
62 while (tokenizer.hasMoreTokens()) {
63 fields.add(tokenizer.nextToken());
64 }
65 if (fields.size() != _fields.length) {
66 return -1;
67 }
68 int p = 0;
69 int idx = 0;
70 for (String field : fields) {
71 p += field.length();
72 if (p >= pos) {
73 return _fields[idx];
74 }
75 p++;
76 idx++;
77 }
78
79 return -1;
80 }
81
82 }