user3280908
user3280908

Reputation: 162

How add custom rule in pmd and use it from terminal

I have written a custom rule in pmd and written the rule class.

The custom rule is:

<?xml version="1.0"?>
<ruleset name="My custom rules"
 xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0              http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
    <rule name="WhileLoopsMustUseBracesRule"
     message="Avoid using 'while' statements without curly braces"
     class="WhileLoopsMustUseBracesRule">
        <description>
            Avoid using 'while' statements without using curly braces
        </description>
        <priority>3</priority>
        <example>
            <![CDATA[
                public void doSomething() {
                    while (true)
                    x++;
                }
            ]]>
        </example>
    </rule>
</ruleset>

and the class is:

import net.sourceforge.pmd.lang.java.rule.*;
import net.sourceforge.pmd.lang.java.ast.*;
public class WhileLoopsMustUseBracesRule extends AbstractJavaRule {
    public Object visit(ASTWhileStatement node, Object data) {
        System.out.println("hello world");
        return data;
    }
}

Now when I type the command from the terminal

sh run.sh pmd -d /Users/sree/Documents/learning/programs/java xml /Users/sree/Desktop/customrule.xml 

I get this error:

Was passed main parameter 'xml' but no main parameter was defined

Now to include custom rule so that I can access it from the terminal and after bundling up both the rule and the ruleset.xml file in a jar file how to include it in the class path

NOTE: I am using a mac and not a Windows operating system

Upvotes: 4

Views: 1543

Answers (1)

oddi
oddi

Reputation: 91

I am using this:

./run.sh pmd -d /Users/ardaaslan/Documents/workspace/PMDRulesTest/src/AttributeTypeAndNameIsInconsistentTest.java -f text -R /Users/ardaaslan/Downloads/pmd-src-5.5.1/pmd-java/src/main/resources/rulesets/java/customrules.xml -version 1.7

After -d I give the directory of the custom rule code. Then I give the output format with -f which is text. Then the location of rule.xml.

The additional thing to do is to compile your source code with using pmd-bin's library as classpath

javac -cp /Users/ardaaslan/Downloads/pmd-bin-5.5.0/lib/\* AttributeTypeAndNameIsInconsistentRule.java

Then put compiled .class file to jar and move that jar under

pmd-bin-5.5.0/lib

for pmd to find your class file

After these you can try to execute run.sh again.

Upvotes: 1

Related Questions