1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.onemind.commons.java.text;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 /***
26 * A simple implementation of generator
27 * @author TiongHiang Lee (thlee@onemindsoft.org)
28 */
29 public class SimpleTextGenerator implements TextGenerator
30 {
31
32 /*** the delimiter **/
33 private String _delimiter;
34
35 /*** sub delimiter **/
36 private String _subDelimiter;
37
38 /*** attr generators * */
39 private Map _generators = new HashMap();
40
41 /***
42 * Constructor
43 */
44 public SimpleTextGenerator(String delimiter, String subDelimiter)
45 {
46 _delimiter = delimiter;
47 _subDelimiter = subDelimiter;
48 }
49
50 /***
51 * add text generator to the sub specification
52 * @param subSpec the sub spec
53 * @param gen the sub generator
54 */
55 public void addGenerator(String subSpec, TextGenerator gen)
56 {
57 _generators.put(subSpec, gen);
58 }
59
60 /***
61 * {@inheritDoc}
62 */
63 public StringBuffer generateText(String spec, Object obj)
64 {
65 StringBuffer sb = new StringBuffer();
66 generateText(spec, obj, sb);
67 return sb;
68 }
69
70 /***
71 * {@inheritDoc}
72 */
73 public void generateText(String spec, Object obj, StringBuffer sb)
74 {
75 String[] fields = spec.split(_delimiter);
76 for (int i = 0; i < fields.length; i++)
77 {
78 if (_subDelimiter != null)
79 {
80 TextGenerator gen = getGenerator(fields[i]);
81 if (gen == null)
82 {
83 throw new IllegalArgumentException("No sub generator for " + fields[i]);
84 } else
85 {
86 gen.generateText(null, obj, sb);
87 }
88 } else
89 {
90 String specs[] = fields[i].split(_subDelimiter);
91 TextGenerator subGen = getGenerator(specs[0]);
92 if (subGen == null)
93 {
94 throw new IllegalArgumentException("No sub generator for " + specs[0]);
95 }
96 if (specs.length > 1)
97 {
98 subGen.generateText(specs[1], obj, sb);
99 } else
100 {
101 subGen.generateText(null, obj, sb);
102 }
103 }
104 }
105 }
106
107 /***
108 * Get the generator for subSpec
109 * @param subSpec the sub spec
110 * @return the generator for the sub spec
111 */
112 public TextGenerator getGenerator(String subSpec)
113 {
114 return (TextGenerator) _generators.get(subSpec);
115 }
116 }