3 import java.io.BufferedReader;
4 import java.io.FileInputStream;
5 import java.io.InputStreamReader;
7 import java.io.StringReader;
8 import java.io.StringWriter;
10 import java.io.IOException;
11 import java.io.FileNotFoundException;
14 import org.ibex.util.*;
17 public class Template extends JSLeaf.Element {
18 public static Template parse(String path, Template.Scope s) throws FileNotFoundException, IOException {
19 Reader xmlreader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
20 XML.Document doc = new XML.Document(); // FIXME: switch to Tree.Stream
22 return new Template(doc.getRoot(), s);
25 public static Tree.Leaf wrap(Tree.Leaf leaf, Template.Scope s) throws IOException {
26 if (!(leaf instanceof Tree.Element)) return new Text(leaf);
28 Tree.Element e = (Tree.Element)leaf;
29 final String uri = e.getUri();
33 } else if (uri.equals("http://xt.ibex.org/")) {
34 //#switch(e.getLocalName())
35 case "js": e = new Template.JSTag(e); break;
36 case "foreach": e = new Template.ForEach(e); break;
37 case "children": e = new Template.Children(e); break;
38 case "redirect": e = new Template.Redirect(e); break;
39 case "transaction": e = new Template.Transaction(e, s); break;
42 } else if (uri.startsWith("http://xt.ibex.org/")) {
43 throw new JSLeaf.Exn("Unknown XT library: "+uri);
45 } else if (uri.startsWith("local:")) {
46 // merge a new template into this tree
47 String path = uri.substring(6) + e.getLocalName() + ".xt";
48 Template t = parse(s.getLocalPath() + path, s);
50 List c = e.getChildren();
52 // move all children from e to placeholder
53 Tree.Element placeholder = findPlaceholder(t);
54 if (placeholder == null) throw new JSLeaf.Exn(
55 "<"+e.getQName()+"> attempted to include children into a " +
56 "template which does not contain an <xt:children /> tag.");
58 placeholder.getChildren().addAll(e.getChildren());
59 e.getChildren().clear();
62 // merge the attributes of the template and its representative
63 t.setAttributes(new JSLeaf.MergeAttr(e.getAttributes(), t.getAttributes()));
65 // remap the parent of the original element
66 if (e.getParent() != null) {
67 List ch = e.getParent().getChildren();
68 ch.set(ch.indexOf(e), t);
74 e = new Template.AttributeEval(e);
77 List c = e.getChildren();
78 for (int i=0; i < c.size(); i++) wrap((Tree.Leaf)c.get(i), s);
83 /** Returns the first Template.Children child found. */
84 private static Tree.Element findPlaceholder(Tree.Element e) {
85 if ("http://xt.ibex.org/".equals(e.getUri()) && "children".equals(e.getLocalName()))
88 List c = e.getChildren();
89 for (int i=0; i < c.size(); i++) {
90 if (!(c.get(i) instanceof Tree.Element)) continue;
91 Tree.Element ret = findPlaceholder((Tree.Element)c.get(i));
92 if (ret != null) return ret;
97 private transient Template.Scope tscope;
98 private transient JSScope scope = null;
100 public Template(Tree.Element w, Template.Scope t) { super(w); tscope = t; }
102 public JSScope scope() { return scope == null ? scope = new JSScope(tscope) : scope; }
105 /** Processes ${...} blocks in attributes, loads applicable
106 * attributes into the JS scope and processes global attributes. */
107 public static class AttributeEval extends JSLeaf.Element implements Tree.Attributes {
108 // TODO: hide global attributes from out() function. waiting on util.XMLHelper
109 protected Tree.Attributes a;
111 public AttributeEval(Tree.Element wrapped) {
113 a = wrapped.getAttributes();
114 wrapped.setAttributes(this);
117 public int getIndex(String q) { return a.getIndex(q); }
118 public int getIndex(String u, String k) { return a.getIndex(u, k); }
119 public String getKey(int i) { return a.getKey(i); }
120 public String getVal(int i) { return (String)eval(a.getVal(i)); }
121 public String getUri(int i) { return a.getUri(i); }
122 public String getPrefix(int i) { return a.getPrefix(i); }
123 public String getQName(int i) { return a.getQName(i); }
124 public int attrSize() { return a.attrSize(); }
126 public void out(Writer w) throws IOException {
128 // FIXME: questionable abuse of namespaces here
129 boolean xturi = "http://xt.ibex.org/".equals(getUri());
130 for(int i=0; i < a.attrSize(); i++) {
131 if (!xturi && !"http://xt.ibex.org/".equals(a.getUri(i))) continue;
133 //#switch (a.getKey(i))
134 case "if": if (!"true".equals(eval(a.getVal(i)))) return;
136 Object d = eval(a.getVal(i));
137 if (!(d instanceof String)) throw new JSLeaf.Exn(
138 "attribute '"+getPrefix()+":declare' can only contain a "+
139 "space seperated list of variable names to declare.");
140 StringTokenizer st = new StringTokenizer((String)d, " ");
141 while (st.hasMoreTokens()) scope().declare(st.nextToken());
145 scope().declare(a.getKey(i));
146 scope().put(a.getKey(i), eval(a.getVal(i)));
148 } catch (JSExn e) { throw new Exn(e); }
154 public static final class JSTag extends JSLeaf.Element {
155 public JSTag(Tree.Element e) {
157 List c = getChildren();
158 for (int i=0; i < c.size(); i++)
159 if (c.get(i) instanceof Tree.Element) throw new JSLeaf.Exn(
160 "<"+getPrefix()+":js> tags may not have child elements");
163 public void out(Writer w) throws IOException {
164 List c = getChildren();
165 StringWriter s = new StringWriter();
166 for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(s);
171 public static final class ForEach extends JSLeaf.Element {
172 public ForEach(Tree.Element e) { super(e); }
174 public void out(Writer w) throws IOException {
177 Object varIn = s.get("in"); if (varIn != null) s.undeclare("in");
178 Object varPut = s.get("put"); if (varPut != null) s.undeclare("put");
180 varIn = exec("return (" + varIn + ");");
181 if (varIn == null || (varIn instanceof JSArray)) throw new JSLeaf.Exn(
182 "<"+getPrefix()+":foreach> requires attribute 'in' to specify " +
183 "the name of a valid js array in the current scope, not in='"+varIn+"'.");
185 if (varPut == null) varPut = "x";
186 else if (!(varPut instanceof String) || s.get(varPut) != null)
187 throw new JSLeaf.Exn(
188 "<"+getPrefix()+":foreach> 'put' attribute requires the name of "+
189 "an undeclared variable, not put='"+varPut+"'.");
190 if (scope().get(varPut) != null) throw new JSLeaf.Exn(
191 "<"+getPrefix()+":foreach> has no 'put' attribute defined and the "+
192 "default variable 'x' already exists in the current scope.");
194 List c = getChildren();
196 s.declare((String)varPut);
197 Iterator it = ((JSArray)varIn).toList().iterator(); while (it.hasNext()) {
198 s.put(varPut, it.next());
199 for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(w);
201 } catch (JSExn e) { throw new JSLeaf.Exn(e); }
205 public static final class Children extends JSLeaf.Element {
206 public Children(Tree.Element e) { super(e); }
209 public static final class Redirect extends JSLeaf.Element {
210 public Redirect(Tree.Element e) { super(e); }
212 public void out(Writer w) throws IOException {
214 Object p = scope().get("page"); if (p != null) scope().undeclare("page");
215 if (p == null || !(p instanceof String) || ((String)p).trim().equals(""))
216 throw new JSLeaf.Exn("<"+getPrefix()+":redirect> requires 'page' "+
217 "attribute to be a valid template path");
218 throw new RedirectSignal((String)p);
219 } catch (JSExn e) { throw new JSLeaf.Exn(e); }
224 public static final class Transaction extends JSLeaf.Element {
225 private final Template.Scope scope; // FIXME: HACK. unstatisise all tags, or do this to all
226 public Transaction(Tree.Element e, Template.Scope s) { super(e); scope = s;} // TODO: check kids
228 public void out(Writer w) throws IOException {
230 List c = getChildren();
231 StringWriter sw = new StringWriter();
232 for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(sw);
233 JS t = JS.fromReader("input", 0, new StringReader(sw.toString()));
234 t = JS.cloneWithNewParentScope(t, new JSScope(null));
235 scope.transaction(t);
239 public static final class Text extends JSLeaf {
240 public Text(Tree.Leaf w) { super(w); }
241 public void out(Writer w) throws IOException {
242 // FIXME: make eval() take a writer
243 StringWriter sw = new StringWriter();
245 w.write((String)eval(sw.toString()));
249 public abstract static class Scope extends JSScope {
250 public Scope(JSScope j) { super(j); }
252 /** Returns the template path for local:/ namespace. */
253 public abstract String getLocalPath();
255 /** Registers a new Prevayler transaction. */
256 public abstract void transaction(JS t);
259 public static class Signal extends RuntimeException {}
260 public static class ReturnSignal extends Signal { }
261 public static class RedirectSignal extends Signal {
262 protected String target;
263 public RedirectSignal(String target) { super(); this.target = target; }
264 public String getTarget() { return target; }