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 = node.getFirstParentOfType(ASTBlockStatement.class);
30 if (bs == null) {
31 return data;
32 }
33
34 String str = node.getImage();
35 if (str == null || str.length() < 3 || str.length() > 4) {
36 return data;
37 }
38
39 Matcher matcher = REGEX.matcher(str);
40 if (matcher.find()) {
41 if (!InefficientStringBuffering.isInStringBufferOperation(node, 8, "append")) {
42 return data;
43 }
44 addViolation(data, node);
45 }
46 return data;
47 }
48 }