Defensive programming – Defend your Code

July 12, 2010 at 9:00 PM | Posted in Defensive Programming, Java, Programming, Techniques Programming | Leave a comment
Tags: , ,

The hypocrisy of War is to be Defensive while Fighting . Today a Software engineer’s life is largely at War because of the stringent time lines, Agile requirments and change of technology world wide. Defending our code is becoming largely important and this white paper serves as a starting point for defensive techniques. Read on and explore ….White Paper -Defensive Programming

A day was there when we were called programmers and no longer that stands.

How to build a simple MVC application using Spring 3.0 MVC

January 31, 2010 at 8:31 PM | Posted in Spring 3.0 | Leave a comment
Tags: , , , , , ,

Sample Web Application using Spring 3.0 MVC  

Spring 3.0 consists of a MVC framework which implements MVC in a very efficient and flexible manner. The use of annotations makes it easy to implement and readable.  

The controller part of MVC can be a basic Java class with a class level annotation @Controller . (No more configuration of XMLs) and URL mappings can be directly put as annotations methods (No need to implement or extend a Class). Adding to the flexibility URL mappings can be put from Class level to Method level and there is provision to Nest the URL mappings.  

The Model and View is combined to an object ModelAndView .The object that need to written to response stream can be added to a Map object (View)with key as the alias for the object. (Just like a setAttribute method of ServletRequest) and View is configurable using the view resolvers with inbuilt support for JSP, velocity etc , extensible using cusom view resolvers  

More details read on the spring-framework-reference document for Spring 3.0 http://www.springsource.org/  

Coming to the example we are trying to build an application to fetch the User details from a data source by giving input as user’s first name.  

The screens would look like below  

  

Give input as ‘Jon’ output would be like  

  

NB: Data source for the example is a Map object with Keys as user’s first name
If a user is not found the screen would be like below  

  

Lets do it noww !!!!  

Starting with controller part ,controller would look like below  


package com.springapp.web;

 

import java.util.HashMap;
import java.util.Map;  

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;  

/**
* Controller Class giving Services for Customer Enquiry
* @author arunvg
*
*/
@Controller
public class CustomerEnquiry {  

/**
* Returns the Name of the application .
* The return value is written into the response body.
* This method can be called as a Web Service
* @return
*/
@RequestMapping(value = "/applicationName", method = RequestMethod.GET)
@ResponseBody
public String myName(){
return "UserEnquiry";  

}  

/**
* Returns the input page of Customer Enquiry
* @return
*/
@RequestMapping(value = "/enquiryPage", method = RequestMethod.GET)
public String inputpage(){
return "userDetail.jsp";  

}  

/**
* Returns the ModelAndView object with userDetails
* and if cannot find the user will return the ModelAndView object with message
* @param firstName
* @return
*/
@RequestMapping(value = "/findDetail", method = RequestMethod.POST)
public ModelAndView findDetail(@RequestParam("firstName") String firstName){
UserDetailsDao dao = new UserDetailsDao();  

Map model = new HashMap();
UserDetails userDetails = dao.getUserDetail(firstName);  

model.put("userDetails", userDetails);  

if(null == userDetails){
model.put("message", "No Data Found");
}
return new ModelAndView("userDetail.jsp",model);  

}  

}
  

Let us analyse the CustomerEnquiry class, the @Controller annotation tells the Spring Frame work that this Class would act as a Controller with URL requests mapped to it. (Note that because of the use of annotations we don’t extend any class or implement an interface and so no framework related methods on this class, just our Custom logic )
Primarily we use the custom methods inputpage() and findDetail() for initial loading and finding the details.  

inputpage() : The soul purpose of this method is to redirect the request for page to the corresponding JSP. How will the framework resolve that which request is to be mapped to this method ?
For that we use the annotation @RequestMapping(value = "/enquiryPage", method = RequestMethod.GET)  

The value of the annotation tells which URL pattern needs to be mapped to this method and method will tell what type of servlet request will come for this method.  

Note that the method returns a String ,So how the framework knows that this return is asking for a forward to JSP ?  

Well this is where View Resolvers come into picture. Using view resolvers we can specify the view we need .Spring supports JSP, Velocity etc.. and we can write our own View resolver (case if the view needs to be a PDF ) (For more details see the Spring reference Document)  

And now what if the method was supposed to write it to the Response stream rather than forwarding to a view technology , the method myName() tells the story . Another tag is added in that method , @ResponseBody this tells that whatever is returned shold be written into the response stream .  

findDetail()  

This method just gets the firstName of user @RequestParam("firstName") in the method signature.
Creates a ModelView Object with attributes that need to be transferred are added into Hashmap ,also the view is specified.  

Our transfer Object UserDetails (self explanatory)


package com.springapp.web;

 

/**
* TO class representing the User Details
* @author user
*
*/
public class UserDetails {  

String firstName;
String secondName;
String country;  

/**
* Constructor
* @param firstName
* @param secondName
* @param country
*/
public UserDetails(String firstName, String secondName, String country) {
this.firstName = firstName;
this.secondName = secondName;
this.country = country;
}  

/**
* Getter
* @return
*/
public String getFirstName() {
return firstName;
}  

/**
* Setter
* @param firstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}  

/**
* Getter
* @return
*/
public String getSecondName() {
return secondName;
}  

/**
* Setter
* @param secondName
*/
public void setSecondName(String secondName) {
this.secondName = secondName;
}  

/**
* Getter
* @return
*/
public String getCountry() {
return country;
}  

/**
* Setter
* @param country
*/
public void setCountry(String country) {
this.country = country;
}  

}  

DAO class :


package com.springapp.web;

 

import java.util.HashMap;
import java.util.Map;  

/**
* DAO class for user details
* @author user
*
*/
public class UserDetailsDao {  

private static Map userDetailSource = new HashMap();  

static{
userDetailSource.put("Arun", new UserDetails("Arun","A2","India"));
userDetailSource.put("David", new UserDetails("David","B2","US"));
userDetailSource.put("Jon", new UserDetails("Jon","C2","UK"));
userDetailSource.put("Sam", new UserDetails("Sam","D2","US"));
userDetailSource.put("Anu", new UserDetails("Anu","E2","India"));
userDetailSource.put("Manu", new UserDetails("Manu","F2","India"));
}  

/**
* Return the UserDetail object for the input name
* @param name
* @return
*/
public UserDetails getUserDetail(String name){
UserDetails userDetails = userDetailSource.get(name);
return userDetails;
}  

}  

View : userDetail.jsp
userDetailsJSP
NB : Adding as PDF as wordpress is not allowing tags of JSP/XML  

Web.xml :
Simple plain old xml for servlets ,the Servlet used by the framework is DispatcherServlet
Web-XML  

The webApplication context is refered in springapp-servlet.xml .As this a smple application the only relevant thing here is the package in which framework has to search for the Controllers.
springapp-servletXML  

Building and running the application  

The application was run and tested in Jboss jboss-5.0.1.GA-jdk6 version is used and to build the war file used ANT inbuilt with eclipse 3.4  

Jars Needed :  
buildXML
Spring Framework related jar Files (Can be downloaded from Spring 3.0 release)  

org.springframework.aop-3.0.0.RELEASE.jar
org.springframework.asm-3.0.0.RELEASE.jar
org.springframework.beans-3.0.0.RELEASE.jar
org.springframework.context-3.0.0.RELEASE.jar
org.springframework.context.support-3.0.0.RELEASE.jar
org.springframework.core-3.0.0.RELEASE.jar
org.springframework.expression-3.0.0.RELEASE.jar
org.springframework.web-3.0.0.RELEASE.jar
org.springframework.web.portlet-3.0.0.RELEASE.jar
org.springframework.web.servlet-3.0.0.RELEASE.jar  

This should be included in the WAR  

servlet-api.jar is needed for compilation and would be available in web/application server lib directory  

The build structure is  

  

Testing the Application:  

Access the application in a web browser using  

http://contextroot/enquiryPage.do  

Eg :  

http://localhost:8080/springapp/enquiryPage.do  

Happy Developing :-)  

Linking two projects in Eclipse

January 21, 2010 at 6:24 PM | Posted in ECLIPSE | Leave a comment
Tags: , , , , ,

Today I needed to link two projects in Eclipse ,basically Java classes of my  one project was refering to  another project. For debugging  I wanted to link the source. As always  i just googled but suprised not  to find this easy thing. I got it working soon and just wanted to share it.

Well  first I tried to attach the source with the jar  I was using  in the second project but there was a limitation, I could not inspect the local variables but just the instance variables.With linking the project inspecting is not a problem.

Let us start now !

Create the two projects :

I am just creating two projects P1 and P2

View of Project Explorer

I want to  refer Class A in P1 from Class B  P2. So to link P1 with P2 ,

Right Click P2 >> Properties >> Java Build Path >> Click tab Projects

Click Add.The Open projects would be shown in the list and we can choose the needed from there

Click Ok Done

Easy :-) .

Hello world!

November 17, 2009 at 5:07 PM | Posted in Uncategorized | Leave a comment

To the world of blogs with a Helloo :-)

Blog at WordPress.com. | The Pool Theme.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.