View Javadoc

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