01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.rules.strings;
04:
05: import net.sourceforge.pmd.AbstractRule;
06: import net.sourceforge.pmd.ast.ASTBlockStatement;
07: import net.sourceforge.pmd.ast.ASTLiteral;
08:
09: import java.util.regex.Pattern;
10: import java.util.regex.Matcher;
11:
12: /**
13: * This rule finds the following:
14: * <p/>
15: * <pre>
16: * StringBuffer.append("c"); // appends a
17: * single character
18: * </pre>
19: * <p/>
20: * It is preferable to use StringBuffer.append('c'); // appends a single
21: * character Implementation of PMD RFE 1373863
22: */
23: public class AppendCharacterWithChar extends AbstractRule {
24:
25: private static final Pattern REGEX = Pattern
26: .compile("\"[\\\\]?[\\s\\S]\"");
27:
28: public Object visit(ASTLiteral node, Object data) {
29: ASTBlockStatement bs = 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(
43: node, 8, "append")) {
44: return data;
45: }
46: addViolation(data, node);
47: }
48: return data;
49: }
50: }
|