1 package org.cacert.gigi.output;
3 import java.io.PrintWriter;
5 import java.util.LinkedList;
7 import java.util.Scanner;
8 import java.util.regex.Pattern;
10 import org.cacert.gigi.Language;
12 public class Template implements Outputable {
15 public Template(Reader r) {
16 LinkedList<String> splitted = new LinkedList<String>();
17 Scanner sc = new Scanner(r);
18 Pattern p1 = Pattern.compile("([^<]|<[^?])*<\\?");
19 Pattern p2 = Pattern.compile("([^<]|<[^?])*\\?>");
21 String s1 = sc.findWithinHorizon(p1, 0);
25 s1 = s1.substring(0, s1.length() - 2);
27 String s2 = sc.findWithinHorizon(p2, 0);
28 s2 = s2.substring(0, s2.length() - 2);
31 sc.useDelimiter("\0");
33 splitted.add(sc.next());
36 contents = splitted.toArray(new String[splitted.size()]);
38 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
39 LinkedList<String> store = new LinkedList<String>();
40 for (int i = 0; i < contents.length; i++) {
42 out.print(contents[i]);
43 } else if (contents[i].startsWith("=_")) {
44 out.print(l.getTranslation(contents[i].substring(2)));
45 } else if (contents[i].startsWith("=$")) {
46 outputVar(out, l, vars, contents[i].substring(2));
47 } else if (contents[i].startsWith("=s,")) {
48 String command = contents[i].substring(3);
50 while (command.startsWith("$")) {
51 int idx = command.indexOf(",");
52 store.add(command.substring(0, idx));
53 command = command.substring(idx + 1);
55 String[] parts = l.getTranslation(command).split("%s");
56 String[] myvars = store.toArray(new String[store.size()]);
58 for (int j = 1; j < parts.length; j++) {
59 outputVar(out, l, vars, myvars[j - 1].substring(1));
63 System.out.println("Unknown processing instruction: "
68 private void outputVar(PrintWriter out, Language l,
69 Map<String, Object> vars, String varname) {
70 Object s = vars.get(varname);
73 System.out.println("Empty variable: " + varname);
75 if (s instanceof Outputable) {
76 ((Outputable) s).output(out, l, vars);