View Javadoc

    1   /***
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.cpd;
    5
    6   import net.sourceforge.pmd.PMD;
    7   import net.sourceforge.pmd.util.StringUtil;
    8
    9   import java.util.Iterator;
    10
    11  public class SimpleRenderer implements Renderer {
    12
    13  	private String separator;
    14  	private boolean trimLeadingWhitespace;
    15
    16  	public static final String defaultSeparator = "=====================================================================";
    17
    18  	public SimpleRenderer() {
    19  		this(false);
    20  	}
    21
    22  	public SimpleRenderer(boolean trimLeadingWhitespace) {
    23  		this(defaultSeparator);
    24          this.trimLeadingWhitespace = trimLeadingWhitespace;
    25  	}
    26
    27  	public SimpleRenderer(String theSeparator) {
    28  		separator = theSeparator;
    29  	}
    30
    31  	private void renderOn(StringBuffer rpt, Match match) {
    32
    33            rpt.append("Found a ").append(match.getLineCount()).append(" line (").append(match.getTokenCount()).append(" tokens) duplication in the following files: ").append(PMD.EOL);
    34
    35            TokenEntry mark;
    36            for (Iterator occurrences = match.iterator(); occurrences.hasNext();) {
    37                mark = (TokenEntry) occurrences.next();
    38                rpt.append("Starting at line ").append(mark.getBeginLine()).append(" of ").append(mark.getTokenSrcID()).append(PMD.EOL);
    39            }
    40
    41            rpt.append(PMD.EOL);	// add a line to separate the source from the desc above
    42
    43            String source = match.getSourceCodeSlice();
    44
    45            if (trimLeadingWhitespace) {
    46                String[] lines = source.split("[" + PMD.EOL + "]");
    47          	  int trimDepth = StringUtil.maxCommonLeadingWhitespaceForAll(lines);
    48          	  if (trimDepth > 0) {
    49          		  lines = StringUtil.trimStartOn(lines, trimDepth);
    50          	  }
    51          	  for (int i=0; i<lines.length; i++) {
    52          		  rpt.append(lines[i]).append(PMD.EOL);
    53          	  }
    54          	  return;
    55            }
    56
    57            rpt.append(source).append(PMD.EOL);
    58  	}
    59
    60
    61      public String render(Iterator matches) {
    62
    63          StringBuffer rpt = new StringBuffer(300);
    64
    65          if (matches.hasNext()) {
    66          	renderOn(rpt, (Match)matches.next());
    67          }
    68
    69          Match match;
    70          while (matches.hasNext()) {
    71              match = (Match) matches.next();
    72              rpt.append(separator).append(PMD.EOL);
    73              renderOn(rpt, match);
    74
    75          }
    76          return rpt.toString();
    77      }
    78  }