Writing custom XPath rules for PMD

Most Java developers find static source code analysis tools very handy, PMD, CheckStyle, FindBugs being the most popular amongst them. But all of us, at some time or the other, realise that we need to have some project specific coding conventions being enforced on the developers. This article covers this need and would discuss about writing custom rules with PMD tool.

PMD comes with a set of handy rules, which more than often are sufficient for any project. In fact in many cases we would probably need to exclude some default rules being enforced, to avoid noise in the reports. However, in real life projects you also need some custom rules.

Though custom PMD rules can be written as Java code as well, this article talks about writing them using XPath queries, which is evidently an easier way to adopt. With XPath, we simply write a rule by specifying a code sample and an XPath query to verify that the violation is indeed detected. Of course PMD doesn’t apply the query on the Java code itself but rather on the Abstract Syntax Tree, which is a tree representation of the source code. More details on the AST can be found here.

Thankfully PMD also comes with a visual editor for writing the rules. This tool can be run using the designer.bat under /bin. If you are using Eclipse and have the PMD plugin installed then the designer is accessible under Eclipse Preferences > PMD. Lets now try writing a custom PMD rule. The particular rule we plan to write to enforce the use of StringBuilder instead of StringBuffer (where there are no concurrency issues, of course). For this we first write a code snippet, as follows, in the “Source code” box of the designer.

public class SomeClass {
//Consider using StringBuilder, if there
//are no concurrency issues expected
StringBuffer sb = new StringBuffer("c");

public void someMethod(){
//Some code here
StringBuffer sb = new StringBuffer("d");

The next task is to write the XPath expression. Before we do that, we press the “Go” button under “XPath Query” section first. This will generated the corresponding AST in the box and help us write the query well. And since we haven’t written any XPath query as of now, the result section below the “XPath Query” section says “XPath Query field is empty”. Now, we want to detect the presence of a StringBuffer variable, whether at class or method level. If you see the generated AST we can easily detect that the following XPath expression will find the matching lines. We use the @Image attribute to specify the name we want to detect.


Exporting XPath Rule

If we press the “Go” button again, the results of running the XPath query are displayed in the box below the “XPath Query” section. In our code we should get two matches, and we should see the exact matched strings if we click on the individual lines in the result Pane. We can refine the XPath query this way till we get the exact matches.

Lets now try to write another custom rule. This particular one will report a violation if the developer writes any non static method inside a Utility class. We don’t want the Utility class to be instantiated for its methods to be used. Here, we assume that all our Utility class names end with the word “Utils”. As we did last time, we first insert the following code snippet:

public class MyUtils {
//Any Utility class name ending with "Utils"
//to be regarded as a Utility class
public static void myStaticUtilMethod(String x){
//this is a static method as expected

public void myNonStaticUtilMethod(){
//this method should be static and violates our rule

The XPath query in this case, as follows, is quite straight forward. We are only checking for Classes (and skipping Interfaces) that end with the suffix “Utils” and then verify if there are any non-static methods in there. Click the Go button and it should detect a violation as our class does have a non-static method. To verify, change the method signature for myNonStaticUtilMethod() to make it static and press “Go” again. PMD should not report any violation now, confirming that our rule works.

and (ends-with(@Image, 'Utils'))
and (count(.//MethodDeclaration) > count(.//MethodDeclaration[@Static='true']))

The last step in getting our custom defined rules being used by PMD is to add them to a ruleset. Details on creating your own ruleset are provided here. The designer again will help you in creating the rule XMLs that you can easily copy paste in your ruleset file.

Lets create one for the last custom rule we created. To do this click Actions > Create Rule XML on the designer. You will get a pop-up which will ask you to specify the rule name and any description that goes along. For our ruleset we use the rule name as “OnlyStaticMethodsInUtilsClass” and the message text as “In Utility (ending with ‘Utils’) classes, all methods should be declared static.” which will show up as tool-tip on the IDE with violation report. We may also specify a description. Press “Create Rule XML” button and the designer will do so for you (see the screen grab below).

Exporting XPath Rule

Note that the designer specifies the class for the rule as “net.sourceforge.pmd.rules.XPathRule” on its own. The rule priority is specified at default value of 3, but you can change that. PMD users would know that priority figures of 1 = error, high priority, 2 = error, normal priority, 3 = warning, high priority, 4 = warning, normal priority and 5 = information.

Before PMD could be used with Eclipse it must be imported in your IDE. On Eclipse Preferences under “PMD” select “Import Rule Set”, browse to the ruleset file you saved the custom rules to and you would notice them being imported. Of course, we can use the ruleset from the command line as well from our build script.

With our custom rules, our favourite code quality check tool is now even more useful.


Author Spotlight WordPress Widget

Author Spotlight is a new WordPress widget recently created by me and added to the WordPress plugin repository. The Widget displays the profile of the author width the author website link and author profile photo on the Post (Single) page. It automatically detects the current author of the displayed Post, just drag and drop the widget on your Single page sidebar and you are done.

You may see the plugin in action right here on the sidebar on top-right of this page.

If you wish to display a custom photograph to go with the Author’s Profile you may install the User Photo. In absence of this plugin the ‘Author Spotlight” widget will fall-back to displaying the gravatar associated with the user.

Author Spotlight WordPress Widget

Update (Oct 2010): From V2.0 onwards this plugin also supports the excellent “Co-Authors Plus” plugin. If your blog posts have multiple authors we recommend using the co-authors plus plugin. When this plugin is used “Author Spotlight” will display all co-author profiles on the sidebar for the blog-post. Note that using either the “User Photo” or the  “Co-Author Plus” plugin is purely optional and our widget will work fine even without these plugins, but they are nice to have.


Click here to get the Author Spotlight plugin from WordPress.

Update (Sept 2012): From v3.0 onwards the plugin has added the feature to display Social icons with the profile. The Widget has been rewritten to the new WordPress Widget API and supplies sample CSS as well PHP code to add additional fields to User profile for Social web.

For installation instructions and details on the widget please visit the widget page on WordPress. If you face any issues with the plugin or have any suggestion/feature requests please do submit there at this place.

Disclaimer: The information provided on this page comes without any warranty whatsoever. Use it at your own risk.


The bechara who needs a Cinkara

Caution: This is a piece that I wrote in Nov 2000 for the light-hearted journal of my the then employer. Its full of usual jokes and PJs and probably doesn’t deserve a read, now. So why is it being carried here after 9 long years? Well because Yahoo geocities is shutting its shop and these articles had to be saved for eternity 🙂  Bear with me!

They say that life begins at forty. May be that’s true, but everything else starts to wear out or fall out. Why, I’m still too young to consider that, but God knows why, I feel like getting older than my age. Premature..err..ageing?

cinkaraSo you ask what evidence? Mere faazil dost..there are three signs of old age. The first is loss of memory, the other two..I forget. The case is not so serious though like some of my other friends who sometimes find themselves on the landing of the stairs and can’t remember whether they were on their way up or way down.

So what does a married man like me who took to his heel from his 6 years young ‘illustrious’ sales career grunting over in IT with colleagues fit to address him ‘uncle’. Uncle sam? Or the temptation to surf the Net (that ultimately lets you gain so much weight, because at almost every site they give you a “Cookie”) or was it the inability to decide regarding ‘com’ or zyada. The decision to jump in the IT-bandwagon, clever or not, apna raam thinks with Rayben clarity that philhaal work is a lot less fun-and fun is a lot more work (so now you know folks why I did a bunk from parties and never even stroll in the vicinity of Basketball stadium). Imman se, is umra main caution is the only thing I care to exercise.

Still people envy me? I could smell that! They feel that girls flock me. Trust this bhaisaab, one should start realizing that he is getting older when the girls at the office started confiding in him. And you thought.. shiv..shiv..shiv..

So back to the issue of me feeling that I have arrived the stage of taking longer to rest than to get tired. Boss, it’s been ages when I stopped growing at both ends (and begun to grow in the middle). Frankly I never have had this choice of two temptations and choosing the one that will get me home earlier. But you know which one I would have chosen. Reason perhaps, half of the guys who shake hand with me in morning will complain “Arre tu itna dheela kyon rehta hai yaar?”

May God forgive the nadaans for the folly of not their own because even I wake up with that morning-after feeling, while I didn’t do anything the night before. So that’s it guys! It’s a pity you are compelled to cope up with a veteran. But remember even Microsoft gives DOS with windows. When you can have faith in India winning a gold in next Olympics at least I can expect a bit for for now please note that tomorrow I may be late because meri kamar mein dard hai..Ouch..