Friday, 15 April 2011

Add your own Code Template in Eclipse

If you are using Eclipse as your primary development IDE, then you may want to know about Code templates in Eclipse. Code templates are certain user defined (some are available by default) templates which can assist in rapid code writing. Not only code templates increase your code writing speed, but it also add consistency across the code.
To add a code template, all you need to do is to write first character and then press CTRL + SPACE. For example, in Eclipse write tr and press ctrl+space. It will add a try-catch block in your editor.

User defined code templates

You can defined your own code templates. Just goto Windows > Preferences > Java > Editor > Templates.
You can click on New.. button to add your own code template.
eclipse-code-templates
Lets create our own code template. For this example, we will create a template which will check if a local variable is null or not, if its null then it will throw a NullPointerException.
Open Template editor from above path and press New.. Then enter following details.
Name: npe
Description: To check if a local variable is null or not.
Pattern:
if (${arg:localVar} == null)
throw new ${exception:link(NullPointerException,IllegalArgumentException)}("${arg:localVar} is null");

And press Ok to save the template.
Now go to any editor window in Eclipse and press npe and press CTRL + SPACE. You will see a suggestion window which will display you an option to select the npe code template.

Introduction to Apache Maven: A build framework & build automation tool

For a quite while I had been using Ant build tool for building my Java projects. Since few days I have been switching to Apache Maven, an open source build framework that can be used to build almost all the projects in Java, .Net and other platforms. Maven was created by Sonatype’s Jason van Zyl in 2002.

What is Maven?

Maven, a Yiddish word meaning accumulator of knowledge, was originally started as an attempt to simplify the build processes in the Jakarta Turbine project. Maven is really a process of applying patterns to a build infrastructure in order to provide a coherent view of software projects.

Maven is a build tool

maven-build-tool-command-prompt
Maven 2.0 is based around the central concept of a build lifecycle. What this means is that the process for building and distributing a particular artifact (project) is clearly defined.
A Build Lifecycle is Made Up of Phases. Each of these build lifecycles is defined by a different list of build phases, wherein a build phase represents a stage in the lifecycle.

Maven is dependency management tool

maven-dependency-diagram
Dependency management is one of the features of Maven that is best known to users and is one of the areas where Maven excels. There is not much difficulty in managing dependencies for a single a project, but when you start getting into dealing with multi-module projects and applications that consist of tens or hundreds of modules this is where Maven can help you a great deal in maintaining a high degree of control and stability.

A Documentation tool

maven-documentation-screen
Maven helps you to generate documentation of your project and create a Project Site. Not only does it generates the site code, but it can deploy the website on a server. Maven has several reports that you can add to your web site to display the current state of the project. These reports take the form of plugins, just like those used to build the project.
Internationalization in Maven is very simple, as long as the reports you are using have that particular locale defined.

Objectives of Maven

  • Make the development process visible or transparent
  • Provide an easy way to see the health and status of a project
  • Decreasing training time for new developers
  • Bringing together the tools required in a uniform way
  • Preventing inconsistent setups
  • Providing a standard development infrastructure across projects
  • Focus energy on writing applications

Project Object Model (pom.xml)

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. Examples for this is the build directory, which is target; the source directory, which is src/main/java; the test source directory, which is src/main/test; and so on.
The POM was renamed from project.xml in Maven 1 to pom.xml in Maven 2. Instead of having a maven.xml file that contains the goals that can be executed, the goals or plugins are now configured in the pom.xml. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.

POM Sample

<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-core-api-container</artifactId>
<name>Cargo Core Container API</name>
<version>0.7-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies/>
<build/>
[...]

* project – root
* modelVersion – should be set to 4.0.0
* groupId – the id of the project’s group.
* artifactId – the id of the artifact (project)
* version – the version of the artifact under the specified group

Build Profiles in Maven

Profiles are specified using a subset of the elements available in the POM itself (plus one extra section), and are triggered in any of a variety of ways. They modify the POM at build time, and are meant to be used in complementary sets to give equivalent-but-different parameters for a set of target environments (providing, for example, the path of the appserver root in the development, testing, and production environments). As such, profiles can easily lead to differing build results from different members of your team. However, used properly, profiles can be used while still preserving project portability. This will also minimize the use of -f option of maven which allows user to create another POM with different parameters or configuration to build which makes it more maintainable since it is runnning with one POM only.

Different types of Profile

* Per Project – Defined in the POM itself (pom.xml).
* Per User – Defined in the Maven-settings (%USER_HOME%/.m2/settings.xml).
* Global – Defined in the global maven-settings (%M2_HOME%/conf/settings.xml).
* Profile descriptor – a descriptor located in project basedir (profiles.xml)

Repositories in Maven

repository-maven-local-remoteA repository in Maven is used to hold build artifacts and dependencies of varying types. There are strictly only two types of repositories: local and remote. The local repository refers to a copy on your own installation that is a cache of the remote downloads, and also contains the temporary build artifacts that you have not yet released. The local and remote repositories are structured the same way so that scripts can easily be run on either side, or they can be synced for offline used. In general use, the layout of the repositories is completely transparent to the Maven user, however.

Declaring a Remote Repository

Downloading in Maven is triggered by a project declaring a dependency that is not present in the local repository (or for a SNAPSHOT, when the remote repository contains one that is newer). By default, Maven will download from the central repository (http://repo1.maven.org/maven2/).
To override this, you need to specify a repositories element as follows:
<project>
...
<repositories>
<repository>
<id>my-internal-site</id>
<url>http://myserver/repo</url>
</repository>
</repositories>
...
</project>

Plugins in Maven

Maven is really just a core framework for a collection of Maven Plugins. In other words, plugins are where much of the real action is performed, plugins are used to: create jar files, create war files, compile code, unit test code, create project documentation, and on and on. Almost any action that you can think of performing on a project is implemented as a Maven plugin.
Plugins are the central feature of Maven that allow for the reuse of common build logic across multiple projects. They do this by executing an “action” (i.e. creating a WAR file or compiling unit tests) in the context of a project’s description – the Project Object Model (POM). Plugin behavior can be customized through a set of unique parameters which are exposed by a description of each plugin goal (or Mojo).

Inspect your code in Eclipse using Eclipse Scrapbook feature

The java IDEs (eclipse, IRAD etc) contribute a scrapbook facility that can be used to try and evaluate Java expressions (such as code snippets). Java scrapbook errors are shown in the editor. Snippets are edited and evaluated in the Scrapbook page editor. In the editor you can select a code snippet, evaluate it, and display the result as a string in console.

Creating a Java Scrapbook Page

The scrapbook allows Java expressions, to be run, inspected, and displayed, under the control of the debugger. Exceptions are shown in the scrapbook itself.
A VM is launched for each scrapbook page in which expressions are being evaluated. The first time an expression is evaluated in a scrapbook, a VM is launched. The VM for a page will remain active until the page is closed, terminated explicitly (in the debugger or via the Stop the Evaluation button in the console), or when a System.exit() is evaluated.
  1. From the workbench window, do one of the following:
    • From the drop-down File menu ,click on the New button, select Other. Then select Java ->Java Run/Debug -> Scrapbook Page. Then click Next.
    • Enter any file name.
  2. In the File name field, type a name for the new page. The .jpage extension will be added automatically if you do not type it yourself.
  3. Your jpage is ready to use. You can add java code snippets and select them and run them directly.

You will see "Hello World" in console.

Reading/Parsing RSS feed using ROME

ROME is an open source tool to parse, generate and publish RSS and Atom feeds. Using Rome you can parse the available RSS and Atom feeds. Without bothering about format and version of RSS feed. The core library depends on the JDOM XML parser.
Atom is on the similar lines of RSS is another kind of feed. But it’s different in some aspects as protocol, payloads.
RSS is a method to share and publish contents. The contents may be any things from news to any little information. The main component is xml. Using xml you can share your contents on web. At the same time you are free to get what you like from others.

Why use Rome instead of other available readers

The Rome project started with the motivation of ‘ESCAPE’ where each letter stands for:
E – Easy to use. Just give a URL and forget about its type and version, you will be given a output in the format which you like.
S – Simple. Simple structure. The complications are all hidden from developers.
C – Complete. It handles all the versions of RSS and Atom feeds.
A – Abstract. It provides abstraction over various syndication specifications.
P – Powerful. Don’t worry about the format let Rome handle it.
E – Extensible. It needs a simple pluggable architecture to provide future extension of formats.

Dependency

Following are few dependencies:
J2SE 1.4+, JDOM 1.0, Jar files (rome-0.8.jar, purl-org-content-0.3.jar, jdom.jar)

Using Rome to read a Syndication Feed

Considering you have all the required jar files we will start with reading the RSS feed. ROME represents syndication feeds (RSS and Atom) as instances of the com.sun.syndication.synd.SyndFeed interface.
ROME includes parsers to process syndication feeds into SyndFeed instances. The SyndFeedInput class handles the parsers using the correct one based on the syndication feed being processed. The developer does not need to worry about selecting the right parser for a syndication feed, the SyndFeedInput will take care of it by peeking at the syndication feed structure. All it takes to read a syndication feed using ROME are the following 2 lines of code:
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build (new XmlReader (feedUrl));
Now it’s simple to get the details of Feed. You have the object.

The sample code is as follows.
import java.net.URL;
import java.util.Iterator;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * @author Hanumant Shikhare
 */
public class Reader {

public static void main(String[] args) throws Exception {

URL url = new URL("http://viralpatel.net/blogs/feed");
XmlReader reader = null;

try {

reader = new XmlReader(url);
SyndFeed feed = new SyndFeedInput().build(reader);
System.out.println("Feed Title: "+ feed.getAuthor());

for (Iterator i = feed.getEntries().iterator(); i.hasNext();) {
SyndEntry entry = (SyndEntry) i.next();
System.out.println(entry.getTitle());
}
} finally {
if (reader != null)
reader.close();
}
}
}

Understanding the Program

Initialize the URL object with the RSS Feed or Atom url. Then we will need XMLReader object which will then take URL object, as its constructor argument. Initialize the SyndFeed object by calling the build(reader) method. This method takes the XMLReader object as an argument.

References

https://rome.dev.java.net/
http://www.intertwingly.net/wiki/pie/Rss20AndAtom10Compared
http://www.rss-specifications.com

Thursday, 14 April 2011

Spring – How to pass a Date into bean property (CustomDateEditor )


Simple method may not work
Generally, Spring developer are not allow to pass a date format parameter into bean property via DI.

For example,

public class CustomerService
{
Date date;

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

}

Bean configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="customerService" class="com.services.CustomerService">
<property name="date" value="2010-01-31" />
</bean>

</beans>

Run it

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mkyong.customer.services.CustomerService;

public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});

CustomerService cust = (CustomerService)context.getBean("customerService");
System.out.println(cust.getDate());
}
}

Error message prompt.

Caused by: org.springframework.beans.TypeMismatchException:
Failed to convert property value of type [java.lang.String] to
required type [java.util.Date] for property 'date';

nested exception is java.lang.IllegalArgumentException:
Cannot convert value of type [java.lang.String] to
required type [java.util.Date] for property 'date':
no matching editors or conversion strategy found

Solution

There are two solutions available.

1. Factory bean

Declare a dateFormat bean, and reference it as a factory bean from the date property. The factory method will call the SimpleDateFormat.parse() menthod to convert the String into Date object automatically.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>

<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
<property name="date">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-01-31" />
</bean>
</property>
</bean>

</beans>

2. Property editors (CustomEditorConfigurer + CustomDateEditor)

Declare a CustomDateEditor class to convert the String into java.util.Date properties.

<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">

<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />

</bean>

Register the CustomDateEditor in CustomEditorConfigurer, so that the Spring will convert the properties whose type is java.util.Date.


<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>

Bean configuration file.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">

<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />

</bean>

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>

<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
<property name="date" value="2010-02-31" />
</bean>

</beans>




USING SPRING’S STOREDPROCEDURE

One very useful portion of the Spring Framework is the StoredProcedure wrapper’s and the RowMapper objects. Together these allow you to call a stored procedure and then parse the result set back into a collection of objects with very little pain. Below is an example of how to do just this for a simple query like a user query.

public class MyStoredProcedure extends StoredProcedure {

public MyStoredProcedure (DataSource ds, String spname,
Map map, String sqlOutKey, Integer returnType,
RowMapper rowmapper) {
super();
setDataSource(ds);

/* resultset has to be declared first over other declare parameters */
if (rowmapper != null) {
declareParameter(new SqlReturnResultSet(sqlOutKey, rowmapper));
}

if (map != null) {
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String key = (String) itr.next();
Integer value = (Integer) map.get(key);
declareParameter(new SqlParameter(key, value.intValue()));
}
}

/*
         * sql out paramter has to be declared based on the order in stored
         * procedures, In all our stored procedures we have it after input
         * parameters
         */
if (returnType != null) {
declareParameter(new SqlOutParameter(sqlOutKey, returnType
.intValue()));
}

setSql(spname);
compile();
}
}

Next, we have the Mapper class:

public class UserMapper implements RowMapper {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUserId(rs.getString(Constants.USER_ID));
user.setFirstName(rs.getString(Constants.FIRST_NAME));
user.setLastName(rs.getString(Constants.LAST_NAME));
user.setOrganizationName(rs.getString(Constants.ORGANIZATION_NAME));
return user;
}
}

Next, we have to query the actual stored procedure from a DAO. Here’s a sample method that would do just such a thing:

public Collection searchUsers(User user) throws Exception {

Map lhm = new LinkedHashMap(4);
lhm.put(Constants.USER_ID, new Integer(Types.VARCHAR));
lhm.put(Constants.FIRST_NAME,new Integer(Types.VARCHAR));
lhm.put(Constants.LAST_NAME,new Integer(Types.VARCHAR));
lhm.put(Constants.ORGANIZATION_NAME,new Integer(Types.VARCHAR));

UserMapper mapper = new UserMapper();

// Call Stored Procedure
EntitlementsStoredProcedure proc = new EntitlementsStoredProcedure(
ds, StoredProcedureConstants.USER_SEL, lhm,
Constants.RESULTSET, null, mapper);

// Collect the criteria for the search
Map map = new LinkedHashMap(4);
map.put(Constants.USER_ID, user.getUserId());
map.put(Constants.FIRST_NAME, user.getFirstName());
map.put(Constants.LAST_NAME, user.getLastName());
map.put(Constants.ORGANIZATION_NAME, user.getOrganizationName());

Map results = proc.execute(map);
List resultList = (LinkedList)results.get(Constants.RESULTSET);

//iterate of results list and print
for (Iterator it=resultList.iterator(); it.hasNext(); ) {
User user1 = (User)it.next();
System.out.println(user1);
}

return resultList;
}

That’s all there is to it! This shows just how simple it is to do queries in an object oriented way, and have generic row mappers. There are full object relational mapping solutions, such as Hibernate, that do a great job of solving the working with relational data in an OO way paradigm, but they take a LOT of configuration and can be daunting if you’re not accustomed to working with them. This solution, however, I feel works very well in simpler scenarios. It also allows someone who is used to looking at code to quickly read through and get an idea of how to use this.

One point to note: this gets even simpler when using generics that are introduced in Java 1.5.

The Spring Jdbc Template for database access - Tutorial