1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
7 import org.ibex.util.*;
12 import javax.servlet.*;
13 import javax.servlet.http.*;
15 public class Template extends Node.Stream.Filter implements Node.Stream.Functor {
17 static Template newTemplate(Servlet.ServletScope servletscope, Scope scope, String str) {
19 File f = new File(str);
20 if (!f.exists()) f = new File(str + ".xt");
21 if (!f.exists()) f = new File(str + ".xml");
22 return new Template(servletscope, scope, new InputStreamReader(new FileInputStream(f)));
23 } catch (Exception e) { throw new RuntimeException(e); }
26 static Scope copyNodeToScope(Node n, Scope scope) {
28 for(int i=0; i<n.numattrs; i++) {
29 scope.declare(n.attrs[i*2]);
30 scope.put(JSU.S(n.attrs[i*2]), JSU.S(n.attrs[i*2+1]));
33 } catch (Exception e) { throw new RuntimeException(e); }
36 private class JSRewriter extends Node.Stream {
37 private Node.Stream in;
39 public JSRewriter(Node.Stream in, Scope scope) { this.in = in; this.scope = scope; }
40 protected boolean _read(Node n) { if (!in.read(n)) return false; transform(n, scope); return true; }
43 public static Node transform(Node n, Scope scope) {
45 if (n.cdata != null) n.cdata = eval(n.cdata, scope).toString();
46 else for(int i=1; i<n.numattrs*2; i+=2) n.attrs[i] = eval(n.attrs[i], scope).toString();
48 } catch (JSExn e) { throw new RuntimeException(e); }
51 private static Object eval(String s, Scope scope) throws JSExn {
52 if (s == null) return null;
53 StringBuffer ret = new StringBuffer();
54 for(boolean first = true; s.indexOf("${") != -1; first = false) {
55 ret.append(s.substring(0, s.indexOf("${")));
56 String s2 = s.substring(s.indexOf("${")+2);
57 JS app = exec("return (" + s2.substring(0, s2.indexOf('}')) + ");\n", scope);
58 s = s.substring(s.indexOf('}') + 1);
59 //if (first && s.trim().length() == 0) return app;
60 if (!(app == null || app instanceof JSPrimitive))
61 throw new RuntimeException("javascripts within ${...} can only return strings, numbers, and booleans; not a " +
62 app.getClass().getName());
63 ret.append(app == null ? "null" : JSU.toString(app));
66 return ret.toString();
69 public static JS exec(String s, Scope scope) {
71 return JSU.cloneWithNewGlobalScope(JSU.fromReader("input", 0, new StringReader(s)), scope).call(null,null);
72 } catch (Exception e) {
74 throw new RuntimeException(e);
79 private Servlet.ServletScope servletscope;
80 private Node.Stream children;
81 public Node.Stream wrap(Node.Stream children) { this.children = children; return this; }
82 public Template(Servlet.ServletScope servletscope, JS scope, Reader template) {
83 super(new Node.Stream.FromXML(template));
84 this.scope = new Scope(scope);
85 this.servletscope = servletscope;
87 public boolean _read(Node n) { boolean ret = __read(n); if (ret) transform(n, scope); return ret; }
88 public boolean __read(final Node n) {
89 if (!upstreamRead(n)) return false;
90 if (n.cdata != null) return true;
91 final String uri = n.uri;
92 final String name = n.name;
93 if (uri.indexOf(':') == -1)
94 throw new RuntimeException("uri does not contain a colon: " + uri + " (tag name " + name + ")");
95 final String method = uri.substring(0, uri.indexOf(':'));
96 final String rest = uri.substring(uri.indexOf(':')+1);
97 if (uri.equals("http://www.w3.org/1999/xhtml")) { return true;
98 } else if (method.equals("webinf")) {
99 return graft(newTemplate(servletscope, copyNodeToScope(transform(n, scope), new Scope(servletscope)),
100 servletscope.getRealPath("/") + "/WEB-INF/" + rest + name), n).upstreamRead(n);
101 } else if (uri.equals("http://xt.ibex.org/")) {
105 return graft((Node.Stream.Functor)("true".equals(n.attr("if")) ? new DropTag() : new DropAll()), n).upstreamRead(n);
106 case "js": return graft(new JsTag(scope), n).upstreamRead(n);
107 case "foreach": return graft(new ForEach(n, scope), n).upstreamRead(n);
109 if (children == null) return true;
110 graft(new Node.Stream.ConstantFunctor(children), n);
112 return upstreamRead(n);
115 } else if (method.equals("java")) {
116 try { return graft((Node.Stream.Functor)Class.forName(rest).newInstance(), n).upstreamRead(n); }
117 catch (Exception e) { throw new RuntimeException(e); }
119 throw new RuntimeException("Unknown namespace URI " + uri);
122 private class ForEach extends Node.Stream.Filter implements Node.Stream.Functor {
123 private Node[] nodes = null;
124 private Vec array = new Vec();
126 public ForEach(Node n, Scope s) {
127 super(Node.Stream.NULL);
129 JSArray a = ((JSArray)exec("return (" + n.attr("in").toString() + ");", this.scope = s));
131 JS o = a.call(JSU.S("pop"), new JS[] { });
132 if (o == null) break;
136 throw new RuntimeException(e);
139 public Node.Stream wrap(Node.Stream kids) {
140 Vec nodes = new Vec();
141 Node n2 = new Node();
142 while(kids.read(n2)) nodes.addElement(new Node(n2));
143 nodes.copyInto(this.nodes = new Node[nodes.size()]);
146 protected boolean _read(Node n) {
147 if (upstreamRead(n)) return true;
148 if (array.size() == 0) return false;
149 Scope scope2 = new Scope(scope);
150 try { scope2.declare("x"); scope2.put(JSU.S("x"), (JS)array.pop()); } catch (JSExn e) { throw new RuntimeException(e); }
151 return graft(new ConstantFunctor(new JSRewriter(new Node.Stream() {
153 protected boolean _read(Node n) {
154 if (i>=nodes.length) return false;
155 n.copyFrom(nodes[i++]);
157 } }, scope2)), n).upstreamRead(n);
161 public static class Scope extends JS.Obj {
162 private final JS parent;
163 private final Hash declared = new Hash();
164 public Scope(JS parent) { this.parent = parent; }
165 public JS get(JS key) throws JSExn {
166 if (declared.get(key)!=null) return super.get(key);
167 return parent.get(key);
169 public void put(JS key, JS val) throws JSExn {
170 if (declared.get(key)!=null) super.put(key, val);
171 else parent.put(key, val);
173 public void declare(JS key) { declared.put(key, Boolean.TRUE); }
174 public void declare(String key) { declare(JSU.S(key)); }
175 public void undeclare(JS key) { declared.remove(key); }
176 public void undeclare(String key) { undeclare(JSU.S(key)); }
179 private class DropTag implements Node.Stream.Functor {
180 public Node.Stream wrap(Node.Stream kids) {
184 private class DropAll implements Node.Stream.Functor {
185 public Node.Stream wrap(Node.Stream kids) {
186 return new Node.Stream() { public boolean _read(Node n) { return false; } };
189 private class JsTag implements Node.Stream.Functor {
191 public JsTag(Scope scope) { this.scope = scope; }
192 public Node.Stream wrap(final Node.Stream s) {
193 return new Node.Stream() {
194 protected boolean _read(Node n) {
195 boolean ret = s.read(n);
196 if (ret && n.cdata != null) {
197 System.err.println("exec("+n.cdata+")");
198 exec(n.cdata, scope);