01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.rules;
04:
05: import java.util.regex.Pattern;
06:
07: import net.sourceforge.pmd.AbstractJavaRule;
08: import net.sourceforge.pmd.PropertyDescriptor;
09: import net.sourceforge.pmd.ast.ASTLiteral;
10: import net.sourceforge.pmd.properties.StringProperty;
11: import net.sourceforge.pmd.rules.regex.RegexHelper;
12:
13: /**
14: * This class allow to match a Literal (most likely a String) with a regex pattern.
15: * Obviously, there are many applications of it (such as basic.xml/AvoidUsingHardCodedIP).
16: *
17: * @author Romain PELISSE, belaran@gmail.com
18: */
19: public class GenericLiteralCheckerRule extends AbstractJavaRule {
20:
21: private static final String PROPERTY_NAME = "pattern";
22: private static final String DESCRIPTION = "Regular Expression";
23: private Pattern pattern;
24:
25: private void init() {
26: if (pattern == null) {
27: // Retrieve the regex pattern set by user
28: PropertyDescriptor property = new StringProperty(
29: PROPERTY_NAME, DESCRIPTION, "", 1.0f);
30: String stringPattern = super .getStringProperty(property);
31: // Compile the pattern only once
32: if (stringPattern != null && stringPattern.length() > 0) {
33: pattern = Pattern.compile(stringPattern);
34: } else {
35: throw new IllegalArgumentException(
36: "Must provide a value for the '"
37: + PROPERTY_NAME + "' property.");
38: }
39: }
40: }
41:
42: /**
43: * This method checks if the Literal matches the pattern. If it does, a violation is logged.
44: */
45: @Override
46: public Object visit(ASTLiteral node, Object data) {
47: init();
48: String image = node.getImage();
49: if (image != null && image.length() > 0
50: && RegexHelper.isMatch(this.pattern, image)) {
51: addViolation(data, node);
52: }
53: return data;
54: }
55: }
|