01: /*
02: * @(#)Template.java 1.2 04/12/06
03: *
04: * Copyright (c) 2001-2003 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package pnuts.text;
10:
11: import java.io.*;
12: import java.util.*;
13: import java.lang.reflect.*;
14: import pnuts.lang.*;
15: import pnuts.lang.Runtime;
16:
17: public class Template {
18: private String text;
19: private int[] startIndexes;
20: private int[] endIndexes;
21: private String[] keys;
22:
23: public Template(String text, int[] startIndexes, int[] endIndexes,
24: String[] keys) {
25: this .text = text;
26: this .startIndexes = startIndexes;
27: this .endIndexes = endIndexes;
28: this .keys = keys;
29: }
30:
31: static void apply(Object val, Writer writer, Context context)
32: throws IOException {
33: if (val instanceof String) {
34: writer.write((String) val);
35: } else if (val instanceof PnutsFunction) {
36: ((PnutsFunction) val)
37: .call(new Object[] { writer }, context);
38: } else if (val instanceof Collection) {
39: Collection col = (Collection) val;
40: for (Iterator it = col.iterator(); it.hasNext();) {
41: apply(it.next(), writer, context);
42: }
43: } else if (val instanceof Iterator) {
44: for (Iterator it = (Iterator) val; it.hasNext();) {
45: apply(it.next(), writer, context);
46: }
47: } else if (val instanceof Enumeration) {
48: for (Enumeration en = (Enumeration) val; en
49: .hasMoreElements();) {
50: apply(en.nextElement(), writer, context);
51: }
52: } else if (Runtime.isArray(val)) {
53: int len = Runtime.getArrayLength(val);
54: for (int i = 0; i < len; i++) {
55: apply(Array.get(val, i), writer, context);
56: }
57: } else if (val != null) {
58: writer.write(val.toString());
59: }
60: }
61:
62: public void format(Map def, Writer writer, Context context)
63: throws IOException {
64: int offset = 0;
65: for (int i = 0; i < keys.length; i++) {
66: writer.write(text, offset, startIndexes[i] - offset);
67: apply(def.get(keys[i]), writer, context);
68: offset = endIndexes[i];
69: }
70: writer.write(text, offset, text.length() - offset);
71: }
72:
73: public String toString() {
74: return text;
75: }
76: }
|