1 package org.cacert.gigi.output.template;
3 import java.io.PrintWriter;
4 import java.util.LinkedList;
7 import java.util.regex.Matcher;
8 import java.util.regex.Pattern;
10 import org.cacert.gigi.localisation.Language;
11 import org.cacert.gigi.util.HTMLEncoder;
13 public final class SprintfCommand implements Outputable {
15 private final String text;
17 private final String[] store;
19 public SprintfCommand(String text, List<String> store) {
21 this.store = store.toArray(new String[store.size()]);
24 private static final String VARIABLE = "\\$!?\\{[a-zA-Z0-9_-]+\\}";
26 private static final Pattern processingInstruction = Pattern.compile("(" + VARIABLE + ")|(!'[^{}'\\$]*)'");
28 public SprintfCommand(String content) {
29 StringBuffer raw = new StringBuffer();
30 List<String> var = new LinkedList<String>();
32 Matcher m = processingInstruction.matcher(content);
35 raw.append(content.substring(last, m.start()));
37 if ((group = m.group(1)) != null) {
39 } else if ((group = m.group(2)) != null) {
42 throw new Error("Regex is broken??");
45 raw.append("{" + (counter++) + "}");
47 raw.append(content.substring(last));
48 text = raw.toString();
49 store = var.toArray(new String[var.size()]);
52 private final Pattern replacant = Pattern.compile("\\{([0-9]+)\\}");
55 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
56 String parts = l.getTranslation(text);
57 Matcher m = replacant.matcher(parts);
60 out.print(HTMLEncoder.encodeHTML(parts.substring(pos, m.start())));
61 String var = store[Integer.parseInt(m.group(1))];
62 if (var.startsWith("$!")) {
63 Template.outputVar(out, l, vars, var.substring(3, var.length() - 1), true);
64 } else if (var.startsWith("!'")) {
65 out.print(var.substring(2));
66 } else if (var.startsWith("$")) {
67 Template.outputVar(out, l, vars, var.substring(2, var.length() - 1), false);
69 throw new Error("Processing error in template.");
74 out.print(HTMLEncoder.encodeHTML(parts.substring(pos)));