View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.xml.ast;
5   
6   import java.io.IOException;
7   import java.io.PrintWriter;
8   import java.io.Writer;
9   import java.util.ArrayList;
10  import java.util.Iterator;
11  import java.util.List;
12  
13  import net.sourceforge.pmd.lang.ast.xpath.Attribute;
14  import net.sourceforge.pmd.util.StringUtil;
15  
16  public class DumpFacade {
17  
18  	private PrintWriter writer;
19  	private boolean recurse;
20  
21  	public void initializeWith(Writer writer, String prefix, boolean recurse, XmlNode node) {
22  		this.writer = (writer instanceof PrintWriter) ? (PrintWriter) writer : new PrintWriter(writer);
23  		this.recurse = recurse;
24  		this.dump(node, prefix);
25  		try {
26  			writer.flush();
27  		} catch (IOException e) {
28  			throw new RuntimeException("Problem flushing PrintWriter.", e);
29  		}
30  	}
31  
32  	public Object visit(XmlNode node, Object data) {
33  		dump(node, (String) data);
34  		if (recurse) {
35  			for (int i = 0; i < node.jjtGetNumChildren(); i++) {
36  				visit((XmlNode) node.jjtGetChild(i), data + " ");
37  			}
38  			return data;
39  		} else {
40  			return data;
41  		}
42  	}
43  
44  	private void dump(XmlNode node, String prefix) {
45  		//
46  		// Dump format is generally composed of the following items...
47  		//
48  
49  		// 1) Dump prefix
50  		writer.print(prefix);
51  
52  		// 2) JJT Name of the Node
53  		writer.print(node.toString());
54  
55  		//
56  		// If there are any additional details, then:
57  		// 1) A colon
58  		// 2) The Node.getImage() if it is non-empty
59  		// 3) Extras in parentheses
60  		//
61  
62  		// Standard image handling
63  		String image = node.getImage();
64  
65  		// Special image handling (e.g. Nodes with normally null images)
66  
67  		image = StringUtil.escapeWhitespace(image);
68  
69  		// Extras
70  		List<String> extras = new ArrayList<String>();
71  		Iterator<Attribute> iterator = node.getAttributeIterator();
72  		while (iterator.hasNext()) {
73  			Attribute attribute = iterator.next();
74  			extras.add(attribute.getName() + "=" + StringUtil.escapeWhitespace(attribute.getValue()));
75  		}
76  
77  		// Output image and extras
78  		if (image != null || !extras.isEmpty()) {
79  			writer.print(':');
80  			if (image != null) {
81  				writer.print(image);
82  			}
83  			for (String extra : extras) {
84  				writer.print('(');
85  				writer.print(extra);
86  				writer.print(')');
87  			}
88  		}
89  
90  		writer.println();
91  	}
92  }