View Javadoc

1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.rules.strings;
5   
6   import net.sourceforge.pmd.AbstractRule;
7   import net.sourceforge.pmd.ast.ASTBlockStatement;
8   import net.sourceforge.pmd.ast.ASTLiteral;
9   import org.apache.oro.text.perl.Perl5Util;
10  
11  /***
12   * This rule finds the following:
13   * <p/>
14   * <pre>
15   *         StringBuffer.append(&quot;c&quot;); // appends a
16   *         single character
17   * </pre>
18   * <p/>
19   * It is preferable to use StringBuffer.append('c'); // appends a single
20   * character Implementation of PMD RFE 1373863
21   */
22  public class AppendCharacterWithChar extends AbstractRule {
23  
24      private static final String REGEX = "/\"[////]?[//s//S]\"/i";
25  
26      public Object visit(ASTLiteral node, Object data) {
27          ASTBlockStatement bs = (ASTBlockStatement) node
28                  .getFirstParentOfType(ASTBlockStatement.class);
29          if (bs == null) {
30              return data;
31          }
32  
33          String str = node.getImage();
34          if (str == null || str.length() < 3 || str.length() > 4) {
35              return data;
36          }
37  
38          // see
39          // http://jakarta.apache.org/oro/api/org/apache/oro/text/regex/package-summary.html#package_description
40          Perl5Util regexp = new Perl5Util();
41          if (regexp.match(REGEX, str)) {
42              if (!InefficientStringBuffering.isInStringBufferAppend(node, 8)) {
43                  return data;
44              }
45              addViolation(data, node);
46          }
47          return data;
48      }
49  }