DumpFacade.java
001 package net.sourceforge.pmd.lang.xml.ast;
002 
003 import java.io.IOException;
004 import java.io.PrintWriter;
005 import java.io.Writer;
006 import java.util.ArrayList;
007 import java.util.Iterator;
008 import java.util.List;
009 
010 import net.sourceforge.pmd.lang.ast.xpath.Attribute;
011 
012 public class DumpFacade {
013 
014     private PrintWriter writer;
015     private boolean recurse;
016 
017     public void initializeWith(Writer writer, String prefix, boolean recurse, XmlNode node) {
018   this.writer = (writer instanceof PrintWriter(PrintWriterwriter : new PrintWriter(writer);
019   this.recurse = recurse;
020   this.dump(node, prefix);
021   try {
022       writer.flush();
023   catch (IOException e) {
024       throw new RuntimeException("Problem flushing PrintWriter.", e);
025   }
026     }
027 
028     public Object visit(XmlNode node, Object data) {
029   dump(node, (Stringdata);
030   if (recurse) {
031       for (int i = 0; i < node.jjtGetNumChildren(); i++) {
032     visit((XmlNodenode.jjtGetChild(i), data + " ");
033       }
034       return data;
035   else {
036       return data;
037   }
038     }
039 
040     private void dump(XmlNode node, String prefix) {
041   //
042   // Dump format is generally composed of the following items...
043   //
044 
045   // 1) Dump prefix
046   writer.print(prefix);
047 
048   // 2) JJT Name of the Node
049   writer.print(node.toString());
050 
051   //
052   // If there are any additional details, then:
053   // 1) A colon
054   // 2) The Node.getImage() if it is non-empty
055   // 3) Extras in parentheses
056   //
057 
058   // Standard image handling
059   String image = node.getImage();
060 
061   // Special image handling (e.g. Nodes with normally null images)
062 
063   image = escape(image);
064 
065   // Extras
066   List<String> extras = new ArrayList<String>();
067   Iterator<Attribute> iterator = node.getAttributeIterator();
068   while (iterator.hasNext()) {
069       Attribute attribute = iterator.next();
070       extras.add(attribute.getName() "=" + escape(attribute.getValue()));
071   }
072 
073   // Output image and extras
074   if (image != null || !extras.isEmpty()) {
075       writer.print(":");
076       if (image != null) {
077     writer.print(image);
078       }
079       for (String extra : extras) {
080     writer.print("(");
081     writer.print(extra);
082     writer.print(")");
083       }
084   }
085 
086   writer.println();
087     }
088 
089     private static String escape(Object o) {
090   // Replace some whitespace characters so they are visually apparent.
091   if (o == null) {
092       return null;
093   }
094   String s = String.valueOf(o);
095   s = s.replace("\n""\\n");
096   s = s.replace("\r""\\r");
097   s = s.replace("\t""\\t");
098   return s;
099     }
100 }