1 package org.cacert.gigi.output.template;
3 import java.io.EOFException;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.io.PrintWriter;
10 import java.net.URISyntaxException;
12 import java.text.SimpleDateFormat;
13 import java.util.Collection;
14 import java.util.Date;
15 import java.util.LinkedList;
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
20 import org.cacert.gigi.localisation.Language;
21 import org.cacert.gigi.output.DateSelector;
22 import org.cacert.gigi.util.DayDate;
23 import org.cacert.gigi.util.HTMLEncoder;
25 public class Template implements Outputable {
27 private static class ParseResult {
33 public ParseResult(TemplateBlock block, String endType) {
35 this.endType = endType;
38 public String getEndType() {
42 public TemplateBlock getBlock(String reqType) {
43 if (endType == null && reqType == null) {
46 if (endType == null || reqType == null) {
47 throw new Error("Invalid block type: " + endType);
49 if (endType.equals(reqType)) {
52 throw new Error("Invalid block type: " + endType);
56 private TemplateBlock data;
58 private long lastLoaded;
62 private static final Pattern CONTROL_PATTERN = Pattern.compile(" ?([a-zA-Z]+)\\(\\$([^)]+)\\) ?\\{ ?");
64 private static final Pattern ELSE_PATTERN = Pattern.compile(" ?\\} ?else ?\\{ ?");
66 public Template(URL u) {
68 Reader r = new InputStreamReader(u.openStream(), "UTF-8");
70 if (u.getProtocol().equals("file")) {
71 source = new File(u.toURI());
72 lastLoaded = source.lastModified() + 1000;
74 } catch (URISyntaxException e) {
77 data = parse(r).getBlock(null);
79 } catch (IOException e) {
84 public Template(Reader r) {
86 data = parse(r).getBlock(null);
88 } catch (IOException e) {
93 private ParseResult parse(Reader r) throws IOException {
94 LinkedList<String> splitted = new LinkedList<String>();
95 LinkedList<Translatable> commands = new LinkedList<Translatable>();
96 StringBuffer buf = new StringBuffer();
97 String blockType = null;
100 while ( !endsWith(buf, "<?")) {
105 buf.append((char) ch);
107 buf.delete(buf.length() - 2, buf.length());
108 splitted.add(buf.toString());
109 buf.delete(0, buf.length());
110 while ( !endsWith(buf, "?>")) {
113 throw new EOFException();
115 buf.append((char) ch);
117 buf.delete(buf.length() - 2, buf.length());
118 String com = buf.toString().replace("\n", "");
119 buf.delete(0, buf.length());
120 Matcher m = CONTROL_PATTERN.matcher(com);
122 String type = m.group(1);
123 String variable = m.group(2);
124 ParseResult body = parse(r);
125 if (type.equals("if")) {
126 if ("else".equals(body.getEndType())) {
127 commands.add(new IfStatement(variable, body.getBlock("else"), parse(r).getBlock("}")));
129 commands.add(new IfStatement(variable, body.getBlock("}")));
131 } else if (type.equals("foreach")) {
132 commands.add(new ForeachStatement(variable, body.getBlock("}")));
134 throw new IOException("Syntax error: unknown control structure: " + type);
137 } else if ((m = ELSE_PATTERN.matcher(com)).matches()) {
140 } else if (com.matches(" ?\\} ?")) {
144 commands.add(parseCommand(com));
147 splitted.add(buf.toString());
148 return new ParseResult(new TemplateBlock(splitted.toArray(new String[splitted.size()]), commands.toArray(new Translatable[commands.size()])), blockType);
151 private boolean endsWith(StringBuffer buf, String string) {
152 return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
155 private Translatable parseCommand(String s2) {
156 if (s2.startsWith("=_")) {
157 final String raw = s2.substring(2);
158 if ( !s2.contains("$") && !s2.contains("!'")) {
159 return new TranslateCommand(raw);
161 return new SprintfCommand(raw);
163 } else if (s2.startsWith("=$")) {
164 final String raw = s2.substring(2);
165 return new OutputVariableCommand(raw);
167 throw new Error("Unknown processing instruction: " + s2);
172 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
173 if (source != null && lastLoaded < source.lastModified()) {
175 System.out.println("Reloading template.... " + source);
176 InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8");
177 data = parse(r).getBlock(null);
179 lastLoaded = source.lastModified() + 1000;
180 } catch (IOException e) {
184 data.output(out, l, vars);
187 protected static void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname, boolean unescaped) {
188 Object s = vars.get(varname);
191 System.out.println("Empty variable: " + varname);
193 if (s instanceof Outputable) {
194 ((Outputable) s).output(out, l, vars);
195 } else if (s instanceof DayDate) {
196 out.print(DateSelector.getDateFormat().format(((DayDate) s).toDate()));
197 } else if (s instanceof Date) {
198 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
199 out.print(sdf.format(s));
202 out.print(s == null ? "null" : (unescaped ? s.toString() : HTMLEncoder.encodeHTML(s.toString())));
206 public void addTranslations(Collection<String> s) {
207 data.addTranslations(s);