1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 package groovy.util;
47
48
49 import org.codehaus.groovy.runtime.InvokerHelper;
50
51 import java.io.OutputStreamWriter;
52 import java.io.PrintWriter;
53 import java.util.Iterator;
54 import java.util.List;
55 import java.util.Map;
56
57 /***
58 * A helper class for creating nested trees of data
59 *
60 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
61 * @author Christian Stein
62 * @version $Revision: 1.4 $
63 */
64 public class NodePrinter {
65
66 protected final IndentPrinter out;
67
68 public NodePrinter() {
69 this(new IndentPrinter(new PrintWriter(new OutputStreamWriter(System.out))));
70 }
71
72 public NodePrinter(PrintWriter out) {
73 this(new IndentPrinter(out));
74 }
75
76 public NodePrinter(IndentPrinter out) {
77 if (out == null) {
78 throw new NullPointerException("IndentPrinter 'out' must not be null!");
79 }
80 this.out = out;
81 }
82
83 public void print(Node node) {
84 out.printIndent();
85 printName(node);
86 Map attributes = node.attributes();
87 boolean hasAttributes = attributes != null && !attributes.isEmpty();
88 if (hasAttributes) {
89 printAttributes(attributes);
90 }
91 Object value = node.value();
92 if (value instanceof List) {
93 if (!hasAttributes) {
94 out.print("()");
95 }
96 printList((List) value);
97 }
98 else {
99 if (value instanceof String) {
100 out.print("('");
101 out.print((String) value);
102 out.println("')");
103 }
104 else {
105 out.println("()");
106 }
107 }
108 out.flush();
109 }
110
111 protected void printName(Node node) {
112 Object name = node.name();
113 if (name != null) {
114 out.print(name.toString());
115 }
116 else {
117 out.print("null");
118 }
119 }
120
121 protected void printList(List list) {
122 if (list.isEmpty()) {
123 out.println("");
124 }
125 else {
126 out.println(" {");
127 out.incrementIndent();
128 for (Iterator iter = list.iterator(); iter.hasNext();) {
129 Object value = iter.next();
130 if (value instanceof Node) {
131 print((Node) value);
132 }
133 else {
134 out.printIndent();
135 out.print("builder.append(");
136 out.print(InvokerHelper.toString(value));
137 out.println(")");
138 }
139 }
140 out.decrementIndent();
141 out.printIndent();
142 out.println("}");
143 }
144 }
145
146
147 protected void printAttributes(Map attributes) {
148 out.print("(");
149 boolean first = true;
150 for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) {
151 Map.Entry entry = (Map.Entry) iter.next();
152 if (first) {
153 first = false;
154 }
155 else {
156 out.print(", ");
157 }
158 out.print(entry.getKey().toString());
159 out.print(":");
160 if (entry.getValue() instanceof String) {
161 out.print("'" + entry.getValue() + "'");
162 }
163 else {
164 out.print(InvokerHelper.toString(entry.getValue()));
165 }
166 }
167 out.print(")");
168 }
169
170 }