Help. I would like to sacrifice the reputation for a proper answer..
public class ParameterNameConvention extends AbstractJavaRule {
private final static String PATTERN = "[p][a-zA-Z]+";
public Object visit(ASTMethodDeclaration node, Object data) {
RuleContext result = (RuleContext) data;
String rulePattern = (!getStringProperty("rulePattern")
.equalsIgnoreCase("")) ? getStringProperty("rulePattern")
: PATTERN;
if (node.containsChildOfType(ASTFormalParameter.class)) {
Iterator iterator = node.findChildrenOfType(
ASTFormalParameter.class).iterator();
while (iterator.hasNext()) {
ASTFormalParameter element = (ASTFormalParameter) iterator
.next();
Iterator decIdIterator = element.findChildrenOfType(
ASTVariableDeclaratorId.class).iterator();
while (decIdIterator.hasNext()) {
ASTVariableDeclaratorId decElement = (ASTVariableDeclaratorId) decIdIterator
.next();
if (!decElement.getImage().matches(rulePattern)) {
result.getReport()
.addRuleViolation(
createRuleViolation(
this,
node.getBeginLine(),
"Parameter '"
+ decElement.getImage()
+ "' should match regular expression pattern '"
+ rulePattern + "'",
result));
}
}
}
}
return result;
}
}
However, 'creatRuleViolation' doesn't work. How to define it?
Here we go, I did a bit of research last night to help you out.
createRuleViolation()
is defined inAbstractRuleViolationFactory
as abstract and implemented in language specific factory sub-classes (eg:JavaRuleViolationFactory
), not directly available in Rule classes hierarchy.Instead use
addViolationWithMessage()
method that is inherited fromAbstractRule
viaAbstractJavaRule
. This method eventually calls the create method on appropriate factory at runtime.I tried your code with latest PMD version 5.0.3, and required few more tweaks other than the issue with
createRuleViolation()
method to get it working. Mainly to navigate from MethodDeclaration node to Parameter nodes, there could be a better way though, but it works now. I have modified the code based on the AST (abstract source tree).To test the rule on the same class, I named one parameter to satisfy the rule and one not to satisfy (
final ASTMethodDeclaration node, final Object pData
).The ruleset xml is
The result xml PMD generated is :
For more details on running PMD standalone from command line see the documentation on PMD website or there is loads available if you google around.
Hope this is helpful.