Replies: 2 comments 1 reply
-
When writing the rule in Java, you'll need to traverse the AST with java method calls manually. Your rule extends from This method has a first parameter the current node - in that case the catch statement. You can then ask the node for its immediate children ( If you look at the following complete java code sample in the designer: import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Foo {
private static final Logger logger = LoggerFactory.getLogger(Foo.class);
public void bar() {
try {
buzz();
} catch (Exception e) {
logger.error(e);
}
}
} you'll see, that the call to "logger.error" manifests itself as a node of the the "Name" - this corresponds to the java class node type So, you could manually call A complete rule class could look like this: package net.sourceforge.pmd.examples.java.rules;
import java.util.List;
import net.sourceforge.pmd.lang.java.ast.ASTArgumentList;
import net.sourceforge.pmd.lang.java.ast.ASTCatchStatement;
import net.sourceforge.pmd.lang.java.ast.ASTName;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
public class MyRule extends AbstractJavaRule {
@Override
public Object visit(ASTCatchStatement node, Object data) {
boolean found = false;
ASTVariableDeclaratorId exceptionId = node.getExceptionId();
List<ASTName> names = node.getBody().findDescendantsOfType(ASTName.class);
for (ASTName name : names) {
if (name.hasImageEqualTo("logger.error") && name.getFirstParentOfType(ASTPrimaryExpression.class) != null) {
ASTArgumentList argumentList = name.getFirstParentOfType(ASTPrimaryExpression.class).getFirstDescendantOfType(ASTArgumentList.class);
if (argumentList != null && argumentList.size() > 0) {
List<ASTName> refs = argumentList.findDescendantsOfType(ASTName.class);
for (ASTName ref : refs) {
if (ref.hasImageEqualTo(exceptionId.getName())) {
found = true;
}
}
}
}
}
if (!found) {
asCtx(data).addViolation(node);
}
return super.visit(node, data);
}
} |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot for this detailed explanation, can you please tell me what was your thought process behind writing this code, I don't know many of the methods and how to use them to write some complex rules in java. Any resources or topics I need to study for this? |
Beta Was this translation helpful? Give feedback.
-
Hi
I'm trying to implement new pmd rule where I need to check the very first statement after catch block should be log.error("msg"); if it's not there it should give violation something like this-
I was able to write this logic using XPath but I want to write it using java @oowekyala
Can you please help me how can I achieve this I'd be really grateful thank you !
Beta Was this translation helpful? Give feedback.
All reactions