Monday, June 30, 2014

Can main method be overloaded and overridden in Java?


Can main method be overloaded and overridden in Java?

So, answers are very simple...

Overloading>>>>>>> YES

You can overload the main method. but JVM only understands public static void main(String ar[]) {,....} and looks for the main method as with given signature to start the app.

For example:

public class OverloadingMainTest{
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

      public static void main(String... args) {
System.out.println("String... args >>>> VARARGS");
}

   public static void main(Integer[] args) {
        System.out.println("main(Integer[] args)");
    }

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}


Here, i have overloaded the main method with diff. -2 types. but when you run the main method it will print:
          main(String[] args)

So, Again you can overload main method with diff.-2 signatures but it will be a simple     method only ... and it will never execute like actual main method>>

public static void main(String[] args) {
        System.out.println("main(String[] args)");
 }


Overriding>> NO

Overriding of methods can be done for only methods which belongs to an object not class, i mean to say that static methods/static variable etc. are not part of an object. and cant be overridden.

And if you try to do something like given below... you are not overriding it actually. You are hiding it. so when you run the main method of subclass JVM will not be able to load it.


public class Test{
public static void main(String[] args) {
System.out.println("Hello main");
}
}

public class Test1 extends Test{
public static void main(String[] args) {
System.out.println("Hello main test1");
}
}


And yeah if the main method which you have declared is itself not a static method then the overriding concept will be applied.


Friday, June 20, 2014

Data access object unit test using Mokito framework to follow TDD approach

Data access object unit test using Mokito framework to follow TDD approach:

Download MockIto from: 
https://code.google.com/p/mockito/downloads/detail?name=mockito-1.9.5.zip&can=2&q


UserInfoDao .java:

package com.dao;

import java.sql.SQLException;
import com.model.UserModel;

public interface UserInfoDao {
String registerUser(UserModel userInfo) throws SQLException;

}


UserInfoDaoImpl.java:

package com.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.dao.UserInfoDao;
import com.model.UserModel;

public class UserInfoDaoImpl implements UserInfoDao {

private Connection connection;

public UserInfoDaoImpl(Connection connection) {
super();
this.connection = connection;

}

@Override
public String registerUser(UserModel userInfo) throws SQLException {
System.out.println("dao_registerUser(..) invoked..");
String queryResp = "Failed";
PreparedStatement preStmt = connection
.prepareStatement("insert into user_info(userName,password,firstName,lastName) values (?,?,?,?)");
preStmt.setString(1, userInfo.getUserName());
preStmt.setString(2, userInfo.getPassword());
preStmt.setString(3, userInfo.getFirstName());
preStmt.setString(4, userInfo.getLastName());

if (preStmt.executeUpdate() > 0) {
queryResp = "Success";
}
return queryResp;
}

public Connection getConnection() {
return connection;
}

public void setConnection(Connection connection) {
this.connection = connection;
}
}


UserModel.java:

package com.model;

public class UserModel {
private String userName;
private String password;
private String firstName;
private String lastName;
private int id;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@Override
public String toString() {
return "UserModel [userName=" + userName + ", password=" + password
+ ", firstName=" + firstName + ", lastName=" + lastName
+ ", id=" + id + "]";
}

}


UserInfoService.java:

package com.service;

import com.model.UserModel;

public interface UserInfoService {
String registerUser(UserModel userInfo) throws Exception;
}

UserInfoServiceImpl.java:

package com.service.impl;

import com.dao.UserInfoDao;
import com.model.UserModel;
import com.service.UserInfoService;

public class UserInfoServiceImpl implements UserInfoService {

private UserInfoDao userInfoDao;

public UserInfoServiceImpl(UserInfoDao userInfoDao) {
super();
this.userInfoDao = userInfoDao;
}

@Override
public String registerUser(UserModel userInfo) throws Exception {
System.out.println("service_registerUser(..) invoked..");
return getUserInfoDao().registerUser(userInfo);
}

public UserInfoDao getUserInfoDao() {
return userInfoDao;
}

public void setUserInfoDao(UserInfoDao userInfoDao) {
this.userInfoDao = userInfoDao;
}
}

DaoClient:

package com.client;

import java.sql.Connection;

import com.dao.UserInfoDao;
import com.dao.impl.UserInfoDaoImpl;
import com.model.UserModel;
import com.service.UserInfoService;
import com.service.impl.UserInfoServiceImpl;
import com.util.DBMockUtils;

public class DaoClient {
public static void main(String[] args) throws Exception {
UserModel userInfo = new UserModel();
userInfo.setFirstName("Abhinav");
userInfo.setLastName("Mishra");
userInfo.setPassword("admin");
userInfo.setUserName("admin");
Connection conn = DBMockUtils.getConnection("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/users", "root", "root");
UserInfoDao dao= new UserInfoDaoImpl(conn);

UserInfoService userServ=new UserInfoServiceImpl(dao);

System.out.println(userServ.registerUser(userInfo));
}
}


UserServiceTest : JUnit Test case.

package com.service.test;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import com.dao.UserInfoDao;
import com.model.UserModel;
import com.service.UserInfoService;
import com.service.impl.UserInfoServiceImpl;

public class UserServiceTest extends TestCase {

private UserInfoService userInfoService;
private UserModel userInfo;

@Mock
private UserInfoDao userInfoDao;

@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}

@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code
System.out.println("@AfterClass - oneTimeTearDown");
}

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
userInfoService = new UserInfoServiceImpl(userInfoDao);
userInfo = new UserModel();
userInfo.setFirstName("Abhinav");
userInfo.setLastName("Mishra");
userInfo.setPassword("admin");
userInfo.setUserName("admin");

System.out.println("@Before - setUp");
}

@After
public void tearDown() {
System.out.println("@After - tearDown");
}

@Test
public void testUserInfoSuccess() throws Exception{
System.out.println("@Test testUserInfoSuccess()...");

Mockito.when(userInfoDao.registerUser(userInfo)).thenReturn("Success");

final String status = userInfoService.registerUser(userInfo);
System.out.println("Expected Result: " + status);

// Verify state
assertEquals("Success", status);

// Verify that method invoked actually or not
Mockito.verify(userInfoDao).registerUser(userInfo);

// verify the object with no. of times invocation
Mockito.verify(userInfoDao, Mockito.timeout(1)).registerUser(userInfo);
}

@Test
public void testUserInfoFailure() throws Exception {
System.out.println("@Test testUserInfoFailure()...");

Mockito.when(userInfoDao.registerUser(userInfo)).thenReturn("Failed");

final String status = userInfoService.registerUser(userInfo);
System.out.println("Expected Result: " + status);

// Verify state
assertEquals("Failed", status);

// Verify that method invoked actually or not
Mockito.verify(userInfoDao).registerUser(userInfo);

// verify the object with no. of times invocation
Mockito.verify(userInfoDao, Mockito.timeout(1)).registerUser(userInfo);

}
}


Output:


@Before - setUp

@Test testUserInfoSuccess()...

service_registerUser(..) invoked..

Expected Result: Success

@After - tearDown

@Before - setUp

@Test testUserInfoFailure()...

service_registerUser(..) invoked..

Expected Result: Failed

@After - tearDown





Testing servlets using JUNIT and MockIto

Testing Servlets using JUNIT and Mockito:


Mockito framework:



I have used version 1.10.19 of mockito-all for this post.

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
    <scope>test</scope>
</dependency>

Limitations:

1- Final,anonymous and primitive types can not be mocked.
2- Methods with return type "void"called from within doPost or doGet methods can not be mocked.

Servlet:

package com.github.abhinavmishra14.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * The Class Login.
 */
public class Login extends HttpServlet {
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 38044879686270933L;

	/**
	 * Instantiates a new login.
	 */
	public Login() {
		super();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException// called once servlet loads
	{
		System.out.println("Login Init called...");
		try {
			super.init(config);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#destroy()
	 */
	@Override
	public void destroy()// called just before servlet unload
	{
		System.out.println("Login Destroyed...");
		super.destroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		System.out.println("Login doPost...");
		String name = req.getParameter("user");
		String pwd = req.getParameter("password");
		String rememberMe = req.getParameter("rememberMe");
		System.out.println("User: " + name + " | password: " + pwd);
		if (name.equals("abhinav") && pwd.equals("passw0rd")) {
			HttpSession session = req.getSession();
			session.setAttribute("user", name);
			Cookie ck1 = new Cookie("user", name);
			Cookie ck2 = new Cookie("pwd", pwd);
			res.addCookie(ck1);
			res.addCookie(ck2);
			if (rememberMe != null && rememberMe != "") {
				Cookie ck3 = new Cookie("rememberMe", rememberMe);
				res.addCookie(ck3);
			}
		}

		PrintWriter out = res.getWriter();
		out.write("Login successfull...");
		// Dispatching request
		RequestDispatcher rd = req.getRequestDispatcher("/HelloWorld.do");
		rd.forward(req, res);
	}
}



TestCase:

package com.github.abhinavmishra14.demo.servlet.test;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import junit.framework.TestCase;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import com.github.abhinavmishra14.demo.servlet.Login;

public class LoginServletTest extends TestCase {

	@Mock
	HttpServletRequest request;
	@Mock
	HttpServletResponse response;
	@Mock
	HttpSession session;

	@Mock
	RequestDispatcher rd;

	@Before
	protected void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void test() throws Exception {
		when(request.getParameter("user")).thenReturn("abhinav");
		when(request.getParameter("password")).thenReturn("passw0rd");
		when(request.getParameter("rememberMe")).thenReturn("Y");
		when(request.getSession()).thenReturn(session);
		when(request.getRequestDispatcher("/HelloWorld.do")).thenReturn(rd);

		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);

		when(response.getWriter()).thenReturn(pw);

		new Login().doPost(request, response);

		// Verify the session attribute value
		verify(session).setAttribute("user", "abhinav");

		verify(rd).forward(request, response);

		String result = sw.getBuffer().toString().trim();

		System.out.println("Result: " + result);

		assertEquals("Login successfull...", result);
	}
}


Output:

Login doPost...
User: abhinav | password: passw0rd
Result: Login successfull...



Tuesday, June 17, 2014

Implement Java Code Coverage and Junit test cases using Ant

Automating Java Code Coverage and JUnit:

Following jar files are required JUnit:

hamcrest-core-1.3.jar
junit-4.7.jar

Following jar files are required Java Code coverage:

jacocoant.jar


Build Properties:

src.dir=src
test.dir=test
project.name=TestApp
build.dir=appbuild
test.reports=test-reports
coverage.report=coverage-reports

Ant Targets:

<project name="TestApp" default="echo-properties" basedir="." xmlns:jacoco="antlib:org.jacoco.ant">

<property file="build.properties" />

<!--Creating the required directories for test cases-->
<target name="test-init" description="Creates the required directories for test case reports">
<echo>******Cleaning the ${test.reports}******</echo>
<delete dir="${test.reports}" />
<echo>******Creating the required directories for test reports******</echo>
<mkdir dir="${test.reports}" />
</target>
<target name="execute-junit" depends="compile,test-init">
<junit fork="true" printsummary="on" haltonfailure="yes" description="Junit test cases TestApp">
<classpath refid="classpath"/>
<classpath>
       <pathelement location="${build.dir}/WEB-INF/classes"/> 
       <pathelement location="${build.dir}/WEB-INF/test"/> 
       <pathelement location="${build.dir}/WEB-INF/config"/> 
</classpath>

<!--Save test result in xml format-->
    <formatter type="xml"/>
 
<!--Single test case->
     <!--<test name="com.AuthenticationServiceTest"
                                 haltonfailure="no" outfile="unittest_result"/>-->

<!--Batch test run-->
<batchtest fork="yes" todir="${test.reports}">
       <fileset dir="${build.dir}/WEB-INF/test">
        <include name="**/*TestSuite.class"/>
        <exclude name="**/*Test.class"/>
        <exclude name="**/AllTests.class"/>
       </fileset>
</batchtest>
 </junit>
  <antcall target="execute-junit-report"/>
</target>
<!--Report of the Junit Test cases -->
<target name="execute-junit-report">
        <junitreport todir="${test.reports}">
            <fileset dir="${test.reports}" includes="TEST-*.xml"/>
            <report todir="${test.reports}"/>
        </junitreport>
</target>
<!--Creating the required directories for coverage-->
<target name="test-coverage" description="Creates the required directories for coverage">
<echo>******Cleaning the ${coverage.report}******</echo>
<delete dir="${coverage.report}" />
<echo>******Creating the required directories for test reports******</echo>
<mkdir dir="${coverage.report}" />
</target>
<!-- Code Coverage Configurations -->
<taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
<classpath path="${lib.dir}/jacocoant.jar"/>
</taskdef>
<target name="execute-code-coverage" depends="compile,test-coverage,test-init">
   <jacoco:coverage>
<junit fork="true" printsummary="on" haltonfailure="yes" description="Junit test cases TestApp">
<classpath refid="classpath"/>
<classpath>
       <pathelement location="${build.dir}/WEB-INF/classes"/> 
       <pathelement location="${build.dir}/WEB-INF/test"/> 
       <pathelement location="${build.dir}/WEB-INF/config"/> 
</classpath>

    <!--Save test result in xml format-->
    <formatter type="xml"/>
<!--Batch test run-->
<batchtest fork="yes" todir="${test.reports}">
       <fileset dir="${build.dir}/WEB-INF/test">
        <include name="**/*TestSuite.class"/>
        <exclude name="**/*Test.class"/>
        <exclude name="**/AllTests.class"/>
       </fileset>
</batchtest>
</junit>
</jacoco:coverage>
</target>
<target name="code-coverage" depends="execute-code-coverage">
<jacoco:report>
   <executiondata>
       <file file="jacoco.exec"/>
   </executiondata>
   <structure name="TestApp Code Coverage">
       <classfiles>
           <fileset dir="${build.dir}/WEB-INF/classes"/>
       </classfiles>
       <sourcefiles encoding="UTF-8">
           <fileset dir="${src.dir}"/>
       </sourcefiles>
   </structure>
   <html destdir="${coverage.report}"/>
<csv destfile="${coverage.report}/coverage-report.csv"/>
<xml destfile="${coverage.report}/coverage-report.xml"/>
</jacoco:report>
</target>

</project>




Implement FindBugs using ANT

What is FindBugs?

FindBugs is an open source program used to find bugs in Java code.It uses static analysis to identify hundreds of different potential types of errors in Java programs.

Potential errors are classified in four ranks: (i) scariest, (ii) scary, (iii) troubling and (iv) of concern.

This is a hint to the developer about their possible impact or severity. 

It is very similar to PMD, FindBugs operates on Java bytecode, rather than source code. Whereas PMD works on source code.

It can find major issues with code such as Possible NullpointerException, Security flwas, Performance issues etc. and many more. 


So, Let's do it >>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Following are required jar files:

FindBugs Version 3.0.0:

 annotations.jar
ant.jar
asm-debug-all-5.0.2.jar
bcel-6.0-SNAPSHOT.jar
commons-lang-2.6.jar
dom4j-1.6.1.jar
findbugs-ant.jar
findbugs.jar
jaxen-1.1.6.jar
jcip-annotations.jar
jdepend-2.9.jar
jFormatString.jar
jsr305.jar
yjp-controller-api-redist.jar

Documentation:


I am demonstrating
Ant Targets:

<!-- FindBugs Configurations -->
<!-- Put all jar files given above to classpath, in my case all the jar files are in the 
               D:\JavaTools\Findbugs\findbugs-3.0.0\lib -->

<path id="findbugs.classpath">
<fileset dir="D:\JavaTools\Findbugs\findbugs-3.0.0\lib">
<include name="*.jar" />
</fileset>
</path>

<!--Creating the required directories for findbugs--> <target name="findbugs-init" description="Creates the required directories for findbugs."> <echo>******Cleaning the ${basedir}/findbugs-reports******</echo> <delete dir="${basedir}/findbugs-reports" /> <echo>******Creating the required directories for findbugs******</echo> <mkdir dir="${basedir}/findbugs-reports" /> </target>

<target name="findbugs" depends="findbugs-init,compile" description="Run code analysis over code to check for problems.">
       <!-- Fail this target if FindBugs is not installed. -->
<echo>*****Performing FindBugs analysis on ${project.name}*****</echo>
       <taskdef name="findbugs"
                classname="edu.umd.cs.findbugs.anttask.FindBugsTask"
        classpathref="findbugs.classpath" />

          <!-- Run FindBugs.for HTML output-->
<findbugs classpathref="findbugs.classpath"
      output="html"
             outputFile="${basedir}/findbugs-reports/findbugs.html"
     stylesheet="${basedir}/findbugs/fancy-hist.xsl">

<!-- fancy-hist.xsl stylesheet can be found in findbugs.jar file, 
       There are other stylesheets available and can be used based on the needs -->

<!-- An optional nested element which specifies a source directory path containing source files used to  compile the Java code being analyzed.By specifying a source path, any generated XML bug output will have complete source information, which allows later viewing in the GUI. -->

          <sourcePath path="${src.dir}" />

 <!-- auxclasspath is an optional nested element which specifies a classpath (Jar files or        directories) containing classes used by the analyzed library or application, but which you don't want to analyze.It is specified the same way as Ant's classpath element for the Java task.-->

<auxclasspath refid="classpath"/>

<!-- A optional nested element specifying which classes to analyze.The class element must specify a location attribute which names the archive file (jar, zip, etc.), directory, or class file to be analyzed. Multiple class elements may be specified as children of a  single findbugs element. In addition to or instead of specifying a class element, the FindBugs task can contain one or more fileset element(s) that specify files to be analyzed. For example, you might use a fileset to specify that all of the jar files in a directory should be analyzed. -->

<class location="${build.dir}/WEB-INF/classes" />

        </findbugs>

 <!-- Run FindBugs.for XML output -->
<findbugs classpathref="findbugs.classpath"
     output="xml"
             outputFile="${basedir}/findbugs-reports/findbugs.xml">

<!-- An optional nested element which specifies a source directory path containing source files used to  compile the Java code being analyzed.By specifying a source path, any generated XML bug output will have complete source information, which allows later viewing in the GUI. -->

          <sourcePath path="${src.dir}" />

 <!-- auxclasspath is an optional nested element which specifies a classpath (Jar files or        directories) containing classes used by the analyzed library or application, but which you don't want to analyze.It is specified the same way as Ant's classpath element for the Java task.-->

<auxclasspath refid="classpath"/>

<!-- A optional nested element specifying which classes to analyze.The class element must specify a location attribute which names the archive file (jar, zip, etc.), directory, or class file to be analyzed. Multiple class elements may be specified as children of a  single findbugs element. In addition to or instead of specifying a class element, the FindBugs task can contain one or more fileset element(s) that specify files to be analyzed. For example, you might use a fileset to specify that all of the jar files in a directory should be analyzed. -->

<class location="${build.dir}/WEB-INF/classes" />

  </findbugs>
<echo>*****FindBugs analysis report saved into ${basedir}/findbugs-                    reports/findbugs.xml*****</echo>

</target>


  <!-- Compile the source code -->
<target name="compile" depends="init">
<echo>******Compile the source files******</echo>
<javac debug="on" srcdir="${src.dir}" destdir="${build.dir}/WEB-INF/classes"
includes="**/*">
<classpath refid="classpath" />
</javac>
<!-- Compile the test cases -->
<javac debug="on" srcdir="${test.dir}" destdir="${build.dir}/WEB-INF/test"
includes="**/*">
<classpath refid="classpath" />
</javac>

</target>


Implement PMD and CPD (Copy paste detector) using ANT

You can implement automated PMD and CPD analysis on your java source code using ant.

Why PMD?


PMD is a static code analyser tool. It can be used to check common programming mistakes like class naming, variable naming, cyclomatic complexity, unused variables, unused imports etc. and many more.

Examples:
– Empty try/catch blocks

– Over-complicated expressions

– Using .equals() instead of ‘==’

– Unused variables and imports

– Unnecessary loops and if statements

– Enforce naming conventions

Additionally, PMD comes with a copy-paste detector to find blocks of copied and pasted code. Best of all, you can customize the rules. PMD includes a set of built-in rules and supports the ability to write custom rules. The custom rules can be written in two ways:

1- Using XPath

2- Using Java classes

Here i have used XPath wherever rules are customized.

Why CPD?

The Copy/Paste Detector (CPD) is an add-on to PMD that uses the Rabin–Karp string search algorithm to find duplicated code.
After running this tool against your source code you will be able to find the duplicate code and you can create a utility class or method in some common class and re-use it, instead.


So, Here we go>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Prerequisites jar files for PMD/CPD:

ant-1.8.1.jar
ant-launcher-1.8.1.jar
ant-testutil-1.7.1.jar
asm-3.2.jar
commons-io-2.2.jar
dom4j-1.6.1.jar
javacc-4.1.jar
jaxen-1.1.1.jar
jcommander-1.27.jar
jdom-1.0.jar
junit-4.4.jar
pmd-5.0.5.jar
rhino-1.7R3.jar
saxon-9.1.0.8-dom.jar
saxon-9.1.0.8.jar
xercesImpl-2.9.1.jar
xml-apis-1.3.02.jar
xmlParserAPIs-2.6.2.jar
xom-1.0.jar

Download PMD : http://sourceforge.net/projects/pmd/

Reference: http://pmd.sourceforge.net/

PMD Documentation:

PMD version 5.0.5
http://pmd.sourceforge.net/pmd-5.0.5/

PMD version 5.1.2
http://pmd.sourceforge.net/pmd-5.1.2/


PMD For eclipse : http://sourceforge.net/projects/pmd/files/pmd-eclipse/update-site/

Note:  I am using PMD version 5.0.5. Version 5.1.2 onwards you need to make a small change in rule set for singleton .

RuleSet XML File (pmdrulesets.xml):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ruleset xmlns="http://pmd.sf.net/ruleset/1.0.0" name=""
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"
       xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd">
       <description>
             PMD Plugin preferences rule set
             Priority means: 1 – error, high priority, 2 – error,
             normal priority, 3 – warning, high priority, 4 – warning,
             normal priority and 5 – information.
       </description>
       <rule ref="rulesets/java/typeresolution.xml/LooseCoupling">
             <priority>3</priority>
       </rule>
       <rule
             ref="rulesets/java/typeresolution.xml/CloneMethodMustImplementCloneable">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/typeresolution.xml/UnusedImports">
             <priority>4</priority>
       </rule>
       <rule
             ref="rulesets/java/typeresolution.xml/SignatureDeclareThrowsException">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/braces.xml/ForLoopsMustUseBraces">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/braces.xml">
             <exclude name="IfStmtsMustUseBraces" />
             <exclude name="IfElseStmtsMustUseBraces" />
             <exclude name="WhileLoopsMustUseBraces" />
       </rule>
       <rule ref="rulesets/java/naming.xml/ShortVariable">
             <priority>1</priority>
             <properties>
                    <property name="xpath">
                           <value>
                                 //VariableDeclaratorId[string-length(@Image) &lt; 3]
                           </value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/naming.xml/LongVariable">
             <priority>4</priority>
             <properties>
                    <property name="xpath">
                           <value>
                                 //VariableDeclaratorId[string-length(@Image) > 40]
                           </value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/naming.xml/ShortMethodName">
             <priority>4</priority>
             <properties>
                    <property name="xpath">
                           <value>
                                 //MethodDeclarator[string-length(@Image) &lt; 2]
                           </value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/naming.xml/VariableNamingConventions">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/MethodNamingConventions">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/ClassNamingConventions">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/AbstractNaming">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/AvoidDollarSigns">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/MethodWithSameNameAsEnclosingClass">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/SuspiciousHashcodeMethodName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/SuspiciousConstantFieldName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/SuspiciousEqualsMethodName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/AvoidFieldNameMatchingTypeName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/AvoidFieldNameMatchingMethodName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/NoPackage">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/PackageCase">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/MisleadingVariableName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/BooleanGetMethodName">
             <priority>1</priority>
       </rule>

       <rule ref="rulesets/java/design.xml/UseUtilityClass">
             <priority>1</priority>
       </rule>

       <rule ref="rulesets/java/design.xml/SimplifyBooleanReturns">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SimplifyBooleanExpressions">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SwitchStmtsShouldHaveDefault">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidDeeplyNestedIfStmts">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidReassigningParameters">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SwitchDensity">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/ConstructorCallsOverridableMethod">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AccessorClassGeneration">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/FinalFieldCouldBeStatic">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/CloseResource">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/NonStaticInitializer">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/DefaultLabelNotLastInSwitchStmt">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/NonCaseLabelInSwitchStatement">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/OptimizableToArrayCall">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/BadComparison">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/EqualsNull">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/InstantiationToGetClass">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/IdempotentOperations">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SimpleDateFormatNeedsLocale">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/ImmutableField">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/UseLocaleWithCaseConversions">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidProtectedFieldInFinalClass">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AssignmentToNonFinalStatic">
             <priority>1</priority>
       </rule>
       <rule
              ref="rulesets/java/design.xml/MissingStaticMethodInNonInstantiatableClass">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidSynchronizedAtMethodLevel">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/MissingBreakInSwitch">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/UseNotifyAllInsteadOfNotify">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidInstanceofChecksInCatchClause">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AbstractClassWithoutAbstractMethod">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SimplifyConditional">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/CompareObjectsWithEquals">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/PositionLiteralsFirstInComparisons">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/UnnecessaryLocalBeforeReturn">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/NonThreadSafeSingleton">
             <priority>3</priority>
       </rule>

       <rule ref="rulesets/java/design.xml/UncommentedEmptyMethodBody">
             <priority>1</priority>
       </rule>

       <rule ref="rulesets/java/design.xml/UncommentedEmptyConstructor">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidConstantsInterface">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/UnsynchronizedStaticDateFormatter">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml">
             <exclude name="ConfusingTernary" />
       </rule>
       <rule ref="rulesets/java/design.xml/UseCollectionIsEmpty">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/PreserveStackTrace">
             <priority>1</priority>
       </rule>

       <rule
              ref="rulesets/java/design.xml/ClassWithOnlyPrivateConstructorsShouldBeFinal">
             <priority>1</priority>
       </rule>

       <rule
              ref="rulesets/java/design.xml/EmptyMethodInAbstractClassShouldBeAbstract">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SingularField">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/ReturnEmptyArrayRatherThanNull">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AbstractClassWithoutAnyMethod">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/TooFewBranchesForASwitchStatement">
             <priority>1</priority>
       </rule>
       <rule
             ref="rulesets/java/design.xml/FieldDeclarationsShouldBeAtStartOfClass">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/AvoidCatchingThrowable">
             <priority>1</priority>
       </rule>
       <rule
             ref="rulesets/java/strictexception.xml/SignatureDeclareThrowsException">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/ExceptionAsFlowControl">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/AvoidCatchingNPE">
             <priority>3</priority>
       </rule>
       <rule
             ref="rulesets/java/strictexception.xml/AvoidThrowingRawExceptionTypes">
             <priority>1</priority>
       </rule>
       <rule
              ref="rulesets/java/strictexception.xml/AvoidThrowingNullPointerException">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/AvoidRethrowingException">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/DoNotExtendJavaLangError">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/DoNotThrowExceptionInFinally">
             <priority>3</priority>
       </rule>
       <rule
              ref="rulesets/java/strictexception.xml/AvoidThrowingNewInstanceOfSameException">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/AvoidCatchingGenericException">
             <priority>2</priority>
       </rule>
       <rule
             ref="rulesets/java/strictexception.xml/AvoidLosingExceptionInformation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/unusedcode.xml/UnusedPrivateField">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/unusedcode.xml/UnusedLocalVariable">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/unusedcode.xml/UnusedPrivateMethod">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/unusedcode.xml/UnusedFormalParameter">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-java.xml/MoreThanOneLogger">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-java.xml/LoggerIsNotStaticFinal">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-java.xml/SystemPrintln">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-java.xml/AvoidPrintStackTrace">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/AvoidDuplicateLiterals">
             <priority>1</priority>
             <properties>
                    <property name="skipAnnotations">
                           <value>true</value>
                    </property>
                    <property name="maxDuplicateLiterals">
                           <value>4</value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/strings.xml/StringInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/StringToString">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/InefficientStringBuffering">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UnnecessaryCaseChange">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UseStringBufferLength">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/AppendCharacterWithChar">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/ConsecutiveAppendsShouldReuse">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/ConsecutiveLiteralAppends">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UseIndexOfChar">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/InefficientEmptyStringCheck">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/InsufficientStringBufferDeclaration">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UselessStringValueOf">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/StringBufferInstantiationWithChar">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UseEqualsToCompareStrings">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/AvoidStringBufferField">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ReplaceVectorWithList">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ReplaceHashtableWithMap">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ReplaceEnumerationWithIterator">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/AvoidEnumAsIdentifier">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/AvoidAssertAsIdentifier">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/IntegerInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ByteInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ShortInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/LongInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/JUnit4TestShouldUseBeforeAnnotation">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/JUnit4TestShouldUseAfterAnnotation">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/JUnit4TestShouldUseTestAnnotation">
             <priority>3</priority>
       </rule>
       <rule
             ref="rulesets/java/migrating.xml/JUnit4SuitesShouldUseSuiteAnnotation">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/JUnitUseExpected">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/UseProperClassLoader">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/MDBAndSessionBeanNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/RemoteSessionInterfaceNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/LocalInterfaceSessionNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/LocalHomeNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/RemoteInterfaceNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/DoNotCallSystemExit">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/StaticEJBFieldShouldBeFinal">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/DoNotUseThreads">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/MethodArgumentCouldBeFinal">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/LocalVariableCouldBeFinal">
             <priority>1</priority>
       </rule>
       <rule
             ref="rulesets/java/optimizations.xml/AvoidInstantiatingObjectsInLoops">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/UseArrayListInsteadOfVector">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/SimplifyStartsWith">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/UseStringBufferForStringAppends">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/UseArraysAsList">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/AvoidArrayLoops">
             <priority>2</priority>
       </rule>
       <rule
             ref="rulesets/java/optimizations.xml/UnnecessaryWrapperObjectCreation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/AddEmptyString">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/RedundantFieldInitializer">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/PrematureDeclaration">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyCatchBlock">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyIfStmt">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyWhileStmt">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyTryBlock">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyFinallyBlock">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptySwitchStatements">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptySynchronizedBlock">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyStaticInitializer">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyStatementNotInLoop">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyInitializer">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UnnecessaryConversionTemporary">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UnnecessaryReturn">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UnnecessaryFinalModifier">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UselessOverridingMethod">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UselessOperationOnImmutable">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UnusedNullCheckInEquals">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/JumbledIncrementer">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/ForLoopShouldBeWhileLoop">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/OverrideBothEqualsAndHashcode">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/DoubleCheckedLocking">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/ReturnFromFinallyBlock">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/UnconditionalIfStatement">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/BooleanInstantiation">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/CollapsibleIfStatements">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/ClassCastExceptionWithToArray">
             <priority>3</priority>
       </rule>
       <rule
              ref="rulesets/java/basic.xml/AvoidDecimalLiteralsInBigDecimalConstructor">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/MisplacedNullCheck">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidThreadGroup">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/BrokenNullCheck">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/BigIntegerInstantiation">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidUsingOctalValues">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidUsingHardCodedIP">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/CheckResultSet">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidMultipleUnaryOperators">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/ExtendsObject">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/CheckSkipResult">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidBranchingStatementAsLastInLoop">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/DontCallThreadRun">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/DontUseFloatTypeForLoopIndices">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/sunsecure.xml/MethodReturnsInternalArray">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/sunsecure.xml/ArrayIsStoredDirectly">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/coupling.xml/CouplingBetweenObjects">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/coupling.xml/ExcessiveImports">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/coupling.xml/LooseCoupling">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/DuplicateImports">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/DontImportJavaLang">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/UnusedImports">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/ImportFromSamePackage">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/UnnecessaryFullyQualifiedName">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/TooManyStaticImports">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/JUnitStaticSuite">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/JUnitSpelling">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/JUnitAssertionsShouldIncludeMessage">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/JUnitTestsShouldIncludeAssert">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/TestClassWithoutTestCases">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/UnnecessaryBooleanAssertion">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/UseAssertEqualsInsteadOfAssertTrue">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/UseAssertSameInsteadOfAssertTrue">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/UseAssertNullInsteadOfAssertTrue">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/SimplifyBooleanAssertion">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/NullAssignment">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/OnlyOneReturn">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AssignmentInOperand">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AtLeastOneConstructor">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/DontImportSun">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/SuspiciousOctalEscape">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/CallSuperInConstructor">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/UnnecessaryParentheses">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/DefaultPackage">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/BooleanInversion">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AvoidUsingShortType">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AvoidUsingVolatile">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AvoidUsingNativeCode">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AvoidAccessibilityAlteration">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml">
             <exclude name="DataflowAnomalyAnalysis" />
             <exclude name="UnnecessaryConstructor" />
             <exclude name="AvoidFinalLocalVariable" />
       </rule>
       <rule
              ref="rulesets/java/controversial.xml/DoNotCallGarbageCollectionExplicitly">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/NPathComplexity">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/ExcessiveMethodLength">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/ExcessiveParameterList">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/ExcessiveClassLength">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/CyclomaticComplexity">
             <priority>4</priority>
             <properties>
                    <property name="reportLevel">
                           <value>9</value>
                    </property>
                    <property name="showClassesComplexity">
                           <value>true</value>
                    </property>
                    <property name="showMethodsComplexity">
                           <value>true</value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/codesize.xml/ExcessivePublicCount">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/TooManyFields">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/NcssMethodCount">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/NcssTypeCount">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/NcssConstructorCount">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/TooManyMethods">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/EmptyFinalizer">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/FinalizeOnlyCallsSuperFinalize">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/FinalizeOverloaded">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/FinalizeDoesNotCallSuperFinalize">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/FinalizeShouldBeProtected">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/AvoidCallingFinalize">
             <priority>3</priority>
       </rule>
       <rule
             ref="rulesets/java/logging-jakarta-commons.xml/UseCorrectExceptionLogging">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-jakarta-commons.xml/ProperLogger">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/javabeans.xml/BeanMembersShouldSerialize">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/javabeans.xml/MissingSerialVersionUID">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/clone.xml/ProperCloneImplementation">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/clone.xml/CloneThrowsCloneNotSupportedException">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/clone.xml/CloneMethodMustImplementCloneable">
             <priority>3</priority>
       </rule>
</ruleset>



Build properties:

src.dir=src
project.name=TestApp
pmd.reports=pmd-reports


Ant Target Configuration:

 <!--Creating the required directories for pmd-->
<target name="pmd-init" description="Creates the required directories for pmd.">
<echo>******Cleaning the ${pmd.reports}******</echo>
<delete dir="${pmd.reports}" />
<echo>******Creating the required directories for pmd******</echo>
<mkdir dir="${pmd.reports}" />
</target>
<!-- PMD Configurations -->
<!--Provided the pmd library path, It can be taken from environment variable 
as well. -->
 <!--Put the above given jar files to the classpath, For me i am having all jar files in  D:/ProjectSofts/Java/pmd-bin-5.0.5/lib/-->

<path id="pmd.classpath">
<fileset dir="D:/ProjectSofts/Java/pmd-bin-5.0.5/lib/">
<include name="*.jar" />
</fileset>
</path>

<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"
classpathref="pmd.classpath" />

<target name="pmd" description="Run code analysis over code to check for standards." depends="pmd-init">
<echo>*****Performing PMD analysis on ${project.name}*****</echo>
<pmd rulesetfiles="pmdrulesets.xml">
<formatter type="net.sourceforge.pmd.renderers.HTMLRenderer"
toFile="${pmd.reports}/PMD-Reports.html" />
<formatter type="net.sourceforge.pmd.renderers.XMLRenderer"
toFile="${pmd.reports}/pmd.xml" />
<fileset dir="${src.dir}" defaultexcludes="yes">
<include name="com/**" />
<exclude name="com/**/*.properties" />
<exclude name="com/**/*.xml" />
</fileset>
</pmd>
<echo>*****PMD analysis report saved into ${pmd.reports}/PMD-Reports.html*****</echo>
</target>

<!--Creating the required directories for cpd-->
<target name="-cpd-init" description="Creates the required directories for cpd.">
 <echo>******Cleaning the ${basedir}/cpd-reports******</echo>
 <delete dir="${basedir}/cpd-reports" />
 <echo>******Creating the required directories for cpd******</echo>
 <mkdir dir="${basedir}/cpd-reports" />
</target>

Implementing CPD (Copy Paste Detector):

<target name="cpd" depends="-cpd-init">
 <echo>*****Performing Copy Paste Detector (CPD) analysis on ${project.name} to find the duplicate codes*****</echo>
 <taskdef name="cpd" classname="net.sourceforge.pmd.cpd.CPDTask" classpathref="pmd.classpath" />
 <cpd minimumTokenCount="100" outputFile="${basedir}/cpd-reports/cpd.xml" format="xml"
 ignoreliterals="true" ignoreIdentifiers="true">
<fileset dir="${src.dir}" defaultexcludes="yes">
  <include name="com/**" />
  <exclude name="com/**/*.properties" />
  <exclude name="com/**/*.xml" />
</fileset>
  </cpd>
  <echo>*****Copy Paste Detector (CPD) analysis report saved into ${basedir}/cpd-reports/cpd.xml*****</echo>
</target>

Note: Here ${pmd.reports} , ${src.dir} , ${project.name}, are configured in build.properties file.



Leave your comments/suggestions below, Otherwise the next time:)