]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/template/Template.java
8ad47bc2876a271dea1cce221c4a732cc2907190
[gigi.git] / src / org / cacert / gigi / output / template / Template.java
1 package org.cacert.gigi.output.template;
2
3 import java.io.EOFException;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.io.PrintWriter;
9 import java.io.Reader;
10 import java.net.URISyntaxException;
11 import java.net.URL;
12 import java.text.SimpleDateFormat;
13 import java.util.Collection;
14 import java.util.Date;
15 import java.util.LinkedList;
16 import java.util.Map;
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
19
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;
24
25 /**
26  * Represents a loaded template file.
27  */
28 public class Template implements Outputable {
29
30     protected static class ParseResult {
31
32         TemplateBlock block;
33
34         String endType;
35
36         public ParseResult(TemplateBlock block, String endType) {
37             this.block = block;
38             this.endType = endType;
39         }
40
41         public String getEndType() {
42             return endType;
43         }
44
45         public TemplateBlock getBlock(String reqType) {
46             if (endType == null && reqType == null) {
47                 return block;
48             }
49             if (endType == null || reqType == null) {
50                 throw new Error("Invalid block type: " + endType);
51             }
52             if (endType.equals(reqType)) {
53                 return block;
54             }
55             throw new Error("Invalid block type: " + endType);
56         }
57     }
58
59     private TemplateBlock data;
60
61     private long lastLoaded;
62
63     private File source;
64
65     private static final Pattern CONTROL_PATTERN = Pattern.compile(" ?([a-zA-Z]+)\\(\\$([^)]+)\\) ?\\{ ?");
66
67     private static final Pattern ELSE_PATTERN = Pattern.compile(" ?\\} ?else ?\\{ ?");
68
69     /**
70      * Creates a new template by parsing the contents from the given URL. This
71      * constructor will fail on syntax error. When the URL points to a file,
72      * {@link File#lastModified()} is monitored for changes of the template.
73      * 
74      * @param u
75      *            the URL to load the template from. UTF-8 is chosen as charset.
76      */
77     public Template(URL u) {
78         try (Reader r = new InputStreamReader(u.openStream(), "UTF-8")) {
79             try {
80                 if (u.getProtocol().equals("file")) {
81                     source = new File(u.toURI());
82                     lastLoaded = source.lastModified() + 1000;
83                 }
84             } catch (URISyntaxException e) {
85                 e.printStackTrace();
86             }
87             data = parse(r).getBlock(null);
88         } catch (IOException e) {
89             throw new Error(e);
90         }
91     }
92
93     /**
94      * Creates a new template by parsing the contents from the given reader.
95      * This constructor will fail on syntax error.
96      * 
97      * @param r
98      *            the Reader containing the data.
99      */
100     public Template(Reader r) {
101         try {
102             data = parse(r).getBlock(null);
103             r.close();
104         } catch (IOException e) {
105             throw new Error(e);
106         }
107     }
108
109     protected ParseResult parse(Reader r) throws IOException {
110         return parseContent(r);
111     }
112
113     protected ParseResult parseContent(Reader r) throws IOException {
114         LinkedList<String> splitted = new LinkedList<String>();
115         LinkedList<Translatable> commands = new LinkedList<Translatable>();
116         StringBuffer buf = new StringBuffer();
117         String blockType = null;
118         outer:
119         while (true) {
120             while ( !endsWith(buf, "<?")) {
121                 int ch = r.read();
122                 if (ch == -1) {
123                     break outer;
124                 }
125                 buf.append((char) ch);
126             }
127             buf.delete(buf.length() - 2, buf.length());
128             splitted.add(buf.toString());
129             buf.delete(0, buf.length());
130             while ( !endsWith(buf, "?>")) {
131                 int ch = r.read();
132                 if (ch == -1) {
133                     throw new EOFException();
134                 }
135                 buf.append((char) ch);
136             }
137             buf.delete(buf.length() - 2, buf.length());
138             String com = buf.toString().replace("\n", "");
139             buf.delete(0, buf.length());
140             Matcher m = CONTROL_PATTERN.matcher(com);
141             if (m.matches()) {
142                 String type = m.group(1);
143                 String variable = m.group(2);
144                 ParseResult body = parseContent(r);
145                 if (type.equals("if")) {
146                     if ("else".equals(body.getEndType())) {
147                         commands.add(new IfStatement(variable, body.getBlock("else"), parseContent(r).getBlock("}")));
148                     } else {
149                         commands.add(new IfStatement(variable, body.getBlock("}")));
150                     }
151                 } else if (type.equals("foreach")) {
152                     commands.add(new ForeachStatement(variable, body.getBlock("}")));
153                 } else {
154                     throw new IOException("Syntax error: unknown control structure: " + type);
155                 }
156                 continue;
157             } else if ((m = ELSE_PATTERN.matcher(com)).matches()) {
158                 blockType = "else";
159                 break;
160             } else if (com.matches(" ?\\} ?")) {
161                 blockType = "}";
162                 break;
163             } else {
164                 commands.add(parseCommand(com));
165             }
166         }
167         splitted.add(buf.toString());
168         return new ParseResult(new TemplateBlock(splitted.toArray(new String[splitted.size()]), commands.toArray(new Translatable[commands.size()])), blockType);
169     }
170
171     private boolean endsWith(StringBuffer buf, String string) {
172         return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
173     }
174
175     private Translatable parseCommand(String s2) {
176         if (s2.startsWith("=_")) {
177             final String raw = s2.substring(2);
178             if ( !s2.contains("$") && !s2.contains("!'")) {
179                 return new TranslateCommand(raw);
180             } else {
181                 return new SprintfCommand(raw);
182             }
183         } else if (s2.startsWith("=$")) {
184             final String raw = s2.substring(2);
185             return new OutputVariableCommand(raw);
186         } else {
187             throw new Error("Unknown processing instruction: " + s2);
188         }
189     }
190
191     @Override
192     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
193         tryReload();
194         data.output(out, l, vars);
195     }
196
197     protected void tryReload() {
198         if (source != null && lastLoaded < source.lastModified()) {
199             try {
200                 System.out.println("Reloading template.... " + source);
201                 InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8");
202                 data = parse(r).getBlock(null);
203                 r.close();
204                 lastLoaded = source.lastModified() + 1000;
205             } catch (IOException e) {
206                 e.printStackTrace();
207             }
208         }
209     }
210
211     protected static void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname, boolean unescaped) {
212         if (vars.containsKey(Outputable.OUT_KEY_PLAIN)) {
213             unescaped = true;
214         }
215         Object s = vars.get(varname);
216
217         if (s == null) {
218             System.out.println("Empty variable: " + varname);
219         }
220         if (s instanceof Outputable) {
221             ((Outputable) s).output(out, l, vars);
222         } else if (s instanceof DayDate) {
223             out.print(DateSelector.getDateFormat().format(((DayDate) s).toDate()));
224         } else if (s instanceof Date) {
225             SimpleDateFormat sdfUI = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
226             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
227             out.print("<time datetime=\"" + sdf.format(s) + "\">");
228             out.print(sdfUI.format(s));
229             out.print(" UTC</time>");
230         } else {
231             out.print(s == null ? "null" : (unescaped ? s.toString() : HTMLEncoder.encodeHTML(s.toString())));
232         }
233     }
234
235     public void addTranslations(Collection<String> s) {
236         data.addTranslations(s);
237     }
238 }