Spring Dependency Injection

What is the purpose of DI?
Objects don’t define their dependencies themselves, the dependencies are injected to them as needed.

How does it benefit ?

The objects don’t kneed to know where and how to get their dependencies, which results in loose coupling between objects, which makes them a lot easier to test.

How does it implemented ?

Spring container manages the lifecycle of objects and their dependencies based on a configuration file or annotations.


ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans.

The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.

The configuration metadata is represented in XML, Java annotations, or Java code.
It allows you to express the objects that compose your application and the rich interdependencies between such objects.

Spring Dependency Injection Overview

The Spring container is capable of fetching a managed bean and inject that bean into another managed bean.

How does Injection happens via IOC?

Developer defines a Java interface and then declares a property in a managed bean which type is the same of that interface.
When the Spring container initializes the bean it will automatically fetch an implementation of that interface and inject into the bean,

i.e. the bean has a dependency that is injected during initialization time.

This way the target bean becomes completely decoupled from the bean that is injected,
i.e. the implementation of the interface can be switched by another implementation without changing any single piece of code in the target bean. The interface implementation itself must also be a Spring managed bean

DI through Examples
Following code examples are compatible with JDK
and Spring 3.2.0

1. Define the interface of the injected bean

package com.di.example;
public interface InjectedBean {

void doSomething();



2. Define the implementation:

package com.di.example;
import org.springframework.stereotype.Service;

public class InjectedBeanImpl implements InjectedBean {

  public void doSomething() {
    System.out.println("Bean was correctly injected!");


@Service annotation. This tells the Spring container that this class is a managed bean. When the Spring container scans this package for beans during container initialization it will know that this class represents a managed bean.

3.Defining Target Bean
Define a simple Spring bean that will receive the injected bean as a dependency:

package com.di.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

public class ExampleBean {

  private InjectedBean injectedBean;

    public void callExampleMethod() {


Things To remember

injectedBean bean property defined as InjectedBean type. The used type here is the interface type.

This property is annotated with @Autowired annotation.
This means that when the Spring container initializes this bean it will lookup for an implementation of this interface type and inject it as a property of this bean! This is actually the Spring Dependency Injection mechanism. You can easily see that the injected bean and the target bean became decoupled.

You can switch the injected bean implementation without changing a single line of code in the target bean.

4. Main Class

package com.di.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main 
  public static void main( String[] args )
    ApplicationContext ctx = 
                  new ClassPathXmlApplicationContext("spring.xml");
    ExampleBean exampleBean = (ExampleBean) ctx.getBean("exampleBean");

5. Spring configuration File

we need to define the packages where the Spring container should look for beans (the classes annotated with @Service annotation from the previous tutorial sections)

eg : “spring.xml”

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    <context:component-scan base-package="com.di.example" />

Additional Notes.

Differnce between @Resource and @Autowired

@Resource means get me a known resource by name.
The name is extracted from the name of the annotated setter or field, or it is taken from the name-Parameter.

@Inject or @Autowired try to wire in a suitable other component by type.

Tagged with: , , , ,
Posted in Uncategorized

JAVA 7 New Features

Quick Overview of Freequently using JAVA 7 New Features.

Code Examples are well known things circulate in Java Forums in the Web.

1. Strings in switch statements

You can use a String object in the expression of a switch statement


public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
         case "Friday":
             typeOfDay = "End of work week";
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     return typeOfDay;

2. The diamond operator “<>”

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

Following explains it with samples.

For example, consider the following variable declaration:
Map<String, List> myMap = new HashMap<String, List>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters ():

Map<String, List> myMap = new HashMap<>();

3. Handling more than one type of exception

In Java SE 7 and later, a single catch block can handle more than one type of exception. Consider the following example, which contains duplicate code in each of the catch blocks:

//Prior to Java 7
catch (IOException ex) {
     throw ex;
catch (SQLException ex) {
     throw ex;
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.
The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException ex) { // java 7 handling more than one type of exception
    throw ex;

The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|). Some other advantages apart from syntactical improvement

Tagged with: , , , , , ,
Posted in Uncategorized

DAO Framwork using Spring HibernteTemplate

Concept of Data Access layer

A data access layer follows the idea of “separation of concerns” whereby all of the logic required for your business logic to interact with your data layer (database) is isolated to a single set of classes (layer).

This allows you to more easily change the backend physical data storage technology (move from XML files to a database, or from SQL Server to Oracle or MySQL, for example) without having a large impact (and if done right having zero impact) to your business logic.

There are  lot of tools that will help you build your data layer. If you search for the phrase “object relational mapper” or “ORM” you should find some more detailed inform

Source – http://stackoverflow.com Discussions

DAO Design pattern in brief

Data Access Object encapsulates all the data access logic to create, retrieve, delete, and update data from a persistent store.

Data Access Object uses Transfer Object to send and receive data.

The Data Access Object pattern encapsulates access to a persistent store by managing the connection with the data store.

Adavantages of using DAO
Reduces code complexity in client
Improves code reuse
Provides easier migration to new data store

When to use DAO

Decouple data access from the business logic
Provide all data access from in a separate layer.

Generic DAO Layer Example

Following is DAO Framework designed using java.

Following are core components of it.
BusinessDaoImpl.java  (Implementation Class of BaseDao)

Business DAO Interface

Example :

Business DAO Impl


Test Program Using Spring 3.X /Hibernate 3.X / MySql

Source Code Examples in are as Follows


import java.io.Serializable;
import java.util.List;

public interface BaseDao<T, PK extends Serializable> {

    public Serializable save(T newInstance);

    void update(T transientObject);

    void saveOrUpdate(T transientObject);

    void saveOrUpdateAll(List<T> transientObjectCollection);

    void delete(T persistentObject);

    public List<T> find() throws CustomException;

    public List<T> find(String propertyName, Object value);

    T findById(PK id) throws CustomException;

    public T search(String columnName, Object value);

    public Object exec(String query);

    public Object exec(String query,Object[] params);



import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

public abstract class BusinessDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {

private static final String DATA_ACCESS_EXCEPTION_IN_FIND = "DataAccessException in  Find";

private HibernateTemplate hibernateTemplate;

protected Class<T> domainClass = getDomainClass();

protected abstract Class<T> getDomainClass();

public HibernateTemplate getHibernateTemplate() throws Exception {

return hibernateTemplate;

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate = hibernateTemplate;


public Serializable save(T t) {

return hibernateTemplate.save(t);


public void update(T t) {


public void saveOrUpdate(T t) {


public void saveOrUpdateAll(List<T> t) {


public void delete(T t) {


public List<T> find() throws CustomException {

List<T> t = new ArrayList<T>();
try {
t = getHibernateTemplate().find("from " + getDomainClass().getName());
} catch (DataAccessException e) {
throw new CustomException(DATA_ACCESS_EXCEPTION_IN_FIND+"Error=>"+e.toString(),0001);
} catch (Exception e) {
return t;

public List<T> find(String domainObjectField, Object value) throws CustomException {

List<T> t = new ArrayList<T>();
DetachedCriteria criteria = createDetachedCriteria();

criteria.add(Restrictions.eq(domainObjectField, value));

try {
t = getHibernateTemplate().findByCriteria(criteria);
} catch (DataAccessException e) {
throw new CustomException(DATA_ACCESS_EXCEPTION_IN_FIND+"Error=>"+e.toString(),0001);
} catch (Exception e) {
return t;


public T findById(PK id) throws CustomException {

T t = null;
try {

t = getHibernateTemplate().get(getDomainClass(), id);
} catch (Exception e) {
throw new CustomException(DATA_ACCESS_EXCEPTION_IN_FIND+"Error"+e.toString(),0001);
return t;

public T search(final String columnName, final Object value) {

return hibernateTemplate.execute(new HibernateCallback<T>() {

public T doInHibernate(Session session) throws HibernateException, SQLException {

return DataAccessUtils.objectResult(session.createCriteria(getDomainClass()).add(Restrictions.eq(columnName, value)).list(),

* @param query
* @return
public Object exec(final String query) {

return hibernateTemplate.execute(new HibernateCallback<Object>() {

public Object doInHibernate(Session session) throws HibernateException, SQLException {

return session.createQuery(query).list();


public Object exec(final String query, final Object[] params) {

return  hibernateTemplate.execute(new HibernateCallback<Object>() {
public Object doInHibernate(Session session)
throws HibernateException {

Query q = session.createQuery(query);
return q.list();


* @return
protected DetachedCriteria createDetachedCriteria() {

return DetachedCriteria.forClass(getDomainClass());


private void fillParams(Query q, final Object[] params) {

if (null != params) {

for (int i = 0; i < params.length; i++) {
q.setParameter(i, params[i]);



Business DAO Interface
eg : EmployeeDao.java

import java.io.Serializable;

public interface EmployeeDao extends BaseDao<Employee, Serializable>{


Business DAO Implementation Class
Eg: EmployeeDaoImpl

public class EmployeeDaoImpl extends BusinessDaoImpl<Employee, Serializable> implements EmployeeDao {

protected Class<Employee> getDomainClass() {
return Employee.class;


Tagged with: , , , , , ,
Posted in Uncategorized

Cloud Computing Basics


Model for enabling convenient, on-demand network access to a shared pool of configurable computing resources (e.g., networks, servers, storage, applications, and services) that can be rapidly provisioned and released with minimal management effort or service provider interaction.

Cloud Computing -Essential Characteristics


Cloud computing -Service Models


Software as a Service (SaaS)
Use provider’s applications over a network

Platform as a Service (PaaS)
Enables developers to build applications on scalable systems and deploy as a service to customers. (Example: Google App Engine)

Infrastructure as a Service (IaaS)
Provide processing, storage, network capacity, and other fundamental computing resources where the consumer is able to deploy and run arbitrary software





Cloud Computing Deployment Models

Private cloud
Enterprise owned and operated for an organization only.

Community cloud
Shared infrastructure for specific community.

Public cloud
Provided to the public, generally large-scale.

Hybrid cloud
Composition of two or more clouds.

Cloud Computing Architecture


Cloud Computing Application

Applications for Collaboration: email, IM
Online storage: Files, photos, music, movies…
Management: Calendar, project management
Office productivity: Word processor, presentations, spread sheet
Tools: Media player, compression utility, cloud desktop, antivirus
Applications are unlimited. Type of application is limited by the developer’s knowledge only.

Advantages of Cloud computing

Simplicity – easy to deploy and use
Pay as you use – pay only for the services you consume
Cost saving – Lesser in-house IT costs
Backup and Recovery
Easy to upgrade
On demand availability

Cloud Computing Challenges

Uninterrupted availability
Integration with in-house IT
Ability to customize to internal needs
Migrating back to in-house
Regulatory requirements prohibit cloud (data storage abstracted)

Cloud Computing security Adavantages

Shifting public data to a external cloud reduces the exposure of the internal sensitive data
Cloud homogeneity makes security auditing/testing simpler
Clouds enable automated security management
Redundancy / Disaster Recovery

Cloud Computing Security Challenges

Trusting vendor’s security model
Customer inability to respond to audit findings
Obtaining support for investigations
Indirect administrator accountability
Proprietary implementations can’t be examined
Loss of physical control
Denial of Service

Tagged with: , , , , , , ,
Posted in Uncategorized

Integrating Log4j with Spring 3.0 MVC

Here is an explanation of log4j integration with Spring 3.0 MVC Project.

Server – apache-tomcat-7.0.34
Log4j Version – log4j-1.2.16.jar

What is log4j?

Open Source java based framework of Apache Foundation.
It helps to output log statements to output targets.

Components of Log4j?

  • loggers: Responsible for capturing logging information.
  • appenders: Responsible for publishing logging information to various preferred destinations.
  • layouts: Responsible to format logging information in different styles.

There are various different log levels

ALL -All levels including custom levels.

DEBUG-Used to indicate events that are useful to debug an application. Handling method for DEBUG level is: debug().

INFO-Used to highlight the progress of the application. Handling method for INFO level is: info().

WARN-Used to indicate potentially harmful situations. Handling method for WARN level is: warn().

ERROR-Shows errors messages that might not be serious enough and allow the application to continue. Handling method for ERROR level is: error().

FATAL– Used toindicate severe events that will may cause abortion of the application. Handling method for FATAL level is: fatal().

OFF -The highest possible rank and is intended to turn off logging.

How to Integrate log4j into the Spring 3.0 Project?

1. Add log4j jar file into classpath.

2. Create log4j’s configuration in the Project.

Create log4j’s configuration.

Log4j configuration file can be property file or xml file. Xml file has added advantatages than property file. Eg: Filters, custom ErrorHandlers and a special type of appenders, i.e. AsyncAppender. ErrorHandlers define

i. Add the following entry to web.xml file



ii. Place the log4j.xml file inside /WEB-INF folder

Following is sample log4j.xml file

<!--?xml version="1.0" encoding="UTF-8"?-->

<?xml version="1.0" encoding="UTF-8"?>

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<appender name="fileAppender" class="org.apache.log4j.FileAppender">
		<param name="File" value="${catalina.home}/logs/LogFile.log" />
		<param name="MaxFileSize" value="5MB" />
		<param name="MaxBackupIndex" value="50" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-7p %d [%t] %c %x - %m%n" />


	<appender name="htmlFileAppender" class="org.apache.log4j.FileAppender">
		<param name="File" value="${catalina.home}/logs/LogFile.html" />
		<param name="MaxFileSize" value="5MB" />
		<param name="MaxBackupIndex" value="50" />
		<layout class="org.apache.log4j.HTMLLayout">
			<param name="ConversionPattern" value="%-7p %d [%t] %c %x - %m%n" />


	<appender name="stdOut" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-7p %d [%t] %c %x - %m%n" />

	<!-- package level log levels can be define -->
	<category name="com.res.common.controller">
		<priority value="debug" />

	<!-- Root Logger trace/debug/info/warn/error/fatal/off> -->
		<priority value="info" />
		<appender-ref ref="fileAppender" />
		<appender-ref ref="htmlFileAppender" />
		<!-- remove stdOut to disable printing logs in server console -->
		<appender-ref ref="stdOut" />



Following things are included in the sample log4j.xml file

  • Two types of appenders are in the sample log4j.xml. Eg : FileAppender and CosoleAppender.
  • Package level log levels definition is defined
  • Log file layout both text and html formats
  • Root logger is defined
    The root logger is the base logger from which other loggers inherits. Syntax for configuring the root logger is as follows:

log4j.rootLogger=level[, appender1, appender2…]

Java Code Example for adding loggers

import org.apache.log4j.Logger;
public class Test {

    private static final Logger logger = Logger.getLogger(Test.class);

    Test() {


    public void methodOne() {

        logger.info("Add info message");
        logger.warn("Add warn message");


Tagged with: , , , , , , ,
Posted in Uncategorized

Flexible Utilities for Data Retrieval in Hibernate


What is Object Relational Mapping?

Maps the Objects in java with the relational entities in the database.
In this,entities/classes refers to table in database,instance of classes.


Main Advantages of Object Relational Mappings

Improved productivity:

High-level object-oriented API

Less Java code to write

No SQL to write

Improved performance:

Sophisticated caching

Lazy loading

Eager loading

Improved maintainability:

A lot less code to write

Improved portability:

ORM framework generates database-specific SQL for you

What is Hibernate?

Pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables.

Hibernate Architecture


Core Interfaces in Hibernate Framework

Session Interface:
Allows to create Query Objects and Retrieve persistant objects.

Not Thread Safe.

Wraps JDBC Connection Factory for Transactions.

Session session=SessionFactory.openConnection();

SessionFactory Interface

This is a factory that delivers the session objects to hibernate application.
There will be a single SessionFactory for the whole application and it will be shared among all the application threads.
The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime.

    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);

Configuration Interface
This is used to configure hibernate. It’s also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.

Transaction Interface

Optional interface.
Abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.

Query and Criteria Interface
This interface allows the user to perform queries and also control the flow of the query execution.

Hibernate Integration with Business Application.


Hibernate Utility For Easy Data Retrieval.

I have designed framework for Data Retrieval using Hibernate Mapping.
This is some kind of experimental task.

User is able extraxct data easily without having much knowledge about Hibernate Queries.

Following are the core features of developed framework.

1. Retrieves Data from Single Table
2. Retrieves Data from Single Table with Condition statement
3. Retrieves Data from Single Table with Condition statement. Get the data from relationship table
4. Joining Two Tables
5. Aggregate function (MIN,MAX)

Utility Files in the Framework


HibernateUtil Source Code : Download



CustomHibernateUtil Source Code : Download

Following are example of usage of developed Utility Components

1. Retrieving data from Single Table

    public void singleTableDataRetrieval() throws Exception {

<strong>2. Retrieving data from Single Table with Condition statement</strong>

    public void singleTableDataRetrievalWithConditions() {

        Map<String, Object> conditionParmMap = new HashMap<String, Object>();

        conditionParmMap.put("", "value");

        Query query = CustomHibernateUtils.getParmQueryObject(conditionParmMap, <POJO_NAME>.class);
        List ubList = query.list();
        for (Object obj : ubList) {
            System.out.println("UbdId-------------" + ((<POJO_NAME>) obj).getUbdId());



3. Retrieving data from one to many relationship table.

    public void mappingTableDataRetrievalWithConditions() {

        Map<String, Object> conditionParmMap = new HashMap<String, Object>();
       conditionParmMap.put("", "value");

        Query query = CustomHibernateUtils.getParmQueryObject(conditionParmMap, <POJO_NAME>.class);
        List<<POJO_NAME>> objectList = query.list();

        for (<POJO_NAME> businessObject : objectList) {

            Set objectSet = businessObject.getObjectSet();
            Object[] arr = objectSet.toArray();
            for (Object object : arr) {
                System.out.println("value------------------->" + ((POJO_NAME_TWO) object).getxxxxxxx());



4. Joining Two Tables Table A- POJO_ONE, Table B -POJO_TWO

 public void joinTwoTablesAndDataRetrieval() {

        Map<String, Object> conditionParmMap = new HashMap<String, Object>();

        String[] tableAndJoinColum = {"<POJO_ONE>", "JOINING_TABLE_REPRESANTATION_FIELD_IN_POJO_ONE"};

        Query query = CustomHibernateUtils.getJoinQueryObject(conditionParmMap, tableAndJoinColum);
        List objectList = query.list();

        Iterator ite = objectList.iterator();
        while (ite.hasNext()) {
            Object[] objects = (Object[]) ite.next();
            <POJO_ONE> pojoOneObject = (<POJO_ONE>) objects[0];
            <POJO_TWO> pojoTwoObject = (<POJO_TWO>) objects[1];




5. Aggregate Functions Demo

    public void aggregateFunction() {
       private static final String MIN = "min";//This should defined globally

        Map<String, Object> conditionParmMap = new HashMap<String, Object>();
        conditionParmMap.put("", "");
        conditionParmMap.put("", MIN);

        Query query = CustomHibernateUtils.getParmQueryObject(conditionParmMap,  <POJO_NAME>.class);
        List objList = query.list();

        for (Object obj : objList) {
            System.out.println("obj id-------------" + ((BigDecimal) obj));




6.Join Two Tables. POJO_ONE and POJO_TWO. Aggregated Function is there for joining table's field.

  public void joinQueryWithAggregateFunction() {

     private static final String MAX = "max";//This should defined globally
        Map<String, Object> conditionParmMap = new HashMap<String, Object>();
        conditionParmMap.put("status", "1");
        conditionParmMap.put("<POJO_TWO_REPRESENTATION_IN_POJO_ONE>.<FIELD_NAME>", MAX);

        String[] tableAndJoinColum = {"<POJO_ONE>", "<POJO_TWO_REPRESENTATION_IN_POJO_ONE>"};

        Query query = CustomHibernateUtils.getJoinQueryObject(conditionParmMap, tableAndJoinColum);
        List objList = query.list();

        for (Object obj : objList) {
            System.out.println("obj Id-------------" + ((BigDecimal) obj));




Tagged with: , ,
Posted in Uncategorized

Code Quality Tool- PMD with Ant Integration Quick Guide

Value of code Reviews in brief

Code review is formal process for examining software source code to identify problems and improve software quality.

Types of  reviews

Automated tools :- PMD, FindBugs, CheckStyle ect.
Reduce the difficult and slow review of source code. Can Identify code issues quickly in early stage.

Lightweight code reviews (Peer Review)
Get the source code and log the findings of the Peer’s code.

Software inspections:
Product is selected for review and a team is gathered for an inspection meeting to review the work product.

PMD What does it mean?

Pretty Much Done
Project Mess Detector
Project Monitoring Directives
Project Meets Deadline
Programming Mistake Detector
Pounds Mistakes Dead

What is PMD?
PMD is a Automated Code Quality Review Tool. Rules can be configured easily. Tool helps to capture major programming defects in java.

PMD scans Java source code and looks for problems

Possible bugs – empty try/catch/finally/switch statements
Dead code – unused local variables, parameters and private methods
Suboptimal code – wasteful String/StringBuffer usage
Over complicated expressions – unnecessary if statements, for loops that could be while loops
Duplicate code – copied/pasted code means copied/pasted bugs

PMD Tool – Legal BackGround

PMD has “BSD” License.

What is BSD?
A BSD  (Berkeley Software Distribution) licence essentially says to other developers, “do what you like, so long as you retain my copyright note and disclaimer”.

The GPL and the BSD license are both “free”, and “open source”, as they are approved by both the FSF and the OSI

Configuring PMD with Source Code

PMD Jar file can be downloaded from http://pmd.sourceforge.net/

What is rules.xml ?

Contains the code quality rules. There are number of rule files in different categories. Rules files can be found in /rulesets folder inside pmd-x.x.jar.
basic.xml, design.xml, import.xml

Rules can be easily customized by maintaining separate rule configuration file.

Priority levels can be set on those rules.

How to create RuleSet ?
Copy and use following lines to create rule.xml file.

<?xml version="1.0"?>
<ruleset name="Custom ruleset"
   xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
 This ruleset checks my code for bad stuff



Add the rules one by one

<!-- Here's some rules we'll specify one at a time -->
 <rule ref="rulesets/java/unusedcode.xml/UnusedLocalVariable"/>
 <rule ref="rulesets/java/unusedcode.xml/UnusedPrivateField"/>

You can select pre defined rules from /rulesets folder inside pmd-x.x.jar.
basic.xml, design.xml, import.xml

Setting priority Levels and Customize messages for Rules.

Default error messages and priority levels can be overridden in custom ruleset.xml file.
eg :

 <rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod"
  message="Avoid unused private methods">

User Defined Rules

New Rules can be defined base on specific project requirments.
There are two ways of defining customize rules.

Following two method can be use to create new rule.
Write a rule using Java
Write an XPath expression

Here I am not going to describe them in detail.

Integrating RuleSet with Busines Project.

Following are the steps of Integrating PMD custom ruleset with source code.

1.   Create ruleset.xml file.
2.   Integrate ruleset.xml file with build target.
3.   Generate PMD report

Following are most freequently using rules.

UnusedImports/MissingBreakInSwitch …. ect

Ant Targets to Generates PMD Report.

<target name="create-pmd-report">
<MACRO DEF TARGET NAME pmdmodule="sourcePackageNameOne" 

Macro def target is as follows.

	<!-- = = = = = = = = = = = = = = = = =
          macrodef: target        
         = = = = = = = = = = = = = = = = = -->
    <macrodef name="MACRO DEF TARGET NAME">
     <!--default package name can be set -->
        <attribute name="pmdmodule" default="common" />
		<echo message="----Running pmd report from @{pmdmodule}"/>
		<taskdef name="pmd"   classpathref="pmd.taskdef.classpath" classname="net.sourceforge.pmd.ant.PMDTask"/>
		<fail unless="target.reports.pmd" message="@{pmdmodule} is not set"/>
			<delete dir="${target.reports.pmd}/@{pmdmodule}"/>
			<mkdir  dir="${target.reports.pmd}/@{pmdmodule}"/>

			 <pmd rulesetfiles="${basedir}/docs/pmdRules/pmdRules.xml">

				        <formatter type="xml" toFile="${target.reports.pmd}/@{pmdmodule}/@{pmdmodule}-pmd-report.xml" linkPrefix="${src.main}/"/>
						 <fileset dir="${basedir}/@{pmdmodule}">
				            <include name="**/*.java"/>


<xslt in="${target.reports.pmd}/@{pmdmodule}/@{pmdmodule}-pmd-report.xml" style="${basedir}/docs/pmdRules/ag-pmd-report.xslt" out="${target.reports.pmd}/@{pmdmodule}/@{pmdmodule}-pmd-report.html">
<param name="title" expression="Release branch details : ${release.branch} -@{pmdmodule}- Release Revision No: ${release.revision}" />

PMD Rule file (pmdRules.xml) is placed inside ${basedir}/docs/pmdRules/”

Here I have used ag-pmd-report.xslt to get look and feel of the generated report.

Following is Generated PMD Report.

Report displays number of violations in each file and their priority levels
Following is screen-shot of it.
eg :


It displays the detailed violations of each file When you click on each file.


Posted in Uncategorized