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) {
79 Reader r = new InputStreamReader(u.openStream(), "UTF-8");
81 if (u.getProtocol().equals("file")) {
82 source = new File(u.toURI());
83 lastLoaded = source.lastModified() + 1000;
85 } catch (URISyntaxException e) {
88 data = parse(r).getBlock(null);
90 } catch (IOException e) {
96 * Creates a new template by parsing the contents from the given reader.
97 * This constructor will fail on syntax error.
100 * the Reader containing the data.
102 public Template(Reader r) {
104 data = parse(r).getBlock(null);
106 } catch (IOException e) {
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;
118 while ( !endsWith(buf, "<?")) {
123 buf.append((char) ch);
125 buf.delete(buf.length() - 2, buf.length());
126 splitted.add(buf.toString());
127 buf.delete(0, buf.length());
128 while ( !endsWith(buf, "?>")) {
131 throw new EOFException();
133 buf.append((char) ch);
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);
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("}")));
147 commands.add(new IfStatement(variable, body.getBlock("}")));
149 } else if (type.equals("foreach")) {
150 commands.add(new ForeachStatement(variable, body.getBlock("}")));
152 throw new IOException("Syntax error: unknown control structure: " + type);
155 } else if ((m = ELSE_PATTERN.matcher(com)).matches()) {
158 } else if (com.matches(" ?\\} ?")) {
162 commands.add(parseCommand(com));
165 splitted.add(buf.toString());
166 return new ParseResult(new TemplateBlock(splitted.toArray(new String[splitted.size()]), commands.toArray(new Translatable[commands.size()])), blockType);
169 private boolean endsWith(StringBuffer buf, String string) {
170 return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
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);
179 return new SprintfCommand(raw);
181 } else if (s2.startsWith("=$")) {
182 final String raw = s2.substring(2);
183 return new OutputVariableCommand(raw);
185 throw new Error("Unknown processing instruction: " + s2);
190 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
191 if (source != null && lastLoaded < source.lastModified()) {
193 System.out.println("Reloading template.... " + source);
194 InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8");
195 data = parse(r).getBlock(null);
197 lastLoaded = source.lastModified() + 1000;
198 } catch (IOException e) {
202 data.output(out, l, vars);
205 protected static void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname, boolean unescaped) {
206 Object s = vars.get(varname);
209 System.out.println("Empty variable: " + varname);
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 sdfUI = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
217 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
218 out.print("<time datetime=\"" + sdf.format(s) + "\">");
219 out.print(sdfUI.format(s));
220 out.print(" UTC</time>");
222 out.print(s == null ? "null" : (unescaped ? s.toString() : HTMLEncoder.encodeHTML(s.toString())));
226 public void addTranslations(Collection<String> s) {
227 data.addTranslations(s);