Pages

Spring MVC - Exception Handling

Hope you knows MVC. :)
When you comes to Spring MVC there are multiple ways that you can handle exceptions. So in here I will show you some of ways that how to handle exceptions in a proper way.
If you have more than good solutions feel free to add it as comments.
Following solutions are one way to handle exceptions in web application, other than this you can use web.xml error-page tag to handle exceptions but it has many drawbacks. 

1. Here is the default way to handle exceptions. You can use another page to show some user friendly message instead of ugly message. 

 @RequestMapping(value = "/exception1", method = RequestMethod.GET)  
   public String exception1() {  
     throw new NullPointerException("Throwing null pointer exception");  
   }  
   @ExceptionHandler(NullPointerException.class)  
   public String handleException1(NullPointerException e) {  
     return "error/exception1";  
   }  

2. We generate the following exception using ajax and show it in same page as inline html.

Here is the code snippet in controller

 @RequestMapping(value = "/exception2", method = RequestMethod.GET)  
   public String exception2() {  
     throw new IndexOutOfBoundsException("Ajax Exception inline text");  
   }  
   @ExceptionHandler(IndexOutOfBoundsException.class)  
   @ResponseBody  
   public String handleException2(IndexOutOfBoundsException ex) {  
     return ex.getMessage();  
   }  

Here is Ajax code snippet

 function exception2()  
 {  
   $.ajax({  
     type: 'GET',  
     url: "/exception2",  
     success: function(data)  
     {  
       $('#message1').empty().html(data).show();  
     },  
     error:function(data)  
     {  
       alert('error');  
     }  
   });  
   return false;  
 }  

3. Following shows that ugly page with some custom messages (That would be nice :D)
It shows the HTTP status code in that page

 @RequestMapping(value = "/exception3", method = RequestMethod.GET)  
   public String exception3() {  
     throw new IllegalStateException("Exception3 with response status");  
   }  
   @ExceptionHandler(IllegalStateException.class)  
   @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "exception3")  
   public ModelAndView handleException3(IllegalStateException ex, HttpServletResponse response) throws IOException {  
     return new ModelAndView();  
   }  

Here are some of ways to handle exceptions in spring mvc. You can found the complete project here
https://github.com/rajithd/spring-mvc-exception-handling

Enable Remote access to Mysql Server [Ubuntu]

When your installing mysql from apt get you would face this problem. Actually its not a problem but a security for our local mysql server to prevent access from others. :)

If you want enable the remote access here are the steps. Just 3 steps

Step 1
Edit the mysql configuration file
 sudo gedit /etc/mysql/my.cnf  

Comment the following line
 bind-address = 127.0.0.1  
  • To comment add # 
Save the my.cnf file.

Step 2
Restart the mysql server
 sudo /etc/init.d/mysql restart  

Step 3
Grant database access to particular IP address
 GRANT ALL ON foo.* TO bar@'202.54.10.20' IDENTIFIED BY 'PASSWORD';  

That's IT. You just unsecure your database :P

Advance JAXB - XML into Java Map

In this article I will show you how to decode XML into a java Hashmap. So always there are multiple ways. But I will show you how you can do this in a simple and more responsible way.

JAXB is referred as Java Architecture for XML Binding. In this tutorial we are only use annotation for that. We don't require any third party libraries for this because java provide all the additional JAXB annotation for us.

Here is some good article about JAXB

OK first thing first.
Lets create a XML file.
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
 <bookStore>  
   <books>  
     <book bookId="1">  
       <name>book1</name>  
       <author>author1</author>  
     </book>  
     <book bookId="2">  
       <name>book2</name>  
       <author>author2</author>  
     </book>  
   </books>  
 </bookStore>  

Here is the sample and most popular tutorial XML :P

So after this we will write three domain classes for this and a adapter class to get the map.
Yes we need to have 3 domain java classes -> BookStore, Books and Book
and BookAdapter java class to create the hashmap.

Here is the BookStore class.
 @XmlRootElement(name = "bookStore")  
 public class BookStore {  
   private HashMap<String,Book> books;  
   @XmlElement  
   @XmlJavaTypeAdapter(BookAdapter.class)  
   public HashMap<String, Book> getBooks() {  
     return books;  
   }  
   public void setBooks(HashMap<String, Book> books) {  
     this.books = books;  
   }  
 }  

Some basic JAXB annotation are there with @XmlJavaTypeAdapter. We use this adapter class to marshal and unmarshal the xml.
So here is the Books java class
 public class Books {  
   private ArrayList<Book> books;  
   @XmlElement(name = "book")  
   public ArrayList<Book> getBooks() {  
     return books;  
   }  
   public void setBooks(ArrayList<Book> books) {  
     this.books = books;  
   }  
 }  

And here is the Book java class
 public class Book {  
   private String bookId;  
   private String name;  
   private String author;  
   @XmlAttribute  
   public String getBookId() {  
     return bookId;  
   }  
   public void setBookId(String bookId) {  
     this.bookId = bookId;  
   }  
   @XmlElement  
   public String getName() {  
     return name;  
   }  
   public void setName(String name) {  
     this.name = name;  
   }  
   @XmlElement  
   public String getAuthor() {  
     return author;  
   }  
   public void setAuthor(String author) {  
     this.author = author;  
   }  
 }  

So the basic are done. Now we have to write the adapter class to do the magic(actually there is no magic at all.)

Here is the BookAdapter java class
 public class BookAdapter extends XmlAdapter<Books,Map<String,Book>> {  
   // we only going to change this method. Because we are only doing un marshaling  
   // xml into map  
   @Override  
   public Map<String, Book> unmarshal(Books v) throws Exception {  
     Map<String, Book> map = new HashMap<String, Book>();  
     for(Book book : v.getBooks()){  
       map.put(book.getBookId(),book);  
     }  
     return map;  
   }  
   @Override  
   public Books marshal(Map<String, Book> v) throws Exception {  
     return null;  
   }  
 }  

So in here we only consider about unmarshal because our objective is to decode xml into hashmap.

And finally here is the App class with main method
 public class App {  
   public static void main(String[] args) {  
     File file = new File("book-store.xml");  
     try {  
       JAXBContext jaxbContext = JAXBContext.newInstance(BookStore.class);  
       Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();  
       BookStore bookStore = (BookStore) unmarshaller.unmarshal(file);  
       HashMap<String, Book> bookMap = bookStore.getBooks();  
       for (Map.Entry<String, Book> entry : bookMap.entrySet()) {  
         System.out.println("Key = " + entry.getKey());  
         System.out.println("value = " + entry.getValue().getAuthor() + " " + entry.getValue().getName());  
         System.out.println("=========================");  
       }  
     } catch (JAXBException e) {  
       e.printStackTrace();  
     }  
   }  
 }  

Full Project : https://github.com/rajithd/jaxb-sample


Is Clean Code Really matters ?

So, here we are again, IS CLEAN CODE REALLY MATTERS ?
YES, YES and HELL YES.

And the other question is WHAT FOR ?
That's what we talk about here..

OK lets go for it..
What is Clean code ? Actually we don't have the exact definition for this. But there are some definitions that create by geniuses. Below are some of these...

Bjarne Stroustrup, Inventor C++ and author of The C++ Programming Language
 I like my code to be elegant and efficient. The logic should be straightforward to make it hard  
 for bugs to hide, the dependencies minimal to ease maintenance, error handling complete  
 according to an articulated strategy, and performance close to optimal so as not to tempt  
 people to make the code messy with unprincipled optimizations. Clean code does one thing  
 well.  

Dave Thomas, founder of OTI, godfather of the Eclipse strategy,
 Clean code can be read, and enhanced by a developer other than its original author. It has  
 unit and acceptance tests. It has meaningful names. It provides one way rather than many  
 ways for doing one thing. It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.  

Michael Feathers, author of working Effectively with Legacy Code,
 I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought  
 about by the code’s author, and if you try to imagine improvements, you’re led back to  
 where you are, sitting in appreciation of the code someone left for you—code left by someone  
 who cares deeply about the craft.  

and there are many more ...

But the HELL Question remains... WHY WE NEED THIS ? WHY WE NEED CLEAN CODE ?
If your a programmer with more than one year you know what I mean..

First take a look at bad code or a mess code.
Suppose you get a new requirement and you need to add the new functionality to your existing code which is really bad and messy. Before adding any new thing to your code first you need to understand the exiting code. That means you need to READ your existing code. Since its a bad code you will go through really pain full time to understand what the code says. For example imaging a code with no comments, no meaning full variables, no meaning full function definitions with hell of big line of codes that does too many things within single code block , this will drive you crazy.
So this will take more than time than you'r expecting(Or your PM) to read and understand only others code. Every programmer knows about the damn dead lines and our heads will bump up.
If it is a clean code it must full fill the READABILITY.

That's one of the basic thing that each and every code must have. But there are more. Formatting, Unit testing, avoid writing bad comments, Error handling  are some of. So will talk about all of these things in near future. Basically we will talk HOW TO WRITE CLEAN CODE. stay tuned :)




How to restore single table from large mysql dump ?

In this post I will briefly explain how to restore single table from a large mysql dump file. Its not that much hard what it says :)

BTW, first you need to know how to dump the database, so no worries ,some time back I wrote a blog post how to take a database dump. Take a look at this.

OK so lets get back to topic,
Here is the simple command that you can make it happen.

 sed -n -e '/CREATE TABLE.*mytable/,/CREATE TABLE/p' mydump.sql > table.sql  

mytable is the table name that you want to extract from the dump file.
mydump is the large dump file that contains dumped data
table is the file that will create after . (contains table creation data as well as insert data)
SO that's all. enjoy it :)

Easy Glance with Hadoop

Hadoop is a framework for distributed processing large amount of data set across clusters of computers. Hadoop is an open source framework under Apache.

So today I'm not going to show you how to setup hadoop in your machine. You can find some article in here. If you want to setup multi-node cluster here is another article. Also some time back I blogged about how to setup single node hadoop cluster and you can find it here.

When you follow the above tutorials you can simply setup the single node and multi node hadoop cluster. But when I did that I got lots of problems when setting up a multi node cluster (single setup is a straight forward). So in this post I will list down some of issues and also the solutions for that. Also feel free to add any issues that you found as comments.

Before that you need to keep in mind to always check the hadoop logs. After you start the hadoop services or when running map reduce task always check the hadoop logs. To check your job logs, there are two ways you can do it. Either from browser or console. Job logs are created in "hadoop/logs/userlogs/job_id/*".

Here are the issues and solutions for Hadoop multi node cluster

Issue 1 :
=====
  • ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: java.io.IOException: Incompatible namespaceIDs
Solution 
=====
  • If you got this exception in hadoop namenode log what you need to do is copy the namenode namespace id and paste it in every data node namespace id. (including master data node, if your master also act as datanode)
    • vi ${path/to/hadoop/datastore}dfs/name/current/VERSION
    • Copy namespace id value
    • vi ${path/tp/hadoop/datastore/dfs}data/current/VERSION
    • Paste it as in namespace id
  • ${path/to/hadoop/datastore} --> you can find it in hadoop/conf/core-site.xml

Issue 2:
======

  • ERROR org.apache.hadoop.security.UserGroupInformation: PriviledgedActionException as:rajith cause:java.io.IOException: File /home/rajith/softwares/hadoop-temp/mapred/system/jobtracker.info could only be replicated to 0 nodes, instead of 12012-09-14 13:09:50,683 INFO org.apache.hadoop.ipc.Server: IPC Server handler 7 on 54310, call addBlock(/home/rajith/softwares/hadoop-temp/mapred/system/jobtracker.info, DFSClient_-632414254, null) from127.0.0.1:42296: error: java.io.IOException: File /home/rajith/softwares/hadoop-temp/mapred/system/jobtracker.infocould only be replicated to 0 nodes, instead of 1java.io.IOException: File /home/rajith/softwares/hadoop-temp/mapred/system/jobtracker.info could only be replicated to 0 nodes, instead of 1at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:1558) at org.apache.hadoop.hdfs.server.namenode.NameNode.addBlock(NameNode.java:696)
Solution
======
  • If you got this exception on your hadoop namenode log what you need to is be patient. :)
    • First start the datanode (start-dfs.sh) and wait until the datanode starts. This may take 2min to start the datanode. You can verify it in logs.
    • After that start the job tracker (start-mapred.sh)
Issue 3:
======

  • Error reading task outputhttp://localhost:50060/tasklog?plaintext=true&attemptid=attempt_201209141426_0001_m_000002_0&filter=stdout12/09/14 14:27:41 WARN mapred.JobClient: Error reading task outputhttp://localhost:50060/tasklog?plaintext=true&attemptid=attempt_201209141426_0001_m_000002_0&filter=stder
Solution
======
  • If you got this error that means you need to remove 127.0.0.1  localhost map in /etc/hosts in slave machine.
  • Restart your hadoop nodes and check the logs.
Issue 4:
=======
  • java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:691)
at org.apache.hadoop.hdfs.server.datanode.DataXceiverServer.run(DataXceiverServer.java:133)
at java.lang.Thread.run(Thread.java:722)

Solution
========
  • If you got the above exception in datanode check the max number of process by using the following command
    • ulimit -u
      • If you got 1024 or around something increase the value to get rid of that error
    • To increase add following lines to your /etc/security/limit.conf
      • * soft nproc 8094
      • * hard nproc 8094
    • Restart machine to take effect

Spring Security Part 2 – Password Encryption, Customize 404 and 403 error page

Here is the part 2 of spring security post. In this post I will show you how to encrypt password using MD5 and customize 403 and 404 status code error pages. If you haven't read part 1 just click here. Because we continue the part 1 project here.

Download the Completed Project : http://www.mediafire.com/?tkm2vd9ro7oqhmu

First we will look at how to add password encryption to our project.
Edit the spring security file like below.

 <authentication-manager>  
     <authentication-provider>  
       <password-encoder hash="md5"/>  
       <jdbc-user-service data-source-ref="dataSource"  
                 users-by-username-query="select username,password, 'true' as enabled from USER_DETAILS where username=?"  
                 authorities-by-username-query="select USER_DETAILS.username , USER_AUTH.AUTHORITY as authorities from USER_DETAILS,USER_AUTH  
            where USER_DETAILS.username = ? AND USER_DETAILS.username=USER_AUTH.USERNAME "  
           />  
     </authentication-provider>  
   </authentication-manager>  

that's it. We just added the md5 password encryption to our project.

To test this we need to edit out test-data.sql file like below.

 insert into USER_DETAILS values ('user','202cb962ac59075b964b07152d234b70'); -- password - 123  
 insert into USER_DETAILS values ('admin','21232f297a57a5a743894a0e4a801fc3'); -- password - admin  
 insert into USER_AUTH values ('user', 'ROLE_USER');  
 insert into USER_AUTH values ('admin', 'ROLE_ADMIN');  


Now we will look at how to customize the error pages based HTML status code. Otherwise the default error pages are very ugly. :D If you don't have proper understanding about HTML status codes take a look at this.

In here we are handling 403(Permission denied) and 404(resource not found) status code. Because if you are dealing with spring security we definitely need to handle these two status code.(Not a must but a good practice)

There can be more that one way to do this. Changing spring security xml and add additional tag will do this but here we are not going to do that. Always keep it simple. So we are going to edit the web.xml and add error page tag to this task.

before that we need to create 404 and 403 customize error pages. Create two jsp pages and place it under webapp directory (Not inside WEB-INF directory).

after that change the web.xml and add below tags.

 <error-page>  
     <error-code>404</error-code>  
     <location>/404.jsp</location>  
   </error-page>  
   <error-page>  
     <error-code>403</error-code>  
     <location>/403.jsp</location>  
   </error-page>  

thats it. We just customize our error pages

These are some basic things that we can do with spring security. In near future I'll come up with more interesting article about spring security with CAS integration , LDAP integration and many more. Stay Tuned :)

Spring security Part 1 - Simple Login application with database

Spring Security Part 1 – Simple Login application with database

What is Spring Security?
Spring security is a framework that provides security solution, handling authentication and authorization at both the web request level and the method level. Spring security handle security in two ways. One is secure web request and other one is restrict access at the URL level. Spring security uses servlet filters.

In this post I'm going to create a simple web application that handle the login authentication and authorization.

Download project :  http://www.mediafire.com/?bb9x88uxvkb0uuv

Before create the project need to execute some queries to mysql to create a new database , tables and add some sample data.

create-table.sql
 CREATE DATABASE IF NOT EXISTS `spring-test`;  
 -- create user  
 CREATE USER 'user'@'localhost' IDENTIFIED BY 'test';  
 GRANT ALL ON spring-test.* TO 'user'@'localhost';  
 USE `spring-test`;  
 CREATE TABLE USER_DETAILS (  
 USERNAME VARCHAR(10) NOT NULL,  
 PASSWORD VARCHAR(32) NOT NULL,  
 PRIMARY KEY (USERNAME)  
 );  
 CREATE TABLE USER_AUTH (  
 USERNAME VARCHAR(10) NOT NULL,  
 AUTHORITY VARCHAR(10) NOT NULL,  
 FOREIGN KEY (USERNAME) REFERENCES USER_DETAILS(USERNAME)  
 );  


test-data.sql
 insert into USER_DETAILS values ('user','123');  
 insert into USER_DETAILS values ('admin','admin');  
 insert into USER_AUTH values ('user', 'ROLE_USER');  
 insert into USER_AUTH values ('admin', 'ROLE_ADMIN');  


After that I create a web project using maven and add below dependencies to pom.xml

<properties>
        <spring.version>3.0.5.RELEASE</spring.version>
</properties> 
<dependencies>  
     <dependency>  
       <groupId>javax.validation</groupId>  
       <artifactId>validation-api</artifactId>  
       <version>1.0.0.GA</version>  
     </dependency>  
     <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-core</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-web</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-webmvc</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-jdbc</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <!-- Spring Security -->  
     <dependency>  
       <groupId>org.springframework.security</groupId>  
       <artifactId>spring-security-core</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <dependency>  
       <groupId>org.springframework.security</groupId>  
       <artifactId>spring-security-web</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <dependency>  
       <groupId>org.springframework.security</groupId>  
       <artifactId>spring-security-config</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <dependency>  
       <groupId>org.springframework.security</groupId>  
       <artifactId>spring-security-taglibs</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <dependency>  
       <groupId>org.springframework.security</groupId>  
       <artifactId>spring-security-acl</artifactId>  
       <version>${spring.version}</version>  
     </dependency>  
     <!-- jstl -->  
     <dependency>  
       <groupId>javax.servlet</groupId>  
       <artifactId>jstl</artifactId>  
       <version>1.2</version>  
     </dependency>  
     <!-- MySQL database driver -->  
     <dependency>  
       <groupId>mysql</groupId>  
       <artifactId>mysql-connector-java</artifactId>  
       <version>5.1.9</version>  
     </dependency>  
     <dependency>  
       <groupId>c3p0</groupId>  
       <artifactId>c3p0</artifactId>  
       <version>0.9.1</version>  
     </dependency>  
   </dependencies>  

After that change the web.xml like this

 <!DOCTYPE web-app PUBLIC  
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
     "http://java.sun.com/dtd/web-app_2_3.dtd" >  
 <web-app>  
   <display-name>spring-security-login</display-name>  
   <servlet>  
     <servlet-name>login</servlet-name>  
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
     <load-on-startup>1</load-on-startup>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>login</servlet-name>  
     <url-pattern>/</url-pattern>  
   </servlet-mapping>  
   <listener>  
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
   </listener>  
   <context-param>  
     <param-name>contextConfigLocation</param-name>  
     <param-value>  
       /WEB-INF/login-servlet.xml,  
       /WEB-INF/login-security.xml,  
       /WEB-INF/login-service.xml  
     </param-value>  
   </context-param>  
   <!-- Spring Security -->  
   <filter>  
     <filter-name>springSecurityFilterChain</filter-name>  
     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
   </filter>  
   <filter-mapping>  
     <filter-name>springSecurityFilterChain</filter-name>  
     <url-pattern>/*</url-pattern>  
   </filter-mapping>  
   <welcome-file-list>  
     <welcome-file>login.jsp</welcome-file>  
   </welcome-file-list>  
 </web-app>  

Now I need to create login-servlet.xml, login-security.xml and login-service.xml spring configuration files. In this example we are using c3p0 connection pool with Mysql database.

 Here is the login-servlet.xml file
 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
     xmlns:context="http://www.springframework.org/schema/context"  
     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-3.0.xsd  
     http://www.springframework.org/schema/context  
     http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
   <context:component-scan base-package="rd.controller"/>  
   <bean id="internalResourceResolver"  
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
     <property name="prefix" value="/WEB-INF/views/"/>  
     <property name="suffix" value=".jsp"/>  
   </bean>  
   <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>  
   <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>  
   <bean id="placeholderConfig"  
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
     <property name="locations">  
       <list>  
         <value>classpath:login.properties</value>  
       </list>  
     </property>  
   </bean>  
 </beans>  


Here is the login-security.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <beans:beans xmlns="http://www.springframework.org/schema/security"  
        xmlns:beans="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-3.0.xsd  
 http://www.springframework.org/schema/security  
 http://www.springframework.org/schema/security/spring-security-3.0.xsd">  
   <beans:import resource="login-service.xml"/>  
   <http>  
     <intercept-url pattern="/home*" access="ROLE_USER,ROLE_ADMIN" />  
     <intercept-url pattern="/admin*" access="ROLE_ADMIN" />  
     <form-login login-page="/login.jsp" default-target-url="/home" authentication-failure-url="/login.jsp?error=true"/>  
     <logout logout-success-url="/login.jsp" />  
     <anonymous username="guest" granted-authority="ROLE_GUEST"/>  
     <remember-me/>  
   </http>  
   <authentication-manager>  
     <authentication-provider>  
       <!--<user-service>-->  
         <!--<user name="admin" password="secret" authorities="ROLE_ADMIN,ROLE_USER" />-->  
         <!--<user name="user1" password="1111" authorities="ROLE_USER" />-->  
       <!--</user-service>-->  
       <jdbc-user-service data-source-ref="dataSource"  
           users-by-username-query="select username,password, 'true' as enabled from USER_DETAILS where username=?"  
           authorities-by-username-query="select USER_DETAILS.username , USER_AUTH.AUTHORITY as authorities from USER_DETAILS,USER_AUTH  
            where USER_DETAILS.username = ? AND USER_DETAILS.username=USER_AUTH.USERNAME "/>  
     </authentication-provider>  
   </authentication-manager>  
 </beans:beans>  

Here is the login-service.xml
 <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-3.0.xsd">  
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
     <!--Driver name to connect to the database-->  
     <property name="driverClass">  
       <value>${login.jdbc.driver}</value>  
     </property>  
     <!--DB URL-->  
     <property name="jdbcUrl">  
       <value>${login.url}</value>  
     </property>  
     <!--DB User used to connect to the schema-->  
     <property name="user">  
       <value>${login.username}</value>  
     </property>  
     <!--Password required to access for the above user-->  
     <property name="password">  
       <value>${login.password}</value>  
     </property>  
     <!-- configuration pool via c3p0-->  
     <property name="acquireIncrement">  
       <value>${login.c3p0.acquireIncrement}</value>  
     </property>  
     <property name="idleConnectionTestPeriod">  
       <value>${login.c3p0.idleConnectionTestPeriod}</value>  
       <!-- seconds -->  
     </property>  
     <property name="maxPoolSize">  
       <value>${login.c3p0.maxPoolSize}</value>  
     </property>  
     <property name="maxStatements">  
       <value>${login.c3p0.maxStatements}</value>  
     </property>  
     <property name="minPoolSize">  
       <value>${login.c3p0.minPoolSize}</value>  
     </property>  
     <property name="initialPoolSize">  
       <value>${login.c3p0.initialPoolSize}</value>  
     </property>  
     <property name="maxIdleTime">  
       <value>${login.c3p0.maxIdleTime}</value>  
     </property>  
     <property name="acquireRetryAttempts">  
       <value>${login.c3p0.acquireRetryAttempts}</value>  
     </property>  
     <property name="acquireRetryDelay">  
       <value>${login.c3p0.acquireRetryDelay}</value>  
     </property>  
     <property name="breakAfterAcquireFailure">  
       <value>${login.c3p0.breakAfterAcquireFailure}</value>  
     </property>  
   </bean>  
 </beans>  


The login.jsp page looks like this. (Need to place is under webapp directory. But not in under WEB_INF directory)
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
 <html>  
 <head>  
   <title>Login</title>  
 </head>  
 <body>  
 <c:if test="${not empty param.error}">  
   <font color="red">  
     Login error. <br />  
     Reason : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}  
   </font>  
 </c:if>  
 <form method="POST" action="<c:url value="/j_spring_security_check" />">  
   <table>  
     <tr>  
       <td align="right">Username</td>  
       <td><input type="text" name="j_username" /></td>  
     </tr>  
     <tr>  
       <td align="right">Password</td>  
       <td><input type="password" name="j_password" /></td>  
     </tr>  
     <tr>  
       <td colspan="2" align="right">  
         <input type="submit" value="Login" />  
       </td>  
     </tr>  
   </table>  
 </form>  
 </body>  
 </html>  


home.jsp page
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
 <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>  
 <html>  
 <head>  
   <title>Home</title>  
 </head>  
 <body>  
   <a href=<c:url value="/j_spring_security_logout"/>>Logout</a><br/>  
   <sec:authorize ifAnyGranted="ROLE_ADMIN">  
     <h1>Only admin can see this</h1><br/>  
     <a href="admin"> Admin Home </a>  
   </sec:authorize>  
   <h1>Welcome</h1>  
 </body>  
 </html>  


admin-home.jsp page
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>  
 <html>  
 <head>  
   <title>Admin</title>  
 </head>  
 <body>  
   <a href=<c:url value="/j_spring_security_logout"/>>Logout</a><br/>  
   <h1>Only Admin allowed here</h1>  
 </body>  
 </html>  


After that you need to write two controller to retrieve home page and admin-home page. Here is the HomeController.java
 package rd.controller;  
 import org.springframework.stereotype.Controller;  
 import org.springframework.ui.Model;  
 import org.springframework.web.bind.annotation.RequestMapping;  
 import org.springframework.web.bind.annotation.RequestMethod;  
 @Controller  
 public class HomeController {  
   @RequestMapping(value = "/home" , method = RequestMethod.GET)  
   public String setUp(Model model){  
     return "home";  
   }  
 }  


Here is the AdminController.java
 package rd.controller;  
 import org.springframework.stereotype.Controller;  
 import org.springframework.ui.Model;  
 import org.springframework.web.bind.annotation.RequestMapping;  
 import org.springframework.web.bind.annotation.RequestMethod;  
 @Controller  
 public class AdminController {  
   @RequestMapping(value = "/admin" , method = RequestMethod.GET)  
   public String setUp(Model model){  
     return "admin-home";  
   }  
 }  


That's it. Run mvn clean install command to create war file. Copy the war file under tomcat/webapps directory and access the web app in your favorite browser.
url : localhost:<port>/spring-login/login.jsp

Test case 1 : Try to log with user as username 123 as password. You will get users home page.
Test case 2 : Try to log with admin as username admin as password. You will get users home page with visible admin page link.

In spring security part 2 I will modify this project and add remember me feature and md5 password encryption feature.

In near future Ill try to post some interesting article about spring security with CAS integration and LDAP integration. Stay tuned :)

Spring Security Part 2 - Password Encryption, Customize 403 and 404 error pages

Resolving "org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]Offending resource: ServletContext resource"

If you are new to spring security the below exception might get you confused.
"org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]Offending resource: ServletContext resource"

To resolve this you need to add the below maven dependency to your pom.xml(if your working with maven)

Thats it. Redeploy the app and you are done.

Need Java Distribution ? Here we go :)

In this post I will show you how to create Java distribution package in zip and tar.gz. To demonstrate this we use simple maven project. (Need a basic understanding about maven :) )

1. Create a simple maven project

  • mvn archetype:generate to create a sample maven project.
  • Select simple maven project that will create project.
2. Create a directory name assembly under main directory. Also create a distribution.xml file in it.This is the file that will create .zip and .tar.gz formats.


3.Add maven plugin to create distribution directories.



  • Change <mainclass>{add your main class}</mainclass>  and add your main class.
4. Run mvn clean install from your project and it will create both .zip and .tar.gz distribution under your <project>/target directory. Unzip the directory and you can see under the bin folder you have the all the execution file (windows and linux)

Spring Quartz Scheduler

Scheduling a task is a important aspect when comes to EE programming. So In this article I'm going to show you how to schedule a task using one of the popular scheduler framework Quartz with spring integration.

Quartz : http://quartz-scheduler.org/
Spring : http://www.springsource.org/

Sample Project : https://github.com/rajithd/SpringQuartzSchedulerExample

Hadoop Architecture

Here I found some valuable presentation about hadoop architecture. :)