Learning Google Guice

Learning Google Guice

Learning Google Guice 3.0 is instant, hands on book to cover various areas of dependency injection using the features provided by latest version of Guice. It focuses on core functionality as well as covers various extensions surrounding Guice making it useful in other areas like web development, integration with frameworks for web development and persistence.

Learning_Google_Guice_Cover_pageLearning_Google_Guice_Back_page

Table Of Contents

  • Preface

  • Chapter 1: Getting Started with Guice

    • Wiring dependencies

      • Resolving dependencies directly

      • Inverting the dependencies

      • Understanding Inversion of Control

      • Inverting the control using the Dependency injection

    • Comparing two approaches

      • Initializing dependencies directly

      • Refactoring to use Guice

    • Building and Running the examples

      • Compiling the sample code

      • Running Unit tests

      • Running the main application

    • Summary

  • Chapter 2: Exploring Google Guice

    • Meet the injector

      • Various kinds of injections

        • Field injection
        • Method injection
        • Constructor injection

    • Configuring a module to write bindings

      • Bindings

        • Linked bindings
        • Instance bindings
        • Untargeted bindings
        • Constructor bindings
      • Binding annotations

      • Binding constants

      • Binding properties

      • Just in time bindings

        • By default constructors

        • @Inject annotated constructors

        • Interfaces annotated with @ImplementedBy

    • Static injection

    • Summary

  • Chapter 3: Diving Deeper in Guice

    • Going the extra mile with Providers

      • Need for a Provider

        • Working of a Provider
      • Rolling your own Provider

        • Injecting dependencies in Providers
        • Advantages of a Provider
        • @Provides
      • CheckedProviders

        • @CheckedProvides
    • AssistedInject

    • Binding collections

      • Using TypeLiteral

      • Using MultiBinder

    • Scoping

      • Singletons with Guice

      • Eager Singletons

      • Custom Scopes

        • Motivation to write a custom scope
        • Modifying our Provider
        • Defining our own scope
        • Changes in Module
        • Observations
    • Summary

  • Chapter 4: Guice in Web Development

    • Structure of flightsweb application

    • Using GuiceFilter

    • Rolling out our ServletContextListener interface

    • ServletModule – the entry point for configurations

    • Binding language

      • Mapping servlets

      • Mapping filters

    • Web scopes

      • @RequestScoped

      • @SessionScoped

      • @RequestParameters

      • Exercising caution while scoping

    • Summary

  • Chapter 5: Integrating Guice with Struts 2

    • Introducing Struts 2

      • Guice 3 and Struts 2 integration

        • Struts2GuicePluginModule
        • Struts2Factory
      • FlightSearch application with Struts 2

        • FlightServletContexListener
        • Index page
        • FlightSearchAction
        • Response page
    • Summary

  • Chapter 6: Integrating Guice with JPA 2

    • Introduction to JPA 2 and Hibernate 3

      • Persistence Unit

      • PersistenceContext

      • EntityManagerFactory

      • EntityManager

      • Session Strategies

    • Guice 3 with JPA 2

      • PersistService

      • UnitOfWork

      • JpaPersistService

      • PersistFilter

      • @Transactional

      • JpaLocalTxnInterceptor

      • JpaPersistModule

    • FlightSearch application with JPA 2 and Hibernate 3

      • Persistence.xml

      • Client

      • SearchResponse

      • FlightEngineModule

      • FlightJPASupplier

      • FlightServletContextListener

    • Summary

  • Chapter 7: Developing Plugins and Extensions using Guice

    • Developing a plugin

    • Guice SPI (Service Provider Interface)

      • Quick introduction to Visitor Design pattern

      • Elements SPI

        • Implementing Elements SPI
        • Uses of Elements SPI
      • Extensions SPI

    • Exploring a custom extension, guice-multibinder

      • Important classes and interfaces in guice-multibinder

      • Multibinder in action

    • Summary

  • Chapter 8: AOP with Guice

    • What is AOP?

    • How AOP works?

    • How Guice supports AOP?

      • Implementing a LoggingInterceptor

      • Understanding Matchers

      • Limitations

    • Concerns related to performance

    • Summary

  • Appendix: Prerequisites

    • Getting the sample code

      • Installing Git

      • Cloning the repository

    • JDK

    • Installing Maven

      • Mac OSX and Linux

      • Microsoft Windows

    • Installing Eclipse

    • Installing the m2eclipse plugin

    • Installing Apache Tomcat

    • Installing MySQL

      • Microsoft Windows

      • Mac OSX

      • Linux

    • Importing MySQL data

  • Index

Topic

Wiring dependencies in java application has been formally a topic of debate among developers and architects. Prior to the advent of DI frameworks, this has been accomplished mostly using hard coded dependencies, vanilla injection using constructors or setter APIs or using abstract factory/factory design pattern. Lack of a standard to achieve the same has often caused problems to properly design the APIs, separating logical concerns from infrastructure part.

Key Features

  1. Learn how to avoid vanilla dependency injection using Guice as a solution.
  2. Set up the stage for a fictitious application development, which would start as a small SA application and conclude as a Struts 2, JPA 2, Hibernate 3 powered web application, all harnessing features of Guice 3.
  3. Learn intricacies of Binding, Scoping and Injection. Master various aspects of Guice pertaining to different areas of application development in Java.
  4. Learn to harness guice-servlet extension for web development using JSP and Servlets.
  5. Learn to harness guice-struts2 extension for web development using Struts 2.
  6. Learn to harness guice-persist extension to develop an application using JPA 2, Hibernate 3.
  7. Leverage AOP using Guice implementation of aopalliance.
  8. Learn how to develop extensions using Guice SPI, Service Provider interface.

Broad Sweep

This book looks forward to dependency injection as an implementation from Guice. Often developers are confused with myriads of possibilities offered by Guice. This book offers insight to applying proper solution to a problem’s context. Various Guice extensions are discussed which avoid complex API usage and keep the spirit of convention over configuration high.

Plot

You will start from developing a trivial application by managing dependencies using Guice 3. As book gradually progresses, we go on adding the complexity to the application and simultaneously learning Guice 3.0 features. Various features of Guice like Injector, Provider, Bindings and Scopes are discussed in detail with recipes for each. Later we retrofit the application for web bringing Guice to not only manage dependencies but also to solve configuration related problems. Web application development using JSP and Servlets is covered which progresses ahead using Struts 2 with Guice 3. The application later harnesses Guice 3 to manage dependencies while powering the application with JPA 2 and Hibernate 3. At last we discuss AOP using Guice and extend Guice itself using SPI, Service Provider Interface.

Who this book is for

This book is for anyone having a minimal understanding of application development in Java and keen to learn dependency injection using Guice. Architects and Lead programmers, who are into designing structure of the application would benefit from various recipes to be leveraged during developing infrastructure pieces. Readers are assumed to have a basic knowledge of dependency injection, however this is not an obligation.

Conclusion

Learning Google Guice 3.0 would help you to harness the various features of Guice and its extensions in different areas of application development in Java.

Building MongoDb client for C++ on MacOS and Boost Problems

Recently, while building mongodb client for C++ (libmongoclient.a). I faced a boost library dependency issue. MongoDb client depends on these boost libraries

  • detail        
  • filesystem      
  • program_options
  • system        
  • thread 

Particularly if you compile a dynamic library without using a –use-system-boost option, you will face linker issues later such as

Undefined symbols for architecture x86_64:
"boost::thread::start_thread()", referenced from:
boost::thread::thread<boost::_bi::bind_t<void, boost::_mfi::mf1<void, mongo::BackgroundJob, boost::shared_ptr<mongo::BackgroundJob::JobStatus> >, boost::_bi::list2<boost::_bi::value<mongo::BackgroundJob*>, boost::_bi::value<boost::shared_ptr<mongo::BackgroundJob::JobStatus> > > > >(boost::_bi::bind_t<void, boost::_mfi::mf1<void, mongo::BackgroundJob, boost::shared_ptr<mongo::BackgroundJob::JobStatus> >, boost::_bi::list2<boost::_bi::value<mongo::BackgroundJob*>, boost::_bi::value<boost::shared_ptr<mongo::BackgroundJob::JobStatus> > > >, boost::disable_if<boost::is_convertible<boost::_bi::bind_t<void, boost::_mfi::mf1<void, mongo::BackgroundJob, boost::shared_ptr<mongo::BackgroundJob::JobStatus> >, boost::_bi::list2<boost::_bi::value<mongo::BackgroundJob*>, boost::_bi::value<boost::shared_ptr<mongo::BackgroundJob::JobStatus> > > >&, boost::detail::thread_move_t<boost::_bi::bind_t<void, boost::_mfi::mf1<void, mongo::BackgroundJob, boost::shared_ptr<mongo::BackgroundJob::JobStatus> >, boost::_bi::list2<boost::_bi::value<mongo::BackgroundJob*>, boost::_bi::value<boost::shared_ptr<mongo::BackgroundJob::JobStatus> > > > > >, boost::thread::dummy*>::type) in libmongoclient.a(background.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Even if you try to compile a dynamic library with  –use-system-boost option, during compilation you could run into compatibility issues between boost version required by client library and boost version installed in your system. Something like this

/usr/local/include/boost/filesystem/config.hpp:16:5: error: #error Compiling Filesystem version 3 file with BOOST_FILESYSTEM_VERSION defined != 3

A simpler approach would be to prepare a static library with following option, assuming we are in the source path.

/Users/hussainp/MongoDB_cpp/mongo> scons --static mongoclient install

This will simply build and install the static library libmongoclient.a in /usr/local/lib

Hope it helps to save time and effort.

How to reverse a doubly linked list in C++ with half number of iterations of its size

This post briefly describes a performant way to reverse a doubly linked list in C++. The key differentiator is number of iterations required which are simply half of the size of list. Also no new list is instantiated.

The modus operandi is simple. Starting with the head we view each node as having a reflection from the tail end. In case of even sized lists we would have all the nodes from 0 to listSize/2 to have reflections but in case of odd sized lists we would have one node left, which we would term as the median. We just need to swap the nodes on one side of the median with their corresponding reflections on the other side. Median need not be swapped and remains as pivotal node.

Way:

  1. Start with two iterators one as the headCursor and the other as the tailCursor. Initially they are pointing at head and tail respectively.
  2. Loop over to half of the listSize.
  3. Just swap the currentNode which is headCursor->next with the reflectionNode which is tailCursor->prev. Make sure we reassign all the next and prev links properly.
  4. For even sized lists , while you reach position when current index of iteration is equal to listSize/2 – 1, insert a dummy node , prior to swapping of the nodes. This is done just to avoid problems related to reassignment of nodes. Once swapping is done the dummy node is removed and later on deleted.

Here is the complete code for the Doubly linked list template

/*
 * DoublyLinkedList.h
 *
 *  Created on: Jan 16, 2013
 *      Author: hussainp
 */

#ifndef DOUBLYLINKEDLIST_H_
#define DOUBLYLINKEDLIST_H_

#include
#include
using namespace std;

template
class DLinkedList;

template
class DNode {
private:
	E elem;
	DNode* prev;
	DNode* next;
	friend class DLinkedList ;
};

template
class DLinkedList {
public:
	DLinkedList();
	~DLinkedList();
	bool empty() const;
	const E& front() const;
	const E& end() const;
	void addFront(const E&);
	void addEnd(const E&);
	void removeFront();
	void removeEnd();
	void print();
	int size();
	void reverse();
	DNode* nodeAtPos(int);
private:
	DNode* head; // head and tail are merely sentinels
	DNode* tail; // they shouldn't be used to hold data
protected:
	void add(DNode*, const E&);
	void remove(DNode*);
};

template DLinkedList::DLinkedList() :
		head(NULL), tail(NULL) {
	head = new DNode();
	tail = new DNode();

	head->next = tail;
	tail->prev = head;
}

template DLinkedList::~DLinkedList() {
	while (!empty()) {
		removeFront();
	}
	delete head;
	delete tail;
}

template bool DLinkedList::empty() const {
	return (head->next == tail && tail->prev == head);
}

template const E& DLinkedList::front() const {
	return head->next->elem;
}

template const E& DLinkedList::end() const {
	return tail->prev->elem;
}

template void DLinkedList::add(DNode* posNode,
		const E& elem) {
	DNode* newNode = new DNode();
	newNode->elem = elem;

	newNode->next = posNode;
	newNode->prev = posNode->prev;
	posNode->prev->next = posNode->prev = newNode; // assign new node in between

}

template void DLinkedList::remove(DNode* posNode) {
	posNode->prev->next = posNode->next;
	posNode->next->prev = posNode->prev;
	delete posNode;
}

template void DLinkedList::addFront(const E& e) {
	add(head->next, e);
}

template void DLinkedList::addEnd(const E& e) {
	add(tail->prev, e);
}

template void DLinkedList::removeFront() {
	remove(head->next);
}

template void DLinkedList::removeEnd() {
	remove(tail->prev);
}

template void DLinkedList::print() {
	DNode* iterator = head->next;
	cout << endl;
	while (iterator != tail) {
		cout << iterator->elem << "\t"; 		iterator = iterator->next;
	}
	cout << endl;
}
/**
 * Traverses half of the list and swaps a node with another node(here by termed as the reflection node)
 * which lies at a position = listSize - (i +1) for every i.
 * Reassignment of element is not needed, hence a soul saver from
 * the copy constructor thing ( '=' assignment operator stuff).
 */
template void DLinkedList::reverse() {
	int median = 0;
	int listSize = size();
	int counter = 0;

	if (listSize == 1)
		return;

	DNode* tempNode = new DNode();

	/**
	 * A temporary node for swapping a node and its reflection node
	 */
	DNode* dummyNode = new DNode();

	DNode* headCursor = head;
	DNode* tailCursor = tail;

	for (int i = 0; i < listSize / 2; i++) { 		headCursor = headCursor->next;
		tailCursor = tailCursor->prev;

		DNode* curNode = headCursor;
		DNode* reflectionNode = tailCursor;

		if (listSize % 2 == 0 && listSize / 2 - 1 == i) {
			/**
			 * insert a dummy node for reflection
			 * for even sized lists at median position
			 */
			curNode->next = dummyNode;
			dummyNode->prev = curNode;

			reflectionNode->prev = dummyNode;
			dummyNode->next = reflectionNode;

		}
		/**
		 * swap the connections from previous and next nodes for current and reflection nodes
		 */

		curNode->prev->next = curNode->next->prev = reflectionNode;

		reflectionNode->prev->next = reflectionNode->next->prev = curNode;

		/**
		 * swapping of the nodes
		 */

		tempNode->prev = curNode->prev;
		tempNode->next = curNode->next;

		curNode->next = reflectionNode->next;
		curNode->prev = reflectionNode->prev;

		reflectionNode->prev = tempNode->prev;
		reflectionNode->next = tempNode->next;

		if (listSize % 2 == 0 && listSize / 2 - 1 == i) {
			/**
			 * remove the dummy node for reflection
			 * for even sized lists from the median
			 */
			reflectionNode->next = curNode;
			curNode->prev = reflectionNode;
		}

		/**
		 * Reassign the cursors to position over the recently swapped nodes
		 */
		tailCursor = curNode;
		headCursor = reflectionNode;
	}

	delete tempNode, dummyNode;
}

template int DLinkedList::size() {
	int count = 0;
	DNode* iterator = head;

	while (iterator->next != tail) {
		count++;
		iterator = iterator->next;
	}
	return count;
}

template DNode* DLinkedList::nodeAtPos(int pos) {
	DNode* iterator = head->next;
	int listSize = size();
	int counter = 0;
	while (counter < pos) { 		iterator = iterator->next;
		counter++;
	}

	return iterator;
}
#endif /* DOUBLYLINKEDLIST_H_ */

Extending Spring Security

Spring’s security framework has proven out to be a great tool aiding in development of secure web applications. The modular architecture, open sourced and loads of reference materials have proven out to be of great help.

While there are lots of articles, tutorials and books are available for spring security, very few describe how to extend this powerful framework beyond the already provided solutions. In this article, I tend to describe a model which is based on simple Username & Password authentication model and is RBAC driven using database. What is different in it is inclusion of an extra parameter of Domain, which is basically a segregator for various users.

First, let’s have a look at the database model

Image

The schema is itself quite simple. The only addition to it is an extra domain table which serves to segregate the users for a particular domain.

For extending the spring security and introducing an extra attribute of domain, we would harness the following classes.

Image

Here DomainAuthenticationToken is our customized class which subclasses UsernamePasswordAuthenticationToken. This is required, because instead of providing all the required implementations for the Authentication(interface) and subsequent AbstractAuthenticationToken(abstract class) we would be able to provide only additionally required implementations.

The source code for DomainAuthenticationToken is as follows.

package org.springframework.security.authentication;

import java.util.Collection;
/**
 * 
 * @author hussain.pithawala
 * 
 */
public class DomainAuthenticationToken extends UsernamePasswordAuthenticationToken{
	
	/**
	 * default serial version uid
	 */
	private static final long serialVersionUID = 1L;

	
	private String domainName = null;
	
	public String getDomainName() {
		return domainName;
	}

	public void setDomainName(String domainName) {
		this.domainName = domainName;
	}

	public DomainAuthenticationToken(Object principal,Object credentials,Collection<GrantedAuthority> authorities){
		super(principal,credentials,authorities);
	}
	
	public DomainAuthenticationToken(String username,String password,String domain){		
		super(username,password);
		this.setDomainName(domain);
	}

	
}

Now, what is the actual use of a customized authentication implementation. The authentication serves as the holder of the principal (logged in user) and his credentials (authorities). This is the most generic information required by the spring security to function. A detailed implementation however covers many other aspects like a UsernamePasswordAuthenticationtoken provides attributes to hold username and password. An OopenidAuthenticationToken contains attributes to hold extra data. In our case DomainAuthenticationToken holds extra attribute of the domain.

Next, we need to provide an implementation of the UserDetails interface.

Image

The implementation of the UserDetails is never used directly by the spring security. Instead it is used by the AuthenticaitonProvider implementation to harness the details regarding the User from a service. Be it an RBAC service, LDAP service or any other service. In our case we again extend from the provided implementation of User and provide an extra attribute of domain. The source code is as follows.

package org.springframework.security.core.userdetails;

import java.util.Collection;
/**
 * 
 * @author hussain.pithawala
 *
 */
@SuppressWarnings("serial")
public class DomainUser extends User {
	private final String domain;
	
	public String getDomain() {
		return domain;
	}

	public DomainUser(String username,String domain,String password, boolean enabled,
			boolean accountNonExpired, boolean credentialsNonExpired,
			boolean accountNonLocked,
			Collection<? extends GrantedAuthority> authorities) {
		super(username, password, enabled, accountNonExpired, credentialsNonExpired,
				accountNonLocked, authorities);
		this.domain = domain;
	}

}

Next, we need to provide an implementation of the UserDetailsService. This is basically a service which prepares the UserDetails object and caters to an AuthenticationProvider. Please note , for the sake of brevity I have not provided the detailed model of Spring Security provided classes. Rather I’ve focused on the implementations which are required to achieve this objective.

Image

The source code for the DomainUserDetailsManager .java is as follows.

package org.springframework.security.provisioning;

import java.sql.ResultSet;
/**
 * 
 * @author hussain.pithawala
 *
 * The purpose of this class is to extend the functionality
 * provided by the JdbcDaoImpl class. The extra features the class
 * provides is availability of the domain name selection for a 
 * particular user.
 */
public class DomainUserDetailsManager extends JdbcUserDetailsManager {
	/**
	 * Set the default value for
	 */
	public static final String USER_BY_USERNAME_DOMAIN = "select users.username,users.password,users.enabled,domain.domainname from users,domain where users.domainid = domain.domainid and users.username = ? and domain.domainname = ?";
	
	public static final String AUTHORITIES_BY_USERNAME_DOMAIN = "select u.username as username,p.permissionname as authorityname from users u,roles r,permissions p,userrole ur, rolepermission rp,domain d where u.username = ? and d.domainid = u.domainid and d.domainname = ? and ur.roleid = r.roleid and ur.userid = u.userid and r.roleid = rp.roleid and rp.permissionid = p.permissionid";
	
	private String authoritiesByUserNameDomainQuery = AUTHORITIES_BY_USERNAME_DOMAIN;
	
	public String getAuthoritiesByUserNameDomainQuery() {
		return authoritiesByUserNameDomainQuery;
	}

	public void setAuthoritiesByUserNameDomainQuery(
			String authoritiesByUserNameDomainQuery) {
		this.authoritiesByUserNameDomainQuery = authoritiesByUserNameDomainQuery;
	}

	private String userByUserNameDomainQuery = USER_BY_USERNAME_DOMAIN;
	
	public String getUserByUserNameDomainQuery() {
		return userByUserNameDomainQuery;
	}

	public void setUserByUserNameDomainQuery(String userByUserNameDomainQuery) {
		this.userByUserNameDomainQuery = userByUserNameDomainQuery;
	}
	
    public DomainUser loadDomainUserByUserNameDomain(String username,String domainname) throws UsernameNotFoundException, DataAccessException {
        List<DomainUser> users = loadDomainUsersByUserNameDomain(username,domainname);

        if (users.size() == 0) {
            throw new UsernameNotFoundException(
                    messages.getMessage("JdbcDaoImpl.notFound", new Object[]{username}, "Username {0} not found"), username);
        }

        DomainUser domainUser = users.get(0); // contains no GrantedAuthority[]

        Set<GrantedAuthority> dbAuthsSet = new HashSet<GrantedAuthority>();

        if (this.getEnableAuthorities()) {
            dbAuthsSet.addAll(loadDomainUserAuthorities(username, domainname));
        }

        if (this.getEnableGroups()) {
            dbAuthsSet.addAll(loadGroupAuthorities(domainUser.getUsername()));
        }

        List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(dbAuthsSet);

        addCustomAuthorities(domainUser.getUsername(), dbAuths);

        if (dbAuths.size() == 0) {
            throw new UsernameNotFoundException(
                    messages.getMessage("JdbcDaoImpl.noAuthority",
                            new Object[] {username}, "User {0} has no GrantedAuthority"), username);
        }

        return createDomainUserDetails(username, domainUser, dbAuths);
    }

	
    protected List<DomainUser> loadDomainUsersByUserNameDomain(String username,String domain) {
        return getJdbcTemplate().query(userByUserNameDomainQuery, new String[] {username,domain}, new RowMapper<DomainUser>() {
            public DomainUser mapRow(ResultSet rs, int rowNum) throws SQLException {
                String username = rs.getString(1);
                String password = rs.getString(2);
                boolean enabled = rs.getBoolean(3);
                String domain = rs.getString(4);
                return new DomainUser(username, domain, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES);
            }

        });
    }
    
    protected List<GrantedAuthority> loadDomainUserAuthorities(String username,String domain) {
        return getJdbcTemplate().query(authoritiesByUserNameDomainQuery, new String[] {username,domain}, new RowMapper<GrantedAuthority>() {
            public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
                String roleName = getRolePrefix() + rs.getString(2);
                GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);

                return authority;
            }
        });
    }
    
    protected DomainUser createDomainUserDetails(String username, DomainUser userFromUserQuery,
            List<GrantedAuthority> combinedAuthorities) {
        String returnUsername = userFromUserQuery.getUsername();

        if (!this.isUsernameBasedPrimaryKey()) {
            returnUsername = username;
        }

        return new DomainUser(returnUsername, userFromUserQuery.getDomain(),userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(),
                true, true, true, combinedAuthorities);
    }
}

Next, we need to have an implementation of the AuthenticationProvider.  We need an implementation of the AuthenticationProvider since call is delegated from AuthenticationManager to one of the registered AuthenticationProviders, which happen to process the Authentication.

Image

The source code for the DomainAuthenticationProvider.java is as follows.

package org.springframework.security.authentication.dao;

import org.springframework.dao.DataAccessException;

public class DomainAuthenticationProvider extends DaoAuthenticationProvider {
	@Override
    public Authentication authenticate(Authentication originalAuthentication) throws AuthenticationException {
        Assert.isInstanceOf(DomainAuthenticationToken.class, originalAuthentication,
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only DomainAuthenticationToken is supported"));
        
		DomainAuthenticationToken authentication = (DomainAuthenticationToken)originalAuthentication;

        // Determine username
        String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

        boolean cacheWasUsed = true;
        
        DomainUser domainUser = null;//this.getUserCache().getUserFromCache(username);

//        if (user == null) {
            cacheWasUsed = false;

            try {
                domainUser = retrieveDomainUser(username, authentication);
            } catch (UsernameNotFoundException notFound) {
                if (hideUserNotFoundExceptions) {
                    throw new BadCredentialsException(messages.getMessage(
                            "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                } else {
                    throw notFound;
                }
            }

            Assert.notNull(domainUser, "retrieveUser returned null - a violation of the interface contract");
//        }

        try {
        	this.getPreAuthenticationChecks().check(domainUser);
            additionalAuthenticationChecks(domainUser, (UsernamePasswordAuthenticationToken) authentication);
        } catch (AuthenticationException exception) {
            if (cacheWasUsed) {
                // There was a problem, so try again after checking
                // we're using latest data (i.e. not from the cache)
                cacheWasUsed = false;
                domainUser = retrieveDomainUser(username, authentication);
                this.getPreAuthenticationChecks().check(domainUser);
                additionalAuthenticationChecks(domainUser, (UsernamePasswordAuthenticationToken) authentication);
            } else {
                throw exception;
            }
        }
        this.getPostAuthenticationChecks().check(domainUser);

        if (!cacheWasUsed) {
        	this.getUserCache().putUserInCache(domainUser);
        }

        Object principalToReturn = domainUser;

        if (this.isForcePrincipalAsString()) {
            principalToReturn = domainUser.getUsername();
        }

        return createSuccessAuthentication2(principalToReturn, authentication, domainUser);
    }

    protected Authentication createSuccessAuthentication2(Object principal, Authentication authentication,
            DomainUser user) {
            // Ensure we return the original credentials the user supplied,
            // so subsequent attempts are successful even with encoded passwords.
            // Also ensure we return the original getDetails(), so that future
            // authentication events after cache expiry contain the details
    		DomainAuthenticationToken result = 
    				new DomainAuthenticationToken(principal,
    	                    authentication.getCredentials(), user.getAuthorities());
            result.setDetails(authentication.getDetails());
            result.setDomainName(user.getDomain());
            return result;
        }
	
    protected final DomainUser retrieveDomainUser(String username, DomainAuthenticationToken authentication)
            throws AuthenticationException {
    	Assert.isInstanceOf(DomainUserDetailsManager.class, this.getUserDetailsService());
    	
        DomainUser loadedDomainUser = null;

        try {
        	if(this.getUserDetailsService() instanceof DomainUserDetailsManager){
        		DomainUserDetailsManager domainUserDetailsManager = (DomainUserDetailsManager)this.getUserDetailsService();        		
        		loadedDomainUser = domainUserDetailsManager.loadDomainUserByUserNameDomain(username,authentication.getDomainName());
        	}
            
        }
        catch (DataAccessException repositoryProblem) {
            throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
        }

        if (loadedDomainUser == null) {
            throw new AuthenticationServiceException(
                    "UserDetailsService returned null, which is an interface contract violation");
        }
        return loadedDomainUser;
    }
}

Lastly we need to provide an implementation of the AbstractAuthenticationProcessingFilter. This filter would actually serve as the AuthenticationEntry point , akin to a DefaultLoginPageGeneratingFilter.Image

The source code for the DomainAuthenticationFilter.java is,

package org.springframework.security.web.authentication;

import javax.servlet.http.HttpServletRequest;

public class DomainAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
	
	public DomainAuthenticationFilter() {
		super();
	}

	public static final String SPRING_SECURITY_FORM_DOMAIN_KEY = "j_domain";

	private String domainParameter = SPRING_SECURITY_FORM_DOMAIN_KEY;
	
	private String alwaysUseDefaultTargetUrl;

	private String authenticationFailureUrl;
	
	private String defaultTargetUrl;
	
	private String loginPage;

	public String getAlwaysUseDefaultTargetUrl() {
		return alwaysUseDefaultTargetUrl;
	}

	public void setAlwaysUseDefaultTargetUrl(String alwaysUseDefaultTargetUrl) {
		this.alwaysUseDefaultTargetUrl = alwaysUseDefaultTargetUrl;
	}

	public String getAuthenticationFailureUrl() {
		return authenticationFailureUrl;
	}

	public void setAuthenticationFailureUrl(String authenticationFailureUrl) {
		this.authenticationFailureUrl = authenticationFailureUrl;
	}

	public String getDefaultTargetUrl() {
		return defaultTargetUrl;
	}

	public void setDefaultTargetUrl(String defaultTargetUrl) {
		this.defaultTargetUrl = defaultTargetUrl;
	}

	public String getLoginPage() {
		return loginPage;
	}

	public void setLoginPage(String loginPage) {
		this.loginPage = loginPage;
	}
	
	  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
	        if (!request.getMethod().equals("POST")) {
	            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	        }

	        String username = obtainUsername(request);
	        String password = obtainPassword(request);
	        String domain = obtainDomain(request);
	        
	        if (username == null) {
	            username = "";
	        }

	        if (password == null) {
	            password = "";
	        }

	        if(domain == null){
	        	domain = "";
	        }
	        username = username.trim();

	        DomainAuthenticationToken authRequest = new DomainAuthenticationToken(username,password,domain);

	        // Place the last username attempted into HttpSession for views
	        HttpSession session = request.getSession(false);

	        if (session != null || getAllowSessionCreation()) {
	            request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextEscapeUtils.escapeEntities(username));
	        }

	        // Allow subclasses to set the "details" property
	        setDetails(request, authRequest);

	        Authentication authentication = this.getAuthenticationManager().authenticate(authRequest);
	     
	        if(!(authentication instanceof DomainAuthenticationToken))
	        	throw new RuntimeException("Undesirable toke type");
	        
	        return authentication;
	    }

	    protected String obtainDomain(HttpServletRequest request) {
	        return request.getParameter(domainParameter);
	    }
}

Before we finish, we need to put all the stuff into the action, we need to just provide the bean declarations in our applicationContext.xml. This applicationContext .xml is by no means complete, as we need to provide a reference to the dataSource.

<?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:cap="http://www.springframework.org/schema/p"
	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.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd ">
	<authentication-manager alias="authenticationManager">
		<authentication-provider ref="domainAuthenticationProvider"/>		
	</authentication-manager>
	
	<beans:bean id="domainAuthenticationProvider" class="org.springframework.security.authentication.dao.DomainAuthenticationProvider">
		<beans:property name="userDetailsService" ref="domainUserDetailsManager"/>
	</beans:bean>
	
	<beans:bean id="domainUserDetailsManager" class="org.springframework.security.provisioning.DomainUserDetailsManager">
		<beans:property name="userByUserNameDomainQuery" value="select users.username,users.password,users.enabled,domain.domainname from users,domain where users.domainid = domain.domainid and users.username = ? and domain.domainname = ?"/>
		<beans:property name="authoritiesByUserNameDomainQuery" value="select u.username as username,p.permissionname as authorityname from users u,roles r,permissions p,userrole ur, rolepermission rp,domain d where u.username = ? and d.domainid = u.domainid and d.domainname = ? and ur.roleid = r.roleid and ur.userid = u.userid and r.roleid = rp.roleid and rp.permissionid = p.permissionid"/>
		<beans:property name="dataSource" ref="dataSource"/>
	</beans:bean>

	<http auto-config="false" entry-point-ref="loginUrlAuthenticationEntryPoint">
		<intercept-url filters="none" pattern="/login.jsp" />
		<intercept-url filters="none" pattern="/images/**" />
		<intercept-url filters="none" pattern="/userRegister.jsp" />
		<intercept-url filters="none" pattern="/rest/UsersService/Users" />
		<intercept-url filters="none" pattern="/scripts/generated/users/**" />
		<intercept-url access="IS_AUTHENTICATED_REMEMBERED"
			pattern="/**" />
		<custom-filter position="FORM_LOGIN_FILTER" ref="domainAuthenticationFilter"/>
		<logout />
	</http>
	
	<beans:bean id="loginUrlAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
		<beans:property name="loginFormUrl" value="/login.jsp"/>
	</beans:bean>
	
	<beans:bean id="domainAuthenticationFilter" class="org.springframework.security.web.authentication.DomainAuthenticationFilter">
		<beans:property name="alwaysUseDefaultTargetUrl" value="true"/>				
		<beans:property name="authenticationFailureUrl" value="/login.jsp?login_error=1"/>
		<beans:property name="defaultTargetUrl" value="/index.jsp"/>
		<beans:property name="loginPage" value="/login.jsp"/>
		<beans:property name="authenticationManager" ref="authenticationManager"/>
	</beans:bean>
		
	<beans:bean
		class="org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor"
		id="methodSecurityInterceptor">
		<beans:property name="authenticationManager" ref="authenticationManager" />
		<beans:property name="accessDecisionManager" ref="accessDecisionManager" />
		<beans:property name="securityMetadataSource">
			<beans:value />
		</beans:property>
	</beans:bean>
	
	<beans:bean class="org.springframework.security.access.vote.AffirmativeBased"
		id="accessDecisionManager">
		<beans:property name="decisionVoters">
			<beans:list>
				<beans:bean class="org.springframework.security.access.vote.RoleVoter" />
				<beans:bean
					class="org.springframework.security.access.vote.AuthenticatedVoter" />
			</beans:list>
		</beans:property>
	</beans:bean>	

</beans:beans>

I hope this blog post serves as a handy reference to carry out extension experiments with Spring security.

Updating Job/TimerEntity in Activiti Workflow Engine

Recently while implementing a workflow implementation using Activiti, I ran across a limitation where in the timer definitions which result into a the creation of Jobs to be ran by jobExecutors couldn’t be updated. The Business Use Case was strange since it required the extension of due date of a certain event. Now once the job is scheduled the Job’s due date could be viewed using managmentService provided but couldn’t be updated

Here in this post I would propose a working solution where in the Job resulting from a TimerDefinition could be updated ( of course, before it exprires).

Let’s start with the Job Interface.

org.activiti.engine.runtime.Job is the interface which defines the contract for a job being executed. A configured org.activiti.engine.impl.jobexecutor via the org.activiti.engine.ProcessEngineConfiguration picks up the jobs and executes them using a org.activiti.engine.impl.cfg.TimerSession.

A Job is extended by the org.activiti.engine.impl.runtime.JobEntity class which implements most of the functionality desired and JobEntity is further extended by the org.activiti.engine.impl.runtime.TimerEntity which is used by the org.activiti.engine.impl.cfg.TimerSession to schedule the jobs.
So Timer definitions like these in BPMN would result into creation of a TimerEntity scheduled by a TimerSession to be executed by a job executor.

<intermediateCatchEvent id="dateCheckLastNotice" name="dateCheck4LastNotice">
<timerEventDefinition>
<timeDuration>${duration}</timeDuration>
</timerEventDefinition>
</intermediateCatchEvent>

Now, we begin our work of implementing a solution. Activiti Process Engine is beautifully designed using the Command pattern in a style where in every request like completion of a user task etc. is accomplished using a commandExecutor. Here , in order to implement our updateTimer service we need to implement the org.activiti.engine.impl.interceptor.Command interface and provide the desired functionality.

protected void updateTimer(TimerEntity timerEntity) {

final class UpdateTimerCommand implements Command<TimerEntity>{
TimerEntity timerEntity;

public UpdateTimerCommand(TimerEntity timerEntity){
this.timerEntity = timerEntity;
}

@Override
public TimerEntity execute(CommandContext commandContext) {

DbSqlSession dbSqlSession = commandContext.getDbSqlSession();
dbSqlSession.getSqlSession().update("updateTimer", timerEntity);

return timerEntity;
}

}

springProcessEngineConfiguration
.getJobExecutor().getCommandExecutor().execute(
new UpdateTimerCommand(timerEntity));

}

We can implement this method in our workflow implementation class and this method could be called using the following semantics.

Once you’ve obtained the Job , simply put an instance check to proceed with this

if(job != null){
if(job instanceof TimerEntity){
TimerEntity timerEntity = (TimerEntity)job;

if(suspension.getEndDate().compareTo(new Date()) > 0){
timerEntity.setDuedate(suspension.getEndDate());
updateTimer(timerEntity);
}

}
}

Now, simply the job is updated, the only prerequisites are protected

void updateTimer(TimerEntity timerEntity)

should be covered under the boundaries of the transaction.

Here is the explanation of the above code

UpdateTimer is an implementation of the Command interface, which takes in a TimerEntity as constructor argument. The moment command is executed using the command context fetched from the jobExecutor ,following lines come into play.

DbSqlSession dbSqlSession = commandContext.getDbSqlSession();

org.activiti.engine.impl.db.DbSqlSession is a wrapper around the org.apache.ibatis.session.SqlSession class which covers the task of wrapping up of the database calls issued to SqlSession methods. As it doesn’t provide any method to directly accomplish the objective we proceed ahead with fetching up of the SqlSession reference.

dbSqlSession.getSqlSession().update("updateTimer", timerEntity);

here simply we fetch the SqlSession and execute an update for it. The mapping of “updateTimer” for the update function is provided in org.activiti.db.ibatis.job.mapping.xml.

The job gets updated and you are done.

Overriding default Serialization/Deserialization behaviour of JackSon json serializer

JSON is a desired media type for RESTFUL services. Jackson JSON library which is one of the preferred JSON provider for the Serialization/Deserialization of the JSON to Java Objects.

Recently I encountered a strange issue where in a UI library wasn’t producing desired JSON values for the boolean fields (true/false) but instead was producing values as (“y”/”n”), the strange behavior was also observed when it received (true/false) from the server as the desired values are (“y”/”n”).

The solution to this problem simply lied in customizing Serializing DeSerializing behavior of the Jackson Library.

Let’s start with the deserialization issue. Jackson provides API(s) to directly supply customized DeSerializers for the same.

We shall start with the ObjectMapper which provides functionality to convert between Java objects and matching JSON constructs.

Let’s subclass the ObjectMapper into


public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {

    }

}

In the constructor we can provide deserializing configuration(s) along with customized deserializers.

Prepare an object of the SimpleDeserializers. It’s a convenience java class supplied by Jackson library to add extra deserializers.

SimpleDeserializers simpleDeserializers = new SimpleDeserializers();

Now we would prepare a boolean deserializer for the same, our customized one.

private class BooleanDeserializer&lt;T extends Object&gt; extends
 JsonDeserializer&lt;Boolean&gt; {
 final protected Class&lt;?&gt; _valueClass = Boolean.class;

@Override
 public Boolean deserialize(JsonParser jp, DeserializationContext ctxt)
 throws IOException, JsonProcessingException {
 // TODO Auto-generated method stub
 return _parseBooleanPrimitive2(jp, ctxt);
 }

protected final boolean _parseBooleanPrimitive2(JsonParser jp,
 DeserializationContext ctxt) throws IOException,
 JsonProcessingException {
 JsonToken t = jp.getCurrentToken();
 if (t == JsonToken.VALUE_TRUE) {
 return true;
 }
 if (t == JsonToken.VALUE_FALSE) {
 return false;
 }
 if (t == JsonToken.VALUE_NULL) {
 return false;
 }
 if (t == JsonToken.VALUE_NUMBER_INT) {
 return (jp.getIntValue() != 0);
 }
 if (t == JsonToken.VALUE_STRING) {
 String text = jp.getText().trim();
 if ("true".equals(text)) {
 return true;
 }
 if ("false".equals(text) || text.length() == 0) {
 return Boolean.FALSE;
 }

if ("n".equals(text) || text.length() == 0) {
 return Boolean.FALSE;
 }

if ("y".equals(text)) {
 return Boolean.TRUE;
 }
throw ctxt.weirdStringException(_valueClass,
 "only \"true\" or \"false\" recognized");
 }
 // Otherwise, no can do:
 throw ctxt.mappingException(_valueClass);
 }
 }

This boolean deserializer is a generified class subclassing the JsonDeserializer, which is supplied to handle the deserialization of the values which are generally not supported by the default boolean  deserializer. Here we have overridden the

public Boolean deserialize(JsonParser jp, DeserializationContext ctxt) method and delegated the call to the

protected final boolean _parseBooleanPrimitive2(JsonParser jp,
 DeserializationContext ctxt) throws IOException,
 JsonProcessingException

In this method we obtain the token from the JsonParser and check for the usual values. This is done to make sure that the default behavior is not affected by the customized part. The implementation is identical to the Boolean Deserializer supplied by the StdDeserializer class of the JackSon library. Next, we fetch the values from the json parser and check whether they match with the values we desire. In case they do match we return the appropriate values else we raise an exception.

Now we would add our deserializer to the simpleDeserializers. To this use the following API.

simpleDeserializers.addDeserializer(Boolean.class,new BooleanDeserializer());

Here simply we have added the BooleanDeserizliaer for the deserialization of json values to type Boolean.

Next we need to do a few configuration steps.

Prepare an object of the StdDeserializerProvider

StdDeserializerProvider stdDeserializerProvider = new StdDeserializerProvider();
// Add additional Deserializers instance to it.
stdDeserializerProvider.withAdditionalDeserializers(simpleDeserializers);

//Set the Deserializer provider in the customized Object Mapper.
setDeserializerProvider(stdDeserializerProvider);

And you are done with it. Basically when you add additional deserializers they get priority over the default deserializers for the Class/Type already supplied by the jackson library.

Now , the tricky part.

Serialization is perhaps more trickier than the DeSerialization as, here we are trying to override the standard behaviour which is not supported directly and we need to imply a few things for the same.

We would start off with creating a customJson factory which could handle customization where required.

public class CustomJsonFactory extends MappingJsonFactory {
 public CustomJsonFactory(){
 super();
 }

}

Here CustomJson Factory extends from MappingJsonFactory so that most of the default implementation could be harnessed, overriding only the required portion. Now we need to sub class the JsonGenerator to control the serialization for the desired type. There are two implementations of the abstract class JsonGenerator supplied by Jackson. WriterBasedGenerator and Utf8Generator. WriterBasedGenerator is declared final and hence couldn’t be used. We shall subclass Utf8Generator and override the desired behavior.

public final static class CustomUTF8Generator extends Utf8Generator {

private final static byte[] ONE_BYTE = { 'y' };
 private final static byte[] ZERO_BYTE = { 'n' };

public CustomUTF8Generator(IOContext ctxt, int features,
 ObjectCodec codec, OutputStream out) {
 super(ctxt, features, codec, out);
 }

@Override
 public void writeBoolean(boolean state) throws IOException,
 JsonGenerationException {
 _verifyValueWrite("write boolean value");
 if ((_outputTail + 5) &gt;= _outputEnd) {
 _flushBuffer();
 }
 byte[] keyword = state ? ONE_BYTE : ZERO_BYTE;
 int len = keyword.length;
 System.arraycopy(keyword, 0, _outputBuffer, _outputTail, len);
 _outputTail += len;

 }
 }

Here we simply override the

public void writeBoolean(boolean state) throws IOException, JsonGenerationException 

to provide the desired behavior.

In this method we simply copy the byte array value of the ONE_BYTE or ZERO_BYTE array (depending on the boolean value) to the keyword byte array and  increase the outputTail by the length of the keyword array. This simply outputs the desired character as the serialized json value. Now we set this customized JsonGenerator into the custom json factory. This is done by overriding these two methods in the CustomJsonFactory.

@Override
 protected JsonGenerator _createJsonGenerator(Writer out, IOContext ctxt)
 throws IOException {
 return new CustomUTF8Generator(
 ctxt, _generatorFeatures, _objectCodec,
 new WriterOutputStream(out));
 }

This case requires little tweaking and we require to convert the java.io.Writer object to an output stream. I am using a convenience utility

org.apache.commons.io.output.WriterOutputStream.WriterOutputStream(Writer writer) from the commons-io ( version 2.0.1) for the same.
@Override
 protected JsonGenerator _createUTF8JsonGenerator(OutputStream out,
 IOContext ctxt) throws IOException {
 // TODO Auto-generated method stub
 return new CustomUTF8Generator(
 ctxt, _generatorFeatures, _objectCodec,
 out);
 }

In this overriding case we simply add the CustomUTF8Generator.

Now with this stuff completed, our CustomJsonFactory is ready to be set in the objectMapper with this call.

public CustomObjectMapper() {
 /**
 * Serialization stuff
 */
 super(new CustomJsonFactory());
 }

add this as the first line of the constructor in the object mapper, and you are done. Register the developed ObjectMapper instance and you can see the desired serialization/deserialization exhibited by it.