add redirect tag support
[org.ibex.xt-crawshaw.git] / src / java / org / ibex / xt / Template.java
1 package org.ibex.xt;
2
3 import java.io.BufferedReader;
4 import java.io.FileInputStream;
5 import java.io.InputStreamReader;
6 import java.io.Reader;
7 import java.io.StringReader;
8 import java.io.StringWriter;
9 import java.io.Writer;
10 import java.io.IOException;
11 import java.io.FileNotFoundException;
12
13 import java.util.*;
14 import org.ibex.util.*;
15 import org.ibex.js.*;
16
17 public class Template extends JSElement {
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();
21         doc.parse(xmlreader);
22         return new Template(doc.getRoot(), s);
23     }
24
25     public static XML.Element wrap(XML.Element e, Template.Scope s) throws IOException {
26         final String uri = e.getUri();
27
28         if (uri.equals("http://xt.ibex.org/")) {
29             //#switch(e.getLocalName())
30             case "js":          e = new Template.JSTag(e); break;
31             case "foreach":     e = new Template.ForEach(e); break;
32             case "children":    e = new Template.Children(e); break;
33             case "redirect":    e = new Template.Redirect(e); break;
34             case "transaction": e = new Template.Transaction(e, s); break;
35             //#end
36
37         } else if (uri.startsWith("http://xt.ibex.org/")) {
38             //#switch(uri.substring(19))
39             case "io": System.out.println("ibex.xt.io not yet implemented"); // TODO
40             //#end
41             //throw new JSElement.Exn("Unknown XT library: "+uri);
42
43         } else if (uri.startsWith("local:")) {
44             Template t = parse(s.getLocalPath() + uri.substring(6), s);
45
46             List c = e.getChildren();
47             if (c.size() > 0) {
48                 // move all children from e to placeholder
49                 XML.Element placeholder = findPlaceholder(t);
50                 if (placeholder == null) throw new JSElement.Exn(
51                     "<"+e.getQName()+"> attempted to include children into a " +
52                     "template which does not contain an <xt:children /> tag.");
53
54                 placeholder.getChildren().addAll(e.getChildren());
55                 e.getChildren().clear();
56             }
57
58             // merge original attributes with replacement template
59             e = new JSElement.Merge(t, e);
60         }
61
62         XML.Attributes a = e.getAttributes();
63         for (int i=0; i < a.attrSize(); i++) {
64             // FIXME: questionable abuse of XML namespaces here
65             if ("if".equals(a.getKey(i)) && (
66                 "http://xt.ibex.org/".equals(e.getUri()) ||
67                 "http://xt.ibex.org/".equals(a.getUri(i)))) {
68                 e = new Template.IfWrap(e);
69             }
70         }
71
72         // wrap children
73         List c = e.getChildren();
74         for (int i=0; i < c.size(); i++)
75             if (c.get(i) instanceof XML.Element) wrap((XML.Element)c.get(i), s);
76
77         return e;
78     }
79
80     /** Returns the first Template.Children child found. */
81     private static Template.Children findPlaceholder(XML.Element e) {
82         if (e instanceof Template.Children) return (Template.Children)e;
83         List c = e.getChildren();
84         for (int i=0; i < c.size(); i++) {
85             if (!(c.get(i) instanceof XML.Element)) continue;
86             Template.Children ret = findPlaceholder((XML.Element)c.get(i));
87             if (ret != null) return ret;
88         }
89         return null;
90     }
91
92     private Template.Scope tscope;
93
94     public Template(XML.Element w, Template.Scope t) { super(w); tscope = t; }
95
96     public JSScope getParentScope() { return tscope; }
97
98     public static final class IfWrap extends JSElement {
99         public IfWrap(XML.Element e) { super(e); }
100
101         public void out(Writer w) throws IOException {
102             loadAttr();
103
104             try {
105                 Object varIf = get("if"); if (varIf != null) undeclare("if");
106                 if (varIf != null && !"true".equals(varIf)) return;
107             } catch (JSExn e) { throw new JSElement.Exn(e); }
108
109             wrapped.out(w);
110         }
111     }
112
113     public static final class JSTag extends JSElement {
114         public JSTag(XML.Element e) {
115             super(e);
116             List c = getChildren();
117             for (int i=0; i < c.size(); i++)
118                 if (c.get(i) instanceof XML.Element) throw new JSElement.Exn(
119                     "<"+getPrefix()+":js> tags may not have child elements");
120         }
121
122         public void out(Writer w) throws IOException {
123             loadAttr();
124
125             List c = getChildren();
126             StringWriter s = new StringWriter();
127             for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(s);
128             exec(s.toString());
129         }
130     }
131
132     public static final class ForEach extends JSElement {
133         public ForEach(XML.Element e) { super(e); }
134
135         public void out(Writer w) throws IOException {
136             loadAttr();
137
138             try {
139                 Object varIn = get("in"); if (varIn != null) undeclare("in");
140                 Object varPut = get("put"); if (varPut != null) undeclare("put");
141
142                 varIn = exec("return (" + varIn + ");");
143                 if (varIn == null || (varIn instanceof JSArray)) throw new JSElement.Exn(
144                     "<"+getPrefix()+":foreach> requires attribute 'in' to specify " +
145                     "the name of a valid js array in the current scope, not in='"+varIn+"'.");
146
147                 if (varPut == null) varPut = "x";
148                 else if (!(varPut instanceof String) || get(varPut) != null)
149                     throw new JSElement.Exn(
150                     "<"+getPrefix()+":foreach> 'put' attribute requires the name of "+
151                     "an undeclared variable, not put='"+varPut+"'.");
152                 if (get(varPut) != null) throw new JSElement.Exn(
153                     "<"+getPrefix()+":foreach> has no 'put' attribute defined and the "+
154                     "default variable 'x' already exists in the current scope.");
155
156                 List c = getChildren();
157
158                 declare((String)varPut);
159                 Iterator it = ((JSArray)varIn).toList().iterator(); while (it.hasNext()) {
160                     put(varPut, it.next());
161                     for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(w);
162                 }
163             } catch (JSExn e) { throw new JSElement.Exn(e); }
164         }
165     }
166
167     public static final class Children extends JSElement {
168         public Children(XML.Element e) { super(e); }
169     }
170
171     public static final class Redirect extends JSElement {
172         public Redirect(XML.Element e) { super(e); }
173
174         public void out(Writer w) throws IOException {
175             loadAttr();
176
177             try {
178                 Object p = get("page"); if (p != null) undeclare("page");
179                 if (p == null || !(p instanceof String) || ((String)p).trim().equals(""))
180                     throw new JSElement.Exn("<"+getPrefix()+":redirect> requires 'page' "+
181                                             "attribute to be a valid template path");
182                 throw new RedirectSignal((String)p);
183             } catch (JSExn e) { throw new JSElement.Exn(e); }
184         }
185     }
186
187     // TODO: finish
188     public static final class Transaction extends JSElement {
189         private final Template.Scope scope; // FIXME: HACK. unstatisise all tags, or do this to all
190         public Transaction(XML.Element e, Template.Scope s) { super(e); scope = s;} // TODO: check kids
191
192         public void out(Writer w) throws IOException {
193             loadAttr();
194
195             // TODO: <xt:use />
196             List c = getChildren();
197             StringWriter sw = new StringWriter();
198             for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(sw);
199             JS t = JS.fromReader("input", 0, new StringReader(sw.toString()));
200             t = JS.cloneWithNewParentScope(t, new JSScope(null));
201             scope.transaction(t);
202         }
203     }
204
205     public abstract static class Scope extends JSScope {
206         public Scope(JSScope j) { super(j); }
207
208         /** Returns the template path for local:/ namespace. */
209         public abstract String getLocalPath();
210
211         /** Registers a new Prevayler transaction. */
212         public abstract void transaction(JS t);
213     }
214
215     public static class Signal extends RuntimeException {}
216     public static class ReturnSignal extends Signal { }
217     public static class RedirectSignal extends Signal {
218         protected String target;
219         public RedirectSignal(String target) { super(); this.target = target; }
220         public String getTarget() { return target; }
221     }
222 }