How to find Particular word from Java class using PMD Rule
A source code analyzer
Brought to you by:
adangel,
juansotuyo
HI All,
I am new to this PMD customization and i am trying to customize PMD rules and i want find a word from my Java class (Most of the developers will use same word i.e hardcoded). kindly suggest me to write a class.Herewith i have attached a class and rules.
public Object visit(ASTStatement node, Object data) {
// System.out.println("node.getImage()"+node.getImage().toString());
}
public Object visit(ASTAllocationExpression node, Object data){
System.out.println("node.getImage()");
if ((node.jjtGetChild(0) instanceof ASTName) &&
((ASTName)node.jjtGetChild(0)).getImage().equals("CheckCode")) {
// we've found one! Now we'll record a RuleViolation and move on
addViolation(data, node);
}
return super.visit(node, data);
}
Rule:
<rule name="Should not Use CheckCode" message="Client Side Developer Should not Use CheckCode" class="net.sourceforge.pmd.lang.rule.WhileLoopsMustUseBracesRule">
<description>
If we Use Checkcode in Client Side then we will get Performace Problem
</description>
<priority>1</priority>
<example>
<![CDATA[
public class SomeClass {
public void someMethod(){
String query="select distinct * from units where unit='"+txtunitcode.getText().trim()+"' and status='A'";
String che = chek.CheckCode(query);
}
]]>
</example>
</rule>
I have used ASTName to find my word.
public Object visit(ASTName node, Object data) {
String name=node.getImage();
if(name.contains("CheckCode")){
System.out.println("CheckCode"+name);
addViolation(data, node);
}
return data;
}
I'd suggest looking into the following docs: http://pmd.sourceforge.net/pmd-5.1.2/howtowritearule.html and http://pmd.sourceforge.net/pmd-5.1.2/xpathruletutorial.html
For the ruleset, see: http://pmd.sourceforge.net/pmd-5.1.2/howtomakearuleset.html
You'll need to reference your class with the
class
attribute ofrule
and not ...WhileLoopsMustUseBracesRuleIt's also worth looking into the AST with the Designer: Start the designer via
bin/run.sh designer
(or under Windows withdesigner.bat
), add your sample java code into the left textarea and click "go". You should see then in the lower area the AST tree and can figure out, which node you need to look at.It might be easier to implement your use-case as a XPath rule, e.g.
//PrimaryExpression[ends-with(PrimaryPrefix/Name/@Image, '.CheckCode')]