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;
26 * Represents a loaded template file.
28 public class Template implements Outputable {
30 private static class ParseResult {
36 public ParseResult(TemplateBlock block, String endType) {
38 this.endType = endType;
41 public String getEndType() {
45 public TemplateBlock getBlock(String reqType) {
46 if (endType == null && reqType == null) {
49 if (endType == null || reqType == null) {
50 throw new Error("Invalid block type: " + endType);
52 if (endType.equals(reqType)) {
55 throw new Error("Invalid block type: " + endType);
59 private TemplateBlock data;
61 private long lastLoaded;
65 private static final Pattern CONTROL_PATTERN = Pattern.compile(" ?([a-zA-Z]+)\\(\\$([^)]+)\\) ?\\{ ?");
67 private static final Pattern ELSE_PATTERN = Pattern.compile(" ?\\} ?else ?\\{ ?");
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.
75 * the URL to load the template from. UTF-8 is chosen as charset.
77 public Template(URL u) {
78 try (Reader r = new InputStreamReader(u.openStream(), "UTF-8")) {
80 if (u.getProtocol().equals("file")) {
81 source = new File(u.toURI());
82 lastLoaded = source.lastModified() + 1000;
84 } catch (URISyntaxException e) {
87 data = parse(r).getBlock(null);
88 } catch (IOException e) {
94 * Creates a new template by parsing the contents from the given reader.
95 * This constructor will fail on syntax error.
98 * the Reader containing the data.
100 public Template(Reader r) {
102 data = parse(r).getBlock(null);
104 } catch (IOException e) {
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;
116 while ( !endsWith(buf, "<?")) {
121 buf.append((char) ch);
123 buf.delete(buf.length() - 2, buf.length());
124 splitted.add(buf.toString());
125 buf.delete(0, buf.length());
126 while ( !endsWith(buf, "?>")) {
129 throw new EOFException();
131 buf.append((char) ch);
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);
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("}")));
145 commands.add(new IfStatement(variable, body.getBlock("}")));
147 } else if (type.equals("foreach")) {
148 commands.add(new ForeachStatement(variable, body.getBlock("}")));
150 throw new IOException("Syntax error: unknown control structure: " + type);
153 } else if ((m = ELSE_PATTERN.matcher(com)).matches()) {
156 } else if (com.matches(" ?\\} ?")) {
160 commands.add(parseCommand(com));
163 splitted.add(buf.toString());
164 return new ParseResult(new TemplateBlock(splitted.toArray(new String[splitted.size()]), commands.toArray(new Translatable[commands.size()])), blockType);
167 private boolean endsWith(StringBuffer buf, String string) {
168 return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
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);
177 return new SprintfCommand(raw);
179 } else if (s2.startsWith("=$")) {
180 final String raw = s2.substring(2);
181 return new OutputVariableCommand(raw);
183 throw new Error("Unknown processing instruction: " + s2);
188 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
189 if (source != null && lastLoaded < source.lastModified()) {
191 System.out.println("Reloading template.... " + source);
192 InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8");
193 data = parse(r).getBlock(null);
195 lastLoaded = source.lastModified() + 1000;
196 } catch (IOException e) {
200 data.output(out, l, vars);
203 protected static void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname, boolean unescaped) {
204 if (vars.containsKey(Outputable.OUT_KEY_PLAIN)) {
207 Object s = vars.get(varname);
210 System.out.println("Empty variable: " + varname);
212 if (s instanceof Outputable) {
213 ((Outputable) s).output(out, l, vars);
214 } else if (s instanceof DayDate) {
215 out.print(DateSelector.getDateFormat().format(((DayDate) s).toDate()));
216 } else if (s instanceof Date) {
217 SimpleDateFormat sdfUI = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
218 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
219 out.print("<time datetime=\"" + sdf.format(s) + "\">");
220 out.print(sdfUI.format(s));
221 out.print(" UTC</time>");
223 out.print(s == null ? "null" : (unescaped ? s.toString() : HTMLEncoder.encodeHTML(s.toString())));
227 public void addTranslations(Collection<String> s) {
228 data.addTranslations(s);