i have been working on Apache CXF, Karaf, Felix from path few months and i find all these bundled technologies very interesting to work with. While working on some use cases i have been got into a situation where i need only One Interceptor that should be executed on each HTTP request sent to any of bundles deployed under application in Karaf.

Basically i want to Authorize every request, change some headers and to do some security checks whatever request has been sent to the system and most importantly i want to do it at a single class. I found many ways to add interceptor in every bundle but i want to do that at some centralized location/bundle so that all the requests can be handled from that bundle. It can simply reject any request after doing some authorization or pass it to relevant bundle(cxf does that internally).

While doing this i came to know that CXF always creating a separate BUS for every RestServer that is being initialized in bundle’s Blueprint. But to achieve my goal we have to register all the bundles on same bus and apply the interceptor to that bus. With that we can control all the requests flowing on the bus.

Common Interceptor

public class CommonInterceptor extends AbstractPhaseInterceptor {

	public CommonInterceptor() {

	public void handleMessage(Message message) throws Fault {
		 * Here write whatever logic you want to implement on each HTTP call sent to your project.
		 * This interceptor will be called on every request that is being recieved by container and then will be sent
		 * to the relevant bundle/class for handling.

		String url = ( String ) message.get( URL_KEY_ );
		String method = ( String ) message.get( Message.HTTP_REQUEST_METHOD );

		LOGGER.debug( "################### Authentication Interceptor Validating Request : " + url + "####################" );

		Map< String, List< String >> headers = Headers.getSetProtocolHeaders( message );
                if ( headers.containsKey( X_AUTH_TOKEN ) ) {

Above is the common interceptor code where you can do anything with the request that is being sent to your server. In constructor i am assigning the Phase to which that interceptor will be hooked up. There are several Phases in CXF. You can get information about Phases link: Phases in CXF.

Extending AbstractFeature:

public class InterceptorManager extends AbstractFeature {

	private static final String COMMON_BUS_NAME = "javapitshop_bus";
	private static final Logger LOGGER = LoggerFactory.getLogger(InterceptorManager.class);
	private static final Interceptor< Message > COMMON_INTERCEPTOR = new CommonInterceptor();

	protected void initializeProvider(InterceptorProvider provider, Bus bus) {
		if ( COMMON_BUS_NAME.equals( bus.getId() ) ) {
			LOGGER.debug( " ############## Registering Common Interceptor on BUS ##############" );
			bus.getInInterceptors().add( COMMON_INTERCEPTOR );
		} else {
			LOGGER.error( " ############## Bus Id: '" + bus.getId() + "' doesn't matched with system bus id ##############" );

In above code i am extending AbstractFeature class and hooking up initilizeProvider method. Then i have given a name to our common bus. Basically whenever any OSGi Bundle gets installed it registered itself with the bus. In that case we are checking if the bundle has the desired bus Id. That bus ID will be unique system wide and all the bundles having this bus id will be registered to same bus and each and every request that will be related to those bundles will be sent to CommonInterceptor first.

Bus Registration In Bundles:

<cxf:bus id="javapitshop_bus">
			<cxf:logging />

To register the bundles with same bus you have to give an Id to that bus and register it in bundle’s blueprint.xml file. Do this in all relevant bundles and all those bundles will be assigned the same bus and CommonInterceptor will automatically be implemented to all the bundles.

You can downlaod the complete source code from my Github.


Now a days it has become mandatory to Gzipping the APIs response due to huge amount of data we are sending in response. It saves network bandwidth and delivery time and off course space over the internet.

While using CXF; it provides an option to use the Gzip Compression in no of ways.

  1. Blueprint
  2. Annotation


<bean id="gZipInterceptor" class="org.apache.cxf.transport.common.gzip.GZIPOutInterceptor" />
	<jaxrs:server id="rsServer" address="/gZip">
			<ref component-id="gZipInterceptor" />


First you need to register the GZIPOutInterceptor in out interceptors list. For that you need to hook into CXF initialization classes.

public class InterceptorManager extends AbstractFeature {

	private static final Logger LOGGER = Logger.getLogger( "simcore" );
	private static final Interceptor< Message > GZIP = new GZIPOutInterceptor();
	//private static final Interceptor< Message > GZIP = new GZIPOutInterceptor(512);
	/* (non-Javadoc)
	 * @see org.apache.cxf.feature.AbstractFeature#initializeProvider(org.apache.cxf.interceptor.InterceptorProvider, org.apache.cxf.Bus)
	protected void initializeProvider( InterceptorProvider provider, Bus bus ) {
		 * Adding Gzip interceptor to all outbound requests/responses
		LOGGER.debug( " ##############  Adding Gzip as OUT Interceptor ##############" );
		provider.getOutInterceptors().add( GZIP );

GZIPOutInterceptor comes with an option to set the Threshold value as no of Bytes. If response size will be below this threshold value then it will not be compressed. It is extremely useful when we will be sending empty lists and status messages/codes only. Because compressing those small responses will be overhead at server side.

But there is another factor which is no of users requesting the response. So set this value by thinking over all the cases in mind.


Now we can use this annotation on any of our web-services controller to implement compression on all the APIs provided in that class.

@Consumes ( { MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON } )
@Produces ( MediaType.APPLICATION_JSON )
public interface WebServicesController {

	@Path ( "/myGzipData" )
	@Produces ( { MediaType.APPLICATION_JSON } )
	Response getZipData( );


Moreover we can set different parameters in Gzip annotation.

@GZIP ( force = true, threshold = 512 )

In a project i was working with my team on OSGi project using Apache Karaf(2.3.5). At a time we decided to use hibernate and spring. While doing that i stuck up in an Exception of NoClassDefinitionFound where Hibernate-Annotations bundle couldn’t find a class from Spring-Orm bundle and both of these bundles were deployed and in Active state and added in my project’s class path.

After wandering about a lot on internet i found out a way where we need to resolve the dependencies of dependencies that are deployed in Apache Karaf.

Use this command to resolve the external dependencies of already deployed bundles.

dev:dynamic-import [bundle-id]

Restart the karaf and that bundle will come up in Active state.


Static code analyzer now become very common and useful while teams will be working specially using RAD. As to meet close deadlines and sprint dates developers usually get out of the right path and use some narrow tactics to accomplish some task.

I have been facing the same situation in my project in which we couldn’t been able to do peer reviews just to meet close deadlines. So we have configured Sonar just to remove any potential issue which we have missed while development or reviewing the code.

Download latest version of Sonar. e.g 4.3 Stable Release.
Unzip the package using command: unzip sonarPakageName.zip
Open to the file which is in folder: /conf/sonar.properties


In that file you can configure sonar settings related to Database and HTTP.
Just to make it easy and time saving we just set the database settings and rest of it will be on default settings.

# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
# Comment the following line to deactivate the default embedded database.
#----- MySQL 5.x
# Comment the embedded database and uncomment the following line to use MySQL

In case if you find any issue while connecting to database then change the localhost to ipAddress of your system.

Create a DB which you have mentioned in “sonar.jdbc.url”. For example above we have used “sonar” as our database name.

SonarQube runner:

Download SonarQube runner latest version. It is responsible for analyzing the project and it automatically submit the results in database. Which sonar use for reporting purposes.

Unzip the package using command: unzip sonar-runner
Open the file which is in folder: /conf/sonar-runner.properties


In this file you will find Database and security related settings of sonar qube.

Uncomment any driver of your choice.

#----- MySQL
#----- Global database settings


sonar-project.properties file contains information about project and source folders. This file persists at root of your project directory. Below is the content which we can define in that file.

# Required metadata

# Paths to source directories.
# Paths are relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# Do not put the "sonar-project.properties" file in the same directory with the source code.
# (i.e. never set the "sonar.sources" property to ".")

# The value of the property must be the key of the language.

# Encoding of the source code

# Additional parameters

Analyzer Execution:

Move to the bin directory in sonar base folder and execute command.

/sonar.sh start [in case of any issue try doing that with root permission or with sudo.]

Hit URL localhost:9000 in browser and you will find sonar web page in front of you.

Now move to your project root directory where sonar-project.properties file is being saved and execute command.


It will start analyzing the project and populate the database so that sonar can use it to display the statistics.

After its completion we can check the results at sonar portal.


In web applications/projects, we came across different scenarios where we need to check the request first before serving it or passing it to our main system or code.

For example in a MVC project we need to check every request that if it contains particular key/switch. That key/switch can inform us prior to processing that request to move it to particular system or portion e.g client side or admin side.

We came across the same case in which we need to verify the request first before passing it or mapping it to any controller class. For that purpose spring provides us with different listeners and hookups which can be used to overcome the cases like this.

For that we need to define a MVC request dispatcher in servlet-context.xml.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"



we can define multiple interceptors depending upon our use. In above code AuthenticationInterceptor is the class which will be called upon first on every request. If this class returns true then that particular request will be processes otherwise that request will be dropped and next request is considered for processing.

Authentication Interceptor

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

	private HttpSession session;

	 * Instantiates a new authentication interceptor.
	private AuthenticationInterceptor() {

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		//Provide your implementation here.
	public boolean postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		//Provide your implementation here.

In above code of AuthenticationInterceptor we can provide implementation of both methods preHandle() and postHandle(). Method preHandle() is being executed before processing of request and postHandle() after processing of request. You can use it depending upon your use case.


We have got a use case in project where we need to identify the time when Tomcat expires any user’s session. Basically we need to flush some persisted values of that user from DB.

For that i have hooked up sessionListener at application load(web.xml).



In web.xml file we are telling the server that it should intimate that class at the time of session creation and invalidation.
Server will automatically calls methods of this class if session of any user expires or developer himself invalidates any session.


package com.vdi.servlet;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

 * @author Javapitshop
public class SessionListener implements HttpSessionListener {

	public void sessionCreated( HttpSessionEvent arg0 ) {

	public void sessionDestroyed( HttpSessionEvent sessionEvent ) {


In above code we simply have to implement HttpSessionListener interface and override its methods. Methods are self descriptive so you can provide your implementation in any or both cases depending upon your usecase.

Below is my implementation how i have provided implementation of one of those overridden methods.

public void sessionDestroyed( HttpSessionEvent sessionEvent ) {
		synchronized ( this ) {
			HttpSession session = sessionEvent.getSession();

			if ( session != null ) {
				UserSessions sessions = userDao.getUserSession( session.getId() );
				if ( sessions != null ) {

					userDao.deleteUserSessionByUserId( sessions.getUserId() );
					UtilityLogger.logInfo( "UserSession Released from an expired login of User : " + sessions.getUserId() );


The major part of above provided implementation is persisted session id. Well as server is intimating application(SessionListener.java) on session invalidation so that means i couldn’t access anything saved in session as it is invalidated by server or user has called invalidate function himself. So for that we need to persist every user’s session id in DB and remove it from DB whenever its session expires or invalidates.

userDao.deleteUserSessionByUserId( sessions.getUserId() );

As i have been removing all the session entries of that user from DB.


Users who are working in frameworks like springs, may be get issues with bean autowiring at this point. As it will be loaded before setting up the context and bean container. So may be you people have to manually instantiate the class to whome you are calling. As in my case i have manually instantiated UserDao.java Class.


Connection pooling is an operation in which system pre-initializes the connection for use as creating connections at the time of use is an expensive operation. In this post we will learn how we can punch C3P0 connection pooling in Spring JDBC(somebody is not using hibernate).




Spring Context File (applicaitonContext-persistance.xml)

Now we need to prepare a JDBC context file for spring. We need to define a Data source for a DB with all its credentials.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	<!-- Employee DB data source. -->
	<bean id="employeeDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="jdbcUrl" value="${jdbc.employee_db_url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
		<property name="minPoolSize" value="${jdbc.minPoolSize}" />
		<property name="maxStatements" value="${jdbc.maxStatements}" />
		<property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
	<context:component-scan base-package="com.javapitshop.dao">


In above example we have created a C3P0 data source for Employee DB with all its credentials and Options. All the credentials and settings aren’t mentioned in context file. I have been using properties file for that.
Now this bean can be auto-wired in any DAO class as DataSource object.




BaseDao Class

Base DAO class is to define any abstract method or any common functionality which we need to use in all child classes. We can make it abstract or whatever we like according to our need. As i have overloaded its constructor to implement Logging. Now every child class need to provide its class definition.

package com.icsmobile.faadplatform.dao;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

 * Its the parent Dao class of the all the daos defined in the System.
 * @author JavaPitShop
public class BaseDao extends SimpleJdbcDaoSupport {

	//common logger for all the classes in the dao layer
	protected Logger logger;
	 * @param daoClass
	public BaseDao(Class<?> daoClass) {
		logger = Logger.getLogger(daoClass);



EmployeeJdbcDao is extending BaseDao and in constructor it is autowiring the “employeeDataSource” which we have defined in context bean.

public class EmployeeJdbcDAO extends BaseDao {

	 * Instantiates a new employee jdbc dao.
	 * @param userDataSource the employee data source
	public ApplicationJdbcDAO(DataSource employeeDataSource) {
	public EmployeeBO getEmployeeById(final int employeeId) {
		logger.debug("getEmployeeById(" + employeeId + ")");
		EmployeeBO employeeBO = null;
		StringBuilder queryString = new StringBuilder();

		queryString.append(" SELECT ")
				   .append( "*" )	
				   .append(" FROM employee ")
				   .append(" WHERE employee_id = ? ");

		Object[] parameterList = { employeeId };
		// execute query
		SqlRowSet dataRow = getJdbcTemplate().queryForRowSet(queryString.toString(), parameterList);
		if (dataRow.next()) {
			// create application object
			employeeBO = getEmployeeBusinessObjectFromRowSet(dataRow);

		return employeeBO;



I was doing a project and it was almost completed. Now i was asked to implement Internationalization in it and i successfully implemented that. After that i came across a challenge where i have to remove the messages from validation beans in which annotation based validation tags were implemented.

@Size(min = 1, max = 50, message = "Email size should be between 1 and 50")
private String loginId;


Now i have to shift all those error messages in properties files of all languages so that error messages will be loaded from properties files if user has changed the language.

Below are the steps of doing that.

@Size(min = 1, max = 50, message = "Email size should be between 1 and 50")
private String loginId;


Now remove { message = “Email size should be between 1 and 50” } from validation tag.
After doing this your annotation will be like this.

@Size(min = 1, max = 50)
private String loginId;


Now define this string in your properties file and a message against that string. Compile and execute. That message will be displayed whenever that annotation wouldn’t be validated.

Size.loginForm.loginId=email shouldn't be empty.


Basically spring makes its own string as key to its property file message if no error message has been given in annotation.
Below is the formula which spring uses to define a key of a property.

Size(@Size) = validation annotation name
loginForm = My Class Name
loginId = Property name in LoginForm class.



Spring provides us a flexible way to hook up internationalization in our framework/application at any time. It can be hook up in spring while loading the context.

Spring provides us two kinds of locale resolvers. Session based and Cookies based.
Session Based stores locale changes in session.
Cookie based stores locale changes in cookies.

You can choose any resolver of your choice and can register it as interceptor while loading the context.

Below are the XML changes need to be done in dispatcher-servlet.xml or servlet-context.xml files.

<bean id="localeResolver"
		<property name="defaultLocale" value="de" />


	<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> 
		<property name="paramName" value="lang" /> </bean>

		<property name="interceptors">
				<ref bean="localeChangeInterceptor" />
		<!-- <property name="pathPrefix" value="**/**.htm" /> -->
		<property name="basePackage"
			value="com.javapitshop.controller" />

			<mvc:mapping path="/**/**/**/" />
			<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
				<property name="paramName" value="lang" />

	<bean id="messageSource"
		<property name="basenames">


Above mentioned XML code is registering locale interceptor and after doing that every request will be intercepted by this interceptor to detect the change in locale/lang.

if at any point/time lang will be changed by user then messages from relevant properties file will be loaded.

if you system is supporting 3 languages then you must have 3 properties files. e.g message_en.properties

Add languages links with lang parameter and its value in all Jsp Pages.

<a href="?lang=en">en</a> | <a href="?lang=de">de</a>



Spring is offering extensive tools for implementing security. Users can use a no of techniques depending upon their problems.

Below is a simple spring application in which xml based authentication and authorization is being implemented.

A Filter proxy must be defined in web.xml file. This will implement/delegate filters and started intercepting the URLs.


 <!-- Security Filters and their Mappings. -->


Security roles and URL patterns must be defined so that Users will be verified from their credentials.

<security:http auto-config='true'>  
  <security:intercept-url pattern="/**" access="ROLE_USER, ROLE_ADMIN" />
  <security:http-basic />

    <security:user name="shani" password="shani123" authorities="ROLE_USER, ROLE_ADMIN" />    



Download Project Source Code