View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.lang.java.rule;
    5
    6   import java.util.regex.Pattern;
    7
    8   import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
    9   import net.sourceforge.pmd.lang.java.rule.regex.RegexHelper;
    10  import net.sourceforge.pmd.lang.rule.properties.StringProperty;
    11
    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  //FUTURE This is not referenced by any RuleSet?
    20  public class GenericLiteralCheckerRule extends AbstractJavaRule {
    21
    22  	private Pattern pattern;
    23
    24  	private static final String PROPERTY_NAME = "regexPattern";
    25
    26  	private static final StringProperty REGEX_PROPERTY = new StringProperty(PROPERTY_NAME,"Regular expression","", 1.0f);
    27
    28  	public GenericLiteralCheckerRule() {
    29  	    definePropertyDescriptor(REGEX_PROPERTY);
    30  	}
    31
    32  	private void init() {
    33  		if (pattern == null) {
    34  			// Retrieve the regex pattern set by user
    35  			String stringPattern = super.getProperty(REGEX_PROPERTY);
    36  			// Compile the pattern only once
    37  			if ( stringPattern != null && stringPattern.length() > 0 ) {
    38  				pattern = Pattern.compile(stringPattern);
    39  			} else {
    40  				throw new IllegalArgumentException("Must provide a value for the '" + PROPERTY_NAME + "' property.");
    41  			}
    42  		}
    43  	}
    44
    45  	/**
    46  	 * This method checks if the Literal matches the pattern. If it does, a violation is logged.
    47  	 */
    48  	@Override
    49  	public Object visit(ASTLiteral node, Object data) {
    50  		init();
    51  		String image = node.getImage();
    52  		if ( image != null && image.length() > 0 && RegexHelper.isMatch(this.pattern,image) ) {
    53  			addViolation(data, node);
    54  		}
    55  		return data;
    56  	}
    57  }