]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/template/Template.java
e80885710959c0ce23ba67c02350b4f94a6d39e7
[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     private 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     private ParseResult parse(Reader r) throws IOException {
110         LinkedList<String> splitted = new LinkedList<String>();
111         LinkedList<Translatable> commands = new LinkedList<Translatable>();
112         StringBuffer buf = new StringBuffer();
113         String blockType = null;
114         outer:
115         while (true) {
116             while ( !endsWith(buf, "<?")) {
117                 int ch = r.read();
118                 if (ch == -1) {
119                     break outer;
120                 }
121                 buf.append((char) ch);
122             }
123             buf.delete(buf.length() - 2, buf.length());
124             splitted.add(buf.toString());
125             buf.delete(0, buf.length());
126             while ( !endsWith(buf, "?>")) {
127                 int ch = r.read();
128                 if (ch == -1) {
129                     throw new EOFException();
130                 }
131                 buf.append((char) ch);
132             }
133             buf.delete(buf.length() - 2, buf.length());
134             String com = buf.toString().replace("\n", "");
135             buf.delete(0, buf.length());
136             Matcher m = CONTROL_PATTERN.matcher(com);
137             if (m.matches()) {
138                 String type = m.group(1);
139                 String variable = m.group(2);
140                 ParseResult body = parse(r);
141                 if (type.equals("if")) {
142                     if ("else".equals(body.getEndType())) {
143                         commands.add(new IfStatement(variable, body.getBlock("else"), parse(r).getBlock("}")));
144                     } else {
145                         commands.add(new IfStatement(variable, body.getBlock("}")));
146                     }
147                 } else if (type.equals("foreach")) {
148                     commands.add(new ForeachStatement(variable, body.getBlock("}")));
149                 } else {
150                     throw new IOException("Syntax error: unknown control structure: " + type);
151                 }
152                 continue;
153             } else if ((m = ELSE_PATTERN.matcher(com)).matches()) {
154                 blockType = "else";
155                 break;
156             } else if (com.matches(" ?\\} ?")) {
157                 blockType = "}";
158                 break;
159             } else {
160                 commands.add(parseCommand(com));
161             }
162         }
163         splitted.add(buf.toString());
164         return new ParseResult(new TemplateBlock(splitted.toArray(new String[splitted.size()]), commands.toArray(new Translatable[commands.size()])), blockType);
165     }
166
167     private boolean endsWith(StringBuffer buf, String string) {
168         return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
169     }
170
171     private Translatable parseCommand(String s2) {
172         if (s2.startsWith("=_")) {
173             final String raw = s2.substring(2);
174             if ( !s2.contains("$") && !s2.contains("!'")) {
175                 return new TranslateCommand(raw);
176             } else {
177                 return new SprintfCommand(raw);
178             }
179         } else if (s2.startsWith("=$")) {
180             final String raw = s2.substring(2);
181             return new OutputVariableCommand(raw);
182         } else {
183             throw new Error("Unknown processing instruction: " + s2);
184         }
185     }
186
187     @Override
188     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
189         if (source != null && lastLoaded < source.lastModified()) {
190             try {
191                 System.out.println("Reloading template.... " + source);
192                 InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8");
193                 data = parse(r).getBlock(null);
194                 r.close();
195                 lastLoaded = source.lastModified() + 1000;
196             } catch (IOException e) {
197                 e.printStackTrace();
198             }
199         }
200         data.output(out, l, vars);
201     }
202
203     protected static void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname, boolean unescaped) {
204         Object s = vars.get(varname);
205
206         if (s == null) {
207             System.out.println("Empty variable: " + varname);
208         }
209         if (s instanceof Outputable) {
210             ((Outputable) s).output(out, l, vars);
211         } else if (s instanceof DayDate) {
212             out.print(DateSelector.getDateFormat().format(((DayDate) s).toDate()));
213         } else if (s instanceof Date) {
214             SimpleDateFormat sdfUI = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
215             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
216             out.print("<time datetime=\"" + sdf.format(s) + "\">");
217             out.print(sdfUI.format(s));
218             out.print(" UTC</time>");
219         } else {
220             out.print(s == null ? "null" : (unescaped ? s.toString() : HTMLEncoder.encodeHTML(s.toString())));
221         }
222     }
223
224     public void addTranslations(Collection<String> s) {
225         data.addTranslations(s);
226     }
227 }