]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/template/Template.java
Merge "add: documentation to output classes"
[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 {
79             Reader r = new InputStreamReader(u.openStream(), "UTF-8");
80             try {
81                 if (u.getProtocol().equals("file")) {
82                     source = new File(u.toURI());
83                     lastLoaded = source.lastModified() + 1000;
84                 }
85             } catch (URISyntaxException e) {
86                 e.printStackTrace();
87             }
88             data = parse(r).getBlock(null);
89             r.close();
90         } catch (IOException e) {
91             throw new Error(e);
92         }
93     }
94
95     /**
96      * Creates a new template by parsing the contents from the given reader.
97      * This constructor will fail on syntax error.
98      * 
99      * @param r
100      *            the Reader containing the data.
101      */
102     public Template(Reader r) {
103         try {
104             data = parse(r).getBlock(null);
105             r.close();
106         } catch (IOException e) {
107             throw new Error(e);
108         }
109     }
110
111     private ParseResult parse(Reader r) throws IOException {
112         LinkedList<String> splitted = new LinkedList<String>();
113         LinkedList<Translatable> commands = new LinkedList<Translatable>();
114         StringBuffer buf = new StringBuffer();
115         String blockType = null;
116         outer:
117         while (true) {
118             while ( !endsWith(buf, "<?")) {
119                 int ch = r.read();
120                 if (ch == -1) {
121                     break outer;
122                 }
123                 buf.append((char) ch);
124             }
125             buf.delete(buf.length() - 2, buf.length());
126             splitted.add(buf.toString());
127             buf.delete(0, buf.length());
128             while ( !endsWith(buf, "?>")) {
129                 int ch = r.read();
130                 if (ch == -1) {
131                     throw new EOFException();
132                 }
133                 buf.append((char) ch);
134             }
135             buf.delete(buf.length() - 2, buf.length());
136             String com = buf.toString().replace("\n", "");
137             buf.delete(0, buf.length());
138             Matcher m = CONTROL_PATTERN.matcher(com);
139             if (m.matches()) {
140                 String type = m.group(1);
141                 String variable = m.group(2);
142                 ParseResult body = parse(r);
143                 if (type.equals("if")) {
144                     if ("else".equals(body.getEndType())) {
145                         commands.add(new IfStatement(variable, body.getBlock("else"), parse(r).getBlock("}")));
146                     } else {
147                         commands.add(new IfStatement(variable, body.getBlock("}")));
148                     }
149                 } else if (type.equals("foreach")) {
150                     commands.add(new ForeachStatement(variable, body.getBlock("}")));
151                 } else {
152                     throw new IOException("Syntax error: unknown control structure: " + type);
153                 }
154                 continue;
155             } else if ((m = ELSE_PATTERN.matcher(com)).matches()) {
156                 blockType = "else";
157                 break;
158             } else if (com.matches(" ?\\} ?")) {
159                 blockType = "}";
160                 break;
161             } else {
162                 commands.add(parseCommand(com));
163             }
164         }
165         splitted.add(buf.toString());
166         return new ParseResult(new TemplateBlock(splitted.toArray(new String[splitted.size()]), commands.toArray(new Translatable[commands.size()])), blockType);
167     }
168
169     private boolean endsWith(StringBuffer buf, String string) {
170         return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
171     }
172
173     private Translatable parseCommand(String s2) {
174         if (s2.startsWith("=_")) {
175             final String raw = s2.substring(2);
176             if ( !s2.contains("$") && !s2.contains("!'")) {
177                 return new TranslateCommand(raw);
178             } else {
179                 return new SprintfCommand(raw);
180             }
181         } else if (s2.startsWith("=$")) {
182             final String raw = s2.substring(2);
183             return new OutputVariableCommand(raw);
184         } else {
185             throw new Error("Unknown processing instruction: " + s2);
186         }
187     }
188
189     @Override
190     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
191         if (source != null && lastLoaded < source.lastModified()) {
192             try {
193                 System.out.println("Reloading template.... " + source);
194                 InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8");
195                 data = parse(r).getBlock(null);
196                 r.close();
197                 lastLoaded = source.lastModified() + 1000;
198             } catch (IOException e) {
199                 e.printStackTrace();
200             }
201         }
202         data.output(out, l, vars);
203     }
204
205     protected static void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname, boolean unescaped) {
206         Object s = vars.get(varname);
207
208         if (s == null) {
209             System.out.println("Empty variable: " + varname);
210         }
211         if (s instanceof Outputable) {
212             ((Outputable) s).output(out, l, vars);
213         } else if (s instanceof DayDate) {
214             out.print(DateSelector.getDateFormat().format(((DayDate) s).toDate()));
215         } else if (s instanceof Date) {
216             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
217             out.print(sdf.format(s));
218             out.print(" UTC");
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 }