1 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 63 public class NodePrinter { 64 65 private IndentPrinter out; 66 67 public NodePrinter() { 68 this(new IndentPrinter(new PrintWriter (new OutputStreamWriter (System.out)))); 69 } 70 71 public NodePrinter(PrintWriter out) { 72 this(new IndentPrinter(out)); 73 } 74 75 public NodePrinter(IndentPrinter out) { 76 this.out = out; 77 } 78 79 public void print(Node node) { 80 out.printIndent(); 81 printName(node); 82 Map attributes = node.attributes(); 83 boolean hasAttributes = attributes != null && !attributes.isEmpty(); 84 if (hasAttributes) { 85 printAttributes(attributes); 86 } 87 Object value = node.value(); 88 if (value instanceof List ) { 89 if (!hasAttributes) { 90 out.print("()"); 91 } 92 printList((List ) value); 93 } 94 else { 95 if (value instanceof String ) { 96 out.print("('"); 97 out.print((String ) value); 98 out.println("')"); 99 } 100 else { 101 out.println("()"); 102 } 103 } 104 out.flush(); 105 } 106 107 protected void printName(Node node) { 108 Object name = node.name(); 109 if (name != null) { 110 out.print(name.toString()); 111 } 112 else { 113 out.print("null"); 114 } 115 } 116 117 protected void printList(List list) { 118 if (list.isEmpty()) { 119 out.println(""); 120 } 121 else { 122 out.println(" {"); 123 out.incrementIndent(); 124 for (Iterator iter = list.iterator(); iter.hasNext();) { 125 Object value = iter.next(); 126 if (value instanceof Node) { 127 print((Node) value); 128 } 129 else { 130 out.printIndent(); 131 out.print("builder.append("); 132 out.print(InvokerHelper.toString(value)); 133 out.println(")"); 134 } 135 } 136 out.decrementIndent(); 137 out.printIndent(); 138 out.println("}"); 139 } 140 } 141 142 143 protected void printAttributes(Map attributes) { 144 out.print("("); 145 boolean first = true; 146 for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { 147 Map.Entry entry = (Map.Entry ) iter.next(); 148 if (first) { 149 first = false; 150 } 151 else { 152 out.print(", "); 153 } 154 out.print(entry.getKey().toString()); 155 out.print(":"); 156 if (entry.getValue() instanceof String ) { 157 out.print("'" + entry.getValue() + "'"); 158 } 159 else { 160 out.print(InvokerHelper.toString(entry.getValue())); 161 } 162 } 163 out.print(")"); 164 } 165 166 } 167 | Popular Tags |