1 package net.sf.tomp.xtcl.command;
2
3 import net.sf.tomp.xtcl.Command;
4 import net.sf.tomp.xtcl.Compiler;
5 import net.sf.tomp.xtcl.Context;
6
7 import org.apache.commons.logging.Log;
8 import org.apache.commons.logging.LogFactory;
9
10 import java.util.HashMap;
11 import java.util.Map;
12 import java.util.regex.Matcher;
13 import java.util.regex.Pattern;
14
15 /***
16 * DOCUMENT ME!
17 *
18 * @author tomp
19 */
20 public class Do extends AbstractCommand {
21 private Log log = LogFactory.getLog(Do.class);
22
23 /*** Template name */
24 private String templateName;
25
26 /*** Template name-parameter assignments */
27 private Map params = new HashMap();
28
29 private Pattern varPattern = Pattern.compile("//%([^//%]*)//%");
30
31 /***
32 * @return Returns the name.
33 */
34 public String getTemplateName() {
35 return templateName;
36 }
37
38 /***
39 * DOCUMENT ME!
40 *
41 * @param context DOCUMENT ME!
42 * @return DOCUMENT ME!
43 * @throws Exception DOCUMENT ME!
44 */
45 public int execute(Context context) throws Exception {
46 Compiler compiler = context.getCompiler();
47 Template template = (Template) context.get(templateName);
48 String body = template.getBody();
49 String substituted = substitute(body);
50
51
52 Command c = compiler.compile(substituted);
53
54 return done(context, context.execute(c));
55
56
57 }
58
59 protected String substitute(String body) {
60 Matcher m = varPattern.matcher(body);
61 StringBuffer replaced = new StringBuffer();
62
63 while (m.find()) {
64 String paramName = m.group(1);
65
66
67 String paramValue = (String) params.get(paramName);
68
69
70 if (paramValue != null) {
71 paramValue = paramValue.replaceAll("//$", "//////$");
72
73
74 m.appendReplacement(replaced, paramValue);
75 }
76 }
77
78 m.appendTail(replaced);
79
80 return replaced.toString();
81 }
82
83 /***
84 * Sets the (formal, real) parameter pair
85 *
86 * @param k Parameter name (key) - formal param. name
87 * @param v Parameter value - real param. name
88 */
89 public void setParameter(String k, Object v) {
90 params.put(k, v);
91
92
93 }
94
95 /***
96 * DOCUMENT ME!
97 *
98 * @param p DOCUMENT ME!
99 */
100 public void setTemplateName(String p) {
101 templateName = p;
102 }
103
104 /***
105 * DOCUMENT ME!
106 *
107 * @return DOCUMENT ME!
108 */
109 public String toString() {
110 return "DO-TEMPLATE " + templateName + " {" + listMap(params) + "}";
111 }
112 }
113
114
115
116
117
118
119
120
121
122
123