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 10 import java.util.regex.Pattern; 11 import java.util.regex.Matcher; 12 13 /*** 14 * This rule finds the following: 15 * <p/> 16 * <pre> 17 * StringBuffer.append("c"); // appends a 18 * single character 19 * </pre> 20 * <p/> 21 * It is preferable to use StringBuffer.append('c'); // appends a single 22 * character Implementation of PMD RFE 1373863 23 */ 24 public class AppendCharacterWithChar extends AbstractRule { 25 26 private static final Pattern REGEX = Pattern.compile("\"[////]?[//s//S]\""); 27 28 public Object visit(ASTLiteral node, Object data) { 29 ASTBlockStatement bs = (ASTBlockStatement) node 30 .getFirstParentOfType(ASTBlockStatement.class); 31 if (bs == null) { 32 return data; 33 } 34 35 String str = node.getImage(); 36 if (str == null || str.length() < 3 || str.length() > 4) { 37 return data; 38 } 39 40 Matcher matcher = REGEX.matcher(str); 41 if (matcher.find()) { 42 if (!InefficientStringBuffering.isInStringBufferOperation(node, 8, "append")) { 43 return data; 44 } 45 addViolation(data, node); 46 } 47 return data; 48 } 49 }