Custom PMD Rules
by Tom Copeland04/09/2003
A Review of PMD
A few weeks ago, O'Reilly Network ran an article on PMD, an open source, Java static-analysis tool sponsored under the umbrella of the Defense Advanced Research Projects Agency (DARPA) project "Cougaar." That article covered some of the basics of PMD--it's built on an Extended Backus Naur Format (EBNF) grammar, from which JavaCC generates a parser and JJTree generates an Java Abstract Syntax Tree (AST), and comes with a number of ready-to-run rules that you can run on your own source code. You can also write your own rules to enforce coding practices specific to your organization.
In this article, we'll take a closer look at the AST, how it is generated,
and some of its complexities. Then we'll write a custom PMD rule to find
the creation of Thread objects. We'll write this custom rule two
ways, first in the form of a Java class, and then in the form of an XPath
expression.
The AST
Recall from the first article that the Java AST is a tree structure that represents a chunk of Java source code. For example, here's a simple code snippet and the corresponding AST:
| Source Code | Abstract Syntax Tree |
|---|---|
|
|
Here we can see that the AST is a standard tree structure: a hierarchy of
nodes of various types. All of the node types and their valid children are
defined in the EBNF grammar file. For example, here's the definition of a
FieldDeclaration:
void FieldDeclaration() :
{
}
{
( "public" { ((AccessNode) jjtThis).setPublic( true ); }
| "protected" { ((AccessNode) jjtThis).setProtected( true ); }
| "private" { ((AccessNode) jjtThis).setPrivate( true ); }
| "static" { ((AccessNode) jjtThis).setStatic( true ); }
| "final" { ((AccessNode) jjtThis).setFinal( true ); }
| "transient" { ((AccessNode) jjtThis).setTransient( true ); }
| "volatile" { ((AccessNode) jjtThis).setVolatile( true ); } )*
Type() VariableDeclarator() ( "," VariableDeclarator() )* ";"
}
A FieldDeclaration is composed of a Type followed
by at least one VariableDeclarator; for example, int x,y,z =
0;. A FieldDeclaration may also be preceeded by a couple
of different modifiers, that is, Java keywords like transient or
private. Since these modifiers are separated by a pipe symbol and
followed by an asterisk, any number can appear in any order. All of these grammar
rules eventually can be traced back to the Java Language Specification (JLS) (see the References section below).
|
Related Reading
|
The grammar doesn't enforce nuances like "a field can't be both public
and private". That's the job of a semantic layer that would be built into
a full compiler such as javac or Jikes. PMD avoids
the job of validating modifiers--and the myriad other tasks a compiler must
perform--by assuming the code is compilable. If it's not, PMD will report an
error, skip that source file, and move on. After all, if a source file can't
even be compiled, there's not much use in trying to check it for unused code.
Looking closer at the grammar snippet above, we can also see some custom
actions that occur when a particular token is found. For example, when the
keyword public is found at the start of a
FieldDeclaration, the parser that JavaCC generates will call the
method setPublic(true) on the current node. The PMD grammar is
full of this sort of thing, and new actions are continually being added. By
the time a source code file makes it through the parser, a lot of work has been
done that makes rule writing much easier.
A Custom Rule
Now that we've reviewed the AST a bit more, let's write a custom PMD rule.
As mentioned before, we'll assume we're writing Enterprise Java Beans, so we
shouldn't be using some of the standard Java library classes. We shouldn't
open a FileInputStream, start a ServerSocket, or
instantiate a new Thread. To make sure our code is safe for use
inside of an EJB container, let's write a rule that checks for Thread
creation.
Writing a Custom Rule as a Java Class
Let's start by writing a Java class that traverses the AST. From the first
article, recall that JJTree generates AST classes that support the
Visitor pattern. Our class will register for callbacks when it
hits a certain type of AST node, then poke around the surrounding nodes to see
if it's found something interesting. Here's some boilerplace code:
// Extend AbstractRule to enable the Visitor pattern
// and get some handy utility methods
public class EmptyIfStmtRule extends AbstractRule {
}
If you look back up at the AST for that initial code snippet--Thread
t = new Thread();--you will find an AST type called an
AllocationExpression. Yup, that sounds like what we're looking
for: allocation of new Thread objects. Let's add in a hook to
notify us when it hits a new [something] node:
public class EmptyIfStmtRule extends AbstractRule {
// make sure we get a callback for any object creation expressions
public Object visit(ASTAllocationExpression node, Object data){
return super.visit(node, data);
}
}
We've put a super.visit(node,data) in there so the
Visitor will continue to visit children of this node. This lets
us catch allocations within allocations, i.e., new Foo(new
Thread()). Let's add in an if statement to exclude array
allocations:
public class EmptyIfStmtRule extends AbstractRule {
public Object visit(ASTAllocationExpression node, Object data){
// skip allocations of arrays and primitive types:
// new int[], new byte[], new Object[]
if ((node.jjtGetChild(0) instanceof ASTName) {
return super.visit(node, data);
}
}
}
We're not concerned about array allocations, not even
Thread-related allocations like Thread[] threads = new
Thread[];. Why not? Because instantiating an array of
Thread object references doesn't really create any new
Thread objects. It just creates the object references. We'll
focus on catching the actual creation of the Thread objects.
Finally, let's add in a check for the Thread name:
public class EmptyIfStmtRule extends AbstractRule {
public Object visit(ASTAllocationExpression node, Object data){
if ((node.jjtGetChild(0) instanceof ASTName &&
((ASTName)node.jjtGetChild(0)).getImage().equals("Thread")) {
// we've found one! Now we'll record a RuleViolation and move on
ctx.getReport().addRuleViolation(
createRuleViolation(ctx, node.getBeginLine()));
}
return super.visit(node, data);
}
}
That about wraps up the Java code. Back in the first article, we described a PMD ruleset and the XML rule definition. Here's a possible ruleset definition containing the rule we just wrote:
<?xml version="1.0"?>
<ruleset name="My company's EJB checker rules">
<description>
The Design Ruleset contains a collection of rules that find questionable designs.
</description>
<rule name="DontCreateThreadsRule"
message="Don't create threads, use the MyCompanyThreadService instead"
class="org.mycompany.util.pmd.DontCreateThreadsRule">
<description>
Don't create Threads, use the MyCompanyThreadService instead.
</description>
<example>
<![CDATA[
Thread t = new Thread(); // don't do this!
]]>
</example>
</rule>
</ruleset>
You can put this ruleset on your CLASSPATH or refer to it
directly, like this:
java net.sourceforge.pmd.PMD /path/to/src xml /path/to/ejbrules.xml
Writing a Custom Rule as an XPath Expression
Recently Daniel Sheppard enhanced PMD to allow rules to be written using XPath. We won't explain XPath completely here--it would require a large book--but generally speaking, XPath is a way of querying an XML document. You can write an XPath query to get a list of nodes that fit a certain pattern. For example, if you have an XML document with a list of departments and employees, you could write a simple XPath query that returns all the employees in a given department, and you wouldn't need to write DOM-traversal or SAX-listener code.
|
Related Reading XPath and XPointer |
That's all well and good, but how does querying XML documents relate to PMD?
Daniel noticed that an AST is a tree, just like an XML document. He downloaded
the Jaxen XPath engine and wrote a class called a
DocumentNavigator that allows Jaxen to traverse the AST. Jaxen
gets the XPath expression, evaluates it, applies it to the AST, and returns a
list of matching nodes to PMD. PMD creates RuleViolation objects
from the matching nodes and moves along to the next source file.
XPath is a new language, though, so why write PMD rules using XPath when you're already a whiz-bang Java programmer? The reason is that it's a whole lot easier to write simple rules using XPath. To illustrate, here's the "DontCreateThreadsRule" written as an XPath expression:
//AllocationExpression[Name/@Image='Thread'][not(ArrayDimsAndInits)]
Concise, eh? There's no Java class to track--you don't have to compile
anything or put anything else on your CLASSPATH. Just add the
XPath expression to your rule definition like this:
<?xml version="1.0"?>
<ruleset name="My company's EJB checker rules">
<description>
The Design Ruleset contains a collection of rules that find questionable designs.
</description>
<rule name="DontCreateThreadsRule"
message="Don't create threads, use the MyCompanyThreadService instead"
class="org.mycompany.util.pmd.DontCreateThreadsRule">
<description>
Don't create Threads, use the MyCompanyThreadService instead.
</description>
<properties>
<property name="xpath">
<value>
<![CDATA[
//AllocationExpression[Name/@Image='Thread'][not(ArrayDimsAndInits)]>
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
Thread t = new Thread(); // don't do this!
]]>
</example>
</rule>
</ruleset>
Refer to the rule as usual to run it on your source code.
You can learn a lot about XPath by looking at how the built-in PMD rules
identify nodes, and you can also try out new XPath expressions using a PMD
utility called the ASTViewer. Run this utility by executing the
astviewer.bat or astviewer.sh scripts in the
etc/ directory of the PMD distribution. It will bring up a window
that looks like Figure 1. Type some code into the left-hand panel, put an
XPath expression in the text field, click the "Go" button at the
bottom of the window, and the other panels will be populated with the AST and
the results of the XPath query.

Figure 1. Screenshot of ASTViewer
When should you use XPath to write a PMD rule? My initial thought is, "Anytime you can." I think that you'll find that many simple rules can be
written using XPath, especially those that are checking for braces or a
particular name. For example, almost all of the rules in the PMD basic ruleset
and braces ruleset are now written as very short, concise XPath expressions.
The more complicated rules--primarily those dealing with the symbol table--are probably still easiest to write in Java. We'll see, though. At some point
we may even wrap the symbol table in a DocumentNavigator.
Future Plans
There's still a lot of work to do on PMD. Now that this XPath infrastructure is in place, it might be possible to write an interactive rule editor. Ideally, you could open a GUI, type in a code snippet, select certain AST nodes, and an XPath expression that finds those nodes would be generated for you. PMD can always use more rules, of course. Currently, there are over 40 feature requests on the web site just waiting for someone to implement them. Also, PMD has a pretty weak symbol table, so it occasionally picks up a false positive. There's plenty of room for contributors to jump in and improve the code.
Conclusion
This article has presented a more in-depth look at the Java AST and how it's
defined. We've written a PMD rule that checks for Thread creation
using two techniques--a Java class and an XPath query. Give PMD a try and
see what it finds in your code today!
Credits
Thanks to the Cougaar program and DARPA for supporting PMD. Thanks to Dan Sheppard for writing the XPath integration. Thanks also to the many other contributors without whom PMD would be a much less useful utility.
References
- PMD home page
- Jaxen home page
- DARPA home page
- Cougaar home page
- Java Language Specification
- W3C XQuery/XPath home page
- JavaCC/JJTree home page
Tom Copeland started programming on a TRS-80 Model III, but demand for that skill has waned and he now programs mostly in Java and Ruby.
Return to ONJava.com.
Showing messages 1 through 40 of 40.
-
PMD 3.7
2006-08-01 03:02:01 Selvameena [Reply | View]
Hi,
We are using PMD1.2.1 in our project. Can you please confirm whether PMD 3.7 will work with WSAD 5.1?
Thanks,
Meena
-
Integrating customized rules in Eclipse
2006-05-23 05:18:22 Achelis [Reply | View]
Hi,
I created some rules using java and integrated into eclipse by importing the ruleset(my customized rules-xml) file and the rules got activated in my workspace.
The problem is for every new workspace i have to import the ruleset file. Is there any way to integrate the customized rules so that it is activated for all the workspaces i create.
Thank u in advance -
Integrating customized rules in Eclipse
2006-05-23 09:32:25 tcopeland [Reply | View]
Hi Achelis -
Hm, I'm not too familiar with the Eclipse plugin, so you may want to post this question on the PMD forums here:
http://sourceforge.net/forum/forum.php?forum_id=188192
More folks who use that plugin hang out thereabouts....
Yours,
tom
Using PMD? Get the book! http://pmdapplied.com/
-
Null check for an object
2006-03-21 22:45:33 PravinD [Reply | View]
please help me in writing the rule for the following scenario:
Before invoking any method of an object, a null check should be done.
Eg:
String str1 = null;
String str2 = "ASP";
str2 = str1.toUpperCase(); // Which will throw NullPointerException.
So I have to ensure that this line is in the if check. Like,
String str1 = null;
String str2 = "ASP";
if(str1 != null)
{
str2 = str1.toUpperCase();
}
Any help would be appreciated. Which would be better a Java rule or XPATH rule?
Thanks,
Meena -
Null check for an object
2006-03-23 05:47:29 tcopeland [Reply | View]
Hi Meena -
These are a good question... would you mind posting them to the PMD "Open Discussion" forum?
http://sourceforge.net/forum/forum.php?forum_id=188192
That way more folks will see your questions and be able to comment. Thanks!
Yours,
Tom
Using PMD? Get the book! http://pmdapplied.com/
-
Null check for an object
2006-03-21 22:15:56 PravinD [Reply | View]
please help me in writing the rule for the following scenario:
Before invoking any method of an object, a null check should be done.
Eg:
String str1 = null;
String str2 = "ASP";
str2 = str1.toUpperCase(); // Which will throw NullPointerException.
So I have to ensure that this line is in the if check. Like,
String str1 = null;
String str2 = "ASP";
if(str1 != null)
{
str2 = str1.toUpperCase();
}
Any help would be appreciated. Which would be better a Java rule or XPATH rule?
-
Help about Custom rule
2006-01-23 22:22:57 ShahzadRaja [Reply | View]
I want that each Collection(say List) defined at class level must be initialized in Constructor, how can i write a XPath rule for this purpose.
Thanks inAdvance.
-
how to run POI in java
2006-01-02 01:42:39 kalaisai [Reply | View]
hai all,
plz any one give me suggestion.i knoe JSF.but they asked me put one example program in POI.but i dont know that.plz give me suggestion how to use that and what are the files needed.actualy my work assigned z how to convert xml file to xls file using POI.plz do so help me.
thanks in advance.
-
problem with pmd 3.4
2005-12-20 07:42:31 nicolasGrossi [Reply | View]
People:
I had a set of pmd rules that i run agaist my project
sources. This task is performed by one script (.bat), this script works
fine with pmd-3-3.jar and doesn't work with pmd-3-4.jar. When I run this
script with 3.4 I get this exception:
Exception in thread "main" java.lang.NoSuchMethodError:
net.sourceforge.pmd.rule
s.BusinessDontThrowingCatchRule.createRuleViolation(Lnet/sourceforge/pmd/RuleCon
text;Lnet/sourceforge/pmd/ast/SimpleNode;)Lnet/sourceforge/pmd/RuleViolation;
at
net.sourceforge.pmd.rules.BusinessDontThrowingCatchRule.visit(Busines
sDontThrowingCatchRule.java:28)
at
net.sourceforge.pmd.ast.ASTCatchStatement.jjtAccept(ASTCatchStatement
.java:17)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:442)
at
net.sourceforge.pmd.ast.ASTTryStatement.jjtAccept(ASTTryStatement.jav
a:21)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:358)
at
net.sourceforge.pmd.ast.ASTStatement.jjtAccept(ASTStatement.java:19)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:370)
at
net.sourceforge.pmd.ast.ASTBlockStatement.jjtAccept(ASTBlockStatement
.java:19)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:366)
at net.sourceforge.pmd.ast.ASTBlock.jjtAccept(ASTBlock.java:19)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:358)
at
net.sourceforge.pmd.ast.ASTStatement.jjtAccept(ASTStatement.java:19)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:406)
at
net.sourceforge.pmd.ast.ASTForStatement.jjtAccept(ASTForStatement.jav
a:19)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:358)
at
net.sourceforge.pmd.ast.ASTStatement.jjtAccept(ASTStatement.java:19)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:370)
at
net.sourceforge.pmd.ast.ASTBlockStatement.jjtAccept(ASTBlockStatement
.java:19)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:366)
at net.sourceforge.pmd.ast.ASTBlock.jjtAccept(ASTBlock.java:19)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:186)
at
net.sourceforge.pmd.ast.ASTMethodDeclaration.jjtAccept(ASTMethodDecla
ration.java:18)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:47)
at
net.sourceforge.pmd.ast.ASTClassOrInterfaceBodyDeclaration.jjtAccept(
ASTClassOrInterfaceBodyDeclaration.java:32)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:43)
at
net.sourceforge.pmd.ast.ASTClassOrInterfaceBody.jjtAccept(ASTClassOrI
nterfaceBody.java:17)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:19)
at
net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration.jjtAccept(ASTC
lassOrInterfaceDeclaration.java:16)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:159)
at
net.sourceforge.pmd.ast.ASTTypeDeclaration.jjtAccept(ASTTypeDeclarati
on.java:32)
at
net.sourceforge.pmd.ast.SimpleNode.childrenAccept(SimpleNode.java:266
)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:6)
at
net.sourceforge.pmd.ast.JavaParserVisitorAdapter.visit(JavaParserVisi
torAdapter.java:135)
at net.sourceforge.pmd.AbstractRule.visitAll(AbstractRule.java:182)
at net.sourceforge.pmd.AbstractRule.apply(AbstractRule.java:143)
at net.sourceforge.pmd.RuleSet.apply(RuleSet.java:91)
at net.sourceforge.pmd.PMD.processFile(PMD.java:75)
at net.sourceforge.pmd.PMD.processFile(PMD.java:98)
at net.sourceforge.pmd.PMD.main(PMD.java:170)
any ideas?
thanks in advance
cheers
nico
-
Rule to search for a particular word in a java file.
2005-06-22 08:28:44 Aarts [Reply | View]
Hi friends,
Gud Day to u all.
Can I have the XPATH code,to be used in PMD, to search for a particular word in a java file, even if it is commented, or inside a loop statement ,etc. -
Rule to search for a particular word in a java file.
2005-06-22 15:23:26 tcopeland [Reply | View]
Hi Aarts -
Hm, I'm not sure if PMD will be the best tool for you in this regard, since it discards comments.
However, perhaps the Unix utility "grep" would work for you... it can search files with regular expressions, report the surrounding context for each occurrence, and so forth.
Yours,
Tom -
Rule to search for a particular word in a java file.
2005-07-05 06:00:05 Aarts [Reply | View]
Hi Tom,
Thanks for responding.
I guess ASTName searches every word in the code.So using that i was able to get my issue resolved.
So I just thought of sharing it with u.
Thanks again.
-
Few More Rules Pls
2005-04-11 02:40:09 PravinD [Reply | View]
Hey Tom,
Hope you doing good. I actually need your help to write a couple of more rules using XPath. I am not able to get them working rite. The following are the conditions that I want to check using XPath rules:
1) Rule that checks for open ResultSets, Statements, PreparedStatements and also ensures that these are closed only in the finally block.
2) Rule to ensure rollback statements are surrounded in a try/catch block.
3) Rule to check Naiming Conventions for PreparedStatement,Statement,ResultSet,CallableStatement. ie. Prepared Statements should start only with the letters 'pstmt'etc. (I have written a rule for this already and it works fine. So you might want to skip this)
4) Rule to check the length of variables such that it does not exceed 25 characters.
Kindly give me the rules if you can.
Cheers,
Pravin. D
-
Few More Rules Pls
2005-04-11 06:05:45 tcopeland [Reply | View]
Hi Pravin -
Cool, let me post an answer to your post over on the PMD forums:
http://sourceforge.net/forum/forum.php?thread_id=1264379&forum_id=188192
Yours,
Tom -
Null check for an object
2006-03-21 23:04:26 PravinD [Reply | View]
please help me in writing the rule for the following scenario:
Before invoking any method of an object, a null check should be done.
Eg:
String str1 = null;
String str2 = "ASP";
str2 = str1.toUpperCase(); // Which will throw NullPointerException.
So I have to ensure that this line is in the if check. Like,
String str1 = null;
String str2 = "ASP";
if(str1 != null)
{
str2 = str1.toUpperCase();
}
Any help would be appreciated. Which would be better a Java rule or XPATH rule?
-
XPath rule to close JDBC resources
2005-02-28 04:31:29 PravinD [Reply | View]
Hello,
I am attempting to create a XPath rule that detects JDBC resources and pops an error if they are not closed inside the finally block. This rule should take care of all objects like resultsets, statements, preparedstatements, connection objects. For starters I would like to check for connection objects alone. If anyone has written such a rule or knows how the rule should be then please post the rule. Thanks in advance.
Pravin. D
P.S: Is it possible to write such a rule using XPath? -
XPath rule to close JDBC resources
2005-02-28 06:06:37 tcopeland [Reply | View]
Hi Pravin -
Cool, I saw you copied this post over here as we discussed:
http://sourceforge.net/forum/forum.php?thread_id=1238765&forum_id=188192
so we'll chat over there...
Yours,
Tom -
XPath rule to close JDBC resources
2005-03-01 04:38:51 PravinD [Reply | View]
Tom,
I saw your reply in the sourceforge.net forum and I went through teh links you had given me there. However, I do not find adequate info on how to include this Close Connection rule into WSAD 5.0. Could you please tell me how I enable the design ruleset in WSAD 5.0?
Regards,
Pravin. D
P.S: Sorry to be eating up your time! :-) -
XPath rule to close JDBC resources
2005-03-01 06:02:47 tcopeland [Reply | View]
Hi Pravin -
> how I enable the design ruleset in WSAD 5.0?
Hm, you may want to ask that question on the PMD forums; I'm not a WSAD user, but folks there may be...
> Sorry to be eating up your time! :-)
No problemo! I'm sorry I can't give better answers to your questions; I usually run PMD from IntelliJ IDEA...
Yours,
Tom
-
PMD CUSTOM XPATH RULE
2005-02-24 01:18:45 PravinD [Reply | View]
I am attempting to create a couple of PMD rules.
1) To create a rule that checks for the occurences of String objects and throws a warning if the names of the objects do not start with the letters 'str'
2) To create a rule that checks for open connection objects and throws a warning if these objects remain unclosed.
Can someone help me on this or post the xpath rule for the same? -
PMD CUSTOM XPATH RULE
2005-02-24 06:09:36 tcopeland [Reply | View]
Hi PravinD -
Cool, OK, let's see:
> occurences of String objects and throws a
> warning if the names of the objects do not
> start with the letters 'str'
Hm. The XPath rule below will catch field declarations of Strings that don't start with "str":
//FieldDeclaration
[
Type/Name[@Image='String']
and not(starts-with(VariableDeclarator/VariableDeclaratorId/@Image, 'str'))
]
and you can write similar ones for parameters and local variable declarations.
> checks for open connection objects and
> throws a warning if these objects remain
> unclosed.
Check out the CloseConnection rule here:
http://pmd.sourceforge.net/rules/design.html
Yours,
Tom -
PMD CUSTOM XPATH RULE
2005-02-24 22:14:46 PravinD [Reply | View]
Hello Tom,
Thnaks for the timely help. I will use the rule and let you know. I have a few more queries coming up, so I am gonna keep you a busier man in teh forthcoming days. Just kidding. Thanks a lot mate.
Cheers,
Pravin. D
-
PMD CUSTOM XPATH RULE
2005-02-24 01:17:37 PravinD [Reply | View]
I am attempting to create a couple of PMD rules.
1) To create a rule that checks for the occurences of String objects and throws a warning if the names of the objects do not start with the letters 'str'
2) To create a rule that checks for open connection objects and throws a warning if these objects remain unclosed.
Can someone help me on this or post the xpath rule for the same?
-
AspectJ
2003-04-13 23:28:09 anonymous2 [Reply | View]
AspectJ seems like an easier way to do this. An article I read about it uses the same example of checking for threads in an EJB. The syntax is certainly lighter.
http://www.eclipse.org/aspectj/






When I tried to export rule sets, it always resulted to a blank xml file. I'm using
PMD 3.2.2 on Eclipse 3.2.
Any advice would be greatly appreciated. Thank you.