Tuesday, August 16, 2011

DAO layer - Generics to the rescue

Generics can be a powerful tool to create reusable code with the power of compile time verification (type safety..).
Unfortunately I feel the main stream developers still afraid of it.
However, in analogy to Hagrid's spiders I would say that Generics are seriously misunderstood creatures... :-)

I hope the following example will demonstrate how useful they can be.

The Problem - DAO (Data Access Objects) classes have common methods such as save, update, delete, loadAll.. which are required in every DAO class.
Writing a base class with these common methods and making every DAO object extend it, is simply not enough since each DAO class represents a different domain class and therefore the type used in the common methods' signature is different (although implementation is similar), for example:
class OrderDAO {
//save method receive an Order
public void save(Order order){....}
//getAll method return Orders List
public List<Order> getAll(){...} 
}

class UserDAO{
//save method receive an User
public void save(User user){....}
//getAll method return Users List
public List<User> getAll(){...}
}


How Generics can help us create a base class with a common implementation and yet, keep method signature type-safety?
First, we need to define an interface with the common methods:
/**
 * Base interface for CRUD operations and common queries
 */
public interface IDaoBase<T> {
	
	public List<T> loadAll();
	
	public void save(T domain);
		
	public void update(T domain);
		
	public void delete(T domain);
	
	public T get(Serializable id);
	
	/**
	 * Get list by criteria
	 * @param detachedCriteria the domain query criteria, include condition and the orders.
	 * @return
	 * 
	 */
	public List<T> getListByCriteria(DetachedCriteria detachedCriteria);
	
	public List<T> getListByCriteria(DetachedCriteria detachedCriteria, int offset, int size);	
}

Please note that we utilize generics so each method signature has a type T, which in the implemented DAO classes, will be a concrete type, per domain.

The second step is to create an abstract class which implements the common functionality:

public abstract class DaoBase<T> extends HibernateDaoSupport implements IDaoBase<T> {
	private Class<T> entityClass;
	
	@Autowired
	public void setSession(SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
		
	public DaoBase() {
		
		entityClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

        public List<T> loadAll(){
		return getHibernateTemplate().loadAll(entityClass);
	}

	public void delete(T domain) {
		getHibernateTemplate().delete(domain);
	}

	public void save(T domain) {
		getHibernateTemplate().saveOrUpdate(domain);
		
	}

	public void update(T domain) {
		getHibernateTemplate().merge(domain);
	}
	
	
        public T get(Serializable id) {
		T o = (T) getHibernateTemplate().get(entityClass, id);
		return o;
	}

	public List<T> getListByCriteria(DetachedCriteria detachedCriteria,
			int offset, int size) {
		return getHibernateTemplate().findByCriteria(detachedCriteria, offset, size);
	}
	
	public List<T> getListByCriteria(DetachedCriteria detachedCriteria) {
		return getHibernateTemplate().findByCriteria(detachedCriteria);
	}
}

And that's it !
Take a minute or two to inspect how the base object implements a generic functionality with a type-safety manner.

All we have to do when implementing a new DAO is:
1. Interface to extend the IDaoBase with a concrete type
public interface DaoUser extends IDaoBase<User> {//<=Notice the User typing
	//Add any additional custom methods..
	public User getbyUsername(String username);
        public User getbyEmail(String email);
}

2. Implementation to extend the DaoBase with a concrete type

//This class has all the common methods, which are type safe for the User class
@Repository("daoUser")
public class DaoUserImpl extends DaoBase<User> implements DaoUser { //<=Notice the User typing

	public User getbyUsername(String username) {
// concrete implmentation		...
	}

So now you see how powerful it is to use generics. Hope it is now a bit less scary and more understood...

Please post me if you have further cool tricks utilizing generics for ease development.

Moreover, if you think any of the above can be improved, I'll be happy to hear about it.

Sunday, August 7, 2011

Spring security 3 Ajax login - accessing protected resources

I have seen some blogs about Spring Security 3 Ajax login, however I could not find any that tackles how to invoke Ajax based login, where a protected resource is being accessed in Ajax by an anonymous user.

The problem - The web application enables anonymous access to certain parts and certain parts are protected resources which require the user to login.
When an anonymous user accesses protected resources (via Http Get / Post), Spring Security automatically invokes the login page and after a successful authentication, redirects to the required resource/page.
However, if the protected resource is being accessed in Ajax, the login page will not appear correctly (will be set on part of the page). The 302 code (redirect to login page) will not function as expected in Ajax.
Please note that this is NOT the same as initiating an Ajax login screen (e.g. when user press on the login button and a popup with user/password fields is being invoked).
So - how can we have Spring Security 3 handle access to protected resources both with "regular" HTTP Post(FORM based authentication) AND Ajax calls, including a redirect to the required resource after successful authentication?

So, this blog post has two protection layers/parts:
1. Spring Security 3 standard FORM based authentication
2. Configure/extends Spring Security 3 and the app to support also Ajax access to protected resources.

Regarding part 1 - there are many references about the issue. No need to elaborate.
Regarding part 2 - Requires the following:
   1. Configure Spring Security 3 to enable Ajax based login.
   2. Configure client Ajax calls to protected resources to handle request for authentication.
   3. Re-execution of functions to simulate the automatic user original method invocation after successful login (as it happens in the FORM based login)

The below diagram describes a detailed flow and should help follow the client/sever communication.

Handling protected resource access via Ajax





Lets discuss the diagram:

The flow starts with an anonymous user Ajax request to a protected resource (1). In this case the user wants to add an item to the shopping cart.

The addItem method is a protected resource, which is protected via Spring Security (@pre_authorize("SOME_ROLE")) (2).  This causes the Spring Secutiry filter (3) to send the login FORM with HTTP code 302 (i.e. redirect to that page).

Now, since this is an Ajax call, it will not handle the request well, so here comes the part that takes the login FORM, put it aside, and invoke Ajax based login instead (4):

The client Ajax method (which invoked the Ajax addItem method) checks whether it is a form based login or any other reply. If it is a FORM based login, it will call a dialog modal (5) that will try to login in Ajax. Spring will handle the Ajax login authentication (6) and return an appropriate message to the client. The client, if the message was successful, will re-execute the original function, which tried to access the protected resource (e.g. addItem in our example).

Let us see how it all fits in our code:
Steps #1, #4 - Client side which accesses protected resources and checks if a login is required
//JavaScript method - Ajax call to protected resource (#1 in flow diagram)
function addItem(itemId) {    
    $.ajax({
        url: '/my_url/order/addItem',
        type: 'POST',
        data: ({orderItemId : itemId,...}),               
        success: function(data) {

           //construct a callback string if user is not logged in.
           var cllbck = 'addItem('+itemId +')';

           //Client check if login required
           //(#4 in flow diagram)
           if (verifyAuthentication(data,cllbck)){
               // in here => access to protected resource was ok
               // show message to user, "item has been added..."
           }
      });
    }

Steps #2, #3 - is a regular Spring Security configuration. Plenty of resources out there.
Step #4 - Client checks if login is required:
function verifyAuthentication(data, cllBackString){
   //naive check - I put a string in the login form, so I check for existance
   if (isNaN(data) && (data.indexOf("login_hidden_for_ajax")!= -1)){
      //if got here then data is a loginform => login required
      
      //set callback in ajax login form hidden input		
      $("#my_callback").val(cllBackString);	
 
      //show ajax login
      //Get the window height and width
      var winH = $(window).height();
      var winW = $(window).width();
              
      //Set the popup window to center
      $("#ajaxLogin").css('top',  winH/2-$("#ajaxLogin").height()/2);
      $("#ajaxLogin").css('left', winW/2-$("#ajaxLogin").width()/2);
      $("#ajaxLogin").fadeIn(2000); 
      return false;
      }	
    // data is not a login form => return true to continue with function processing
    return true;	
}
Step #5, #7 - the Ajax login FORM utilizes the following Ajax login:

function ajaxLogin(form, suffix){
	
	var my_callback = form.my_callback.value; // The original function which accessed the protected resource
	var user_pass = form.j_ajax_password.value;
	var user_name = form.j_ajax_username.value; 

//Ajax login - we send credentials to j_spring_security_check (as in form based login
	$.ajax({
          url: "/myContextURL/j_spring_security_check",    
          data: { j_username: user_name , j_password: user_pass }, 
          type: "POST",
          beforeSend: function (xhr) {
             xhr.setRequestHeader("X-Ajax-call", "true");
          },
          success: function(result) {    	
          //if login is success, hide the login modal and
          //re-execute the function which called the protected resource
          //(#7 in the diagram flow)
    	  if (result == "ok") {
 
            $("#ajax_login_error_"+ suffix).html("");            
    	    $('#ajaxLogin').hide();
    	    if (my_callback!=null && my_callback!='undefined' && my_callback!=''){
    		eval(my_callback.replace(/_/g,'"'));
    	    }
    	    
            return true;
          }else {       	
        	
        	$("#ajax_login_error_"+ suffix).html('<span  class="alert display_b clear_b centeralign">Bad user/password</span>') ;
        	return false;        	
        }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
    	$("#ajax_login_error_"+ suffix).html("Bad user/password") ;
    	return false; 
    }
});
}

We need to set Spring to support Ajax login (#6):
Set Spring Security xml configuration:


   
    
        
        
		
		
        	
        
                    
        

    
	
	...

Define a handler for login success:
@Component("ajaxAuthenticationSuccessHandler")
public class AjaxAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {	
	   
    public AjaxAuthenticationSuccessHandler() {    
    }

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {	
		
		HttpSession session = request.getSession();		
		DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) session.getAttribute(WebAttributes.SAVED_REQUEST);
		//check if login is originated from ajax call
		if ("true".equals(request.getHeader("X-Ajax-call"))) {
	        try {
	        	response.getWriter().print("ok");//return "ok" string
	        	response.getWriter().flush();
		} catch (IOException e) {				
		   //handle exception...
		}
	    } else {	    	
	    	setAlwaysUseDefaultTargetUrl(false);		
		...
	    }
	}
}
Define a handler for login failure - the same as success, but the string is "not-ok".

I know some of the code here is not the best practice so I would like to hear what you think.
Please post me if you can see a way to improve the process or make it more generic.

Acknowledgment -
Diagram was done via gliffy - online diagram tool

Thursday, August 4, 2011

Development stack

On the previous post I wrote a bit about commonly used web development tools.


I now want to focus about my favorite development stack for Java web applications development -

Application server : Tomcat - currently using version 6, but will upgrade to 7 soon. Works great both in Win and Ubuntu. Easy to setup and scalable.
Application framework : Spring - highly stable, robust and now with version 3+ more simple.
Still using different Spring modules can make one fall into maven hell, but I believe it will get better and that the pros are much higher then the cons.
DB : MySQL   / Neo4J - I recently started to think about integration between Graph DB and Relational DB. Recent trends makes us transforming the conventions we know and use. For me - I start thinking that maybe a Graph DB is the "standard" / "natural" choice and relational DB should be chosen per case and for good reason. See Neo4J presentations about how the world should be modeled via the eye of graphs (Try to look for "Thinking in Graphs" article).
ORM : Hibernate/ Spring data-  spring data graph now provides more conservative use and aligned with the current JPA conventions.
UI framework : JQuery + JQuery UI - I also prefer to use plugin/extensions that are theme roller ready.

Monday, August 1, 2011

Toolkit for web development

Following the interesting startup survey infographic about The Web & Business Tools Startups Use Most, I would like to state my toolkit when it comes to web development.

Mocking and wireframe:
Balsamiq - not doubt about this one. I have tried several mocking tools including one which plugs into FF, however Balsamiq is the most simple, extensible, configurable tool for wireframe. Great for agile development since it makes you focus on functionality.
Gliffy - Online diagram tool that support UML. Very easy to start with, very clean and clear outcome.

Project documents sharing: DropBox - enable you to seemlessly share documents cross computers and cross team members.

Page design:  crocodoc - Great tool to provide feedback ( inputs... :) - internal joke... ) for designer. You can post feedbacks in certain places on the design page (like sticky notes - but better) and have offline review. Really cool.

Assembla - Manage your code repository (I use SVN) and support development activities such as planning tasks (tickets), daily meetings, wiki, code diff and much more. Installing and Configuring SVN always seemed to be an exhausting task which even was a highly important development infrastructure tool, does not bring added value to the customer and not the core of application development, therefore an ideal candidate to outsource.

IDE: Eclipse / STS - In not so far past, STS was very slow, but now it is much faster and all the bundled apps make it an easy choice for Java development.
IDE plugins:
ResourceBundle Editor: Useful to track and edit multiple i18n files in Java. (extract it and drag the folder into the eclipse/plugins folder)

Gimp - I don't want to encourage developers to handle UI design themselves (so this would be under the section of productivity killer..)

Testing - BadBoy UI recording tool, most intuitive recording and testing tool I know. Provide also an advanced mode, if required, for testing and verification.

Web pages usability - crazyEgg - demonstrate and visualize where in the page users click.
A very good tool to identify design pitfalls. Helped me see what users think and actually identify that users tried to click on a section which wasn't clickable.

Development OS : Windows
Deployment OS: Ubuntu Server
I found it very useful to use windows to boost development productivity and then deploy it on the Ubuntu server, via remote access. This portability forces me to write better code.

Remote access:
Remote command line control: SSH
Transfer files to server: FileZila

General productivity tools:
Firefox - For me, still the ideal browser for development.
Firebug - The ultimate FF plugin and the reason I don't use Chrome (I know Chrome has alternative, but still..) . No additional word is needed.
ReloadEvery - FF plugin that enable reload of pages automatically. Useful for load test or profiling.
JSONView - FF plugin to view json in clear way.
Cookie manager - Manage cookies (edit, clear, view..)
RoboForm - password management tool, also came in the flavor as a FF plugin. Enable you to have (different) strong password for each site. If you are still using your single "strong" password cross sites, then give it a try, you will be able to sleep better. I have the paid version. Worth every cent.
Notepad++ - Great for adhock file editing.
jsfiddle - Test small scripts / css online
skitch - similar to snagit.
I'll keep updating this list if I will come across further interesting tools.