View Javadoc

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