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

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.
sonar.jdbc.username={userName}
sonar.jdbc.password={password}
# Comment the following line to deactivate the default embedded database.
#sonar.jdbc.url=jdbc:h2:tcp://localhost:9092/sonar
#----- MySQL 5.x
# Comment the embedded database and uncomment the following line to use MySQL
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true

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

sonar-runner.properties:

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

Uncomment any driver of your choice.

#----- MySQL
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8
#----- Global database settings
sonar.jdbc.username={userName}
sonar.jdbc.password={password}

Sonar-project.properties:

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
sonar.projectKey=com.javapitshopt
sonar.projectName=javapitshop
sonar.projectVersion=1.1.6

# 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 ".")
sonar.sources=src,WebContent,build/classes

# The value of the property must be the key of the language.
sonar.language=java

# Encoding of the source code
sonar.sourceEncoding=UTF-8

# Additional parameters
#sonar.my.property=value

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.

/pathToSonarRunnerDirectory/bin/sonar-runner

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.

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"
	xmlns:context="http://www.springframework.org/schema/context"

	xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd


http://www.springframework.org/schema/aop


http://www.springframework.org/schema/aop/spring-aop-3.0.xsd


http://www.springframework.org/schema/mvc


http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


		
				
			
		



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 {

	@Autowired
	private HttpSession session;

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

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		//Provide your implementation here.
	}
	
	@Override
	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).

Web.xml

<listener>
    <display-name>sessionListener</display-name>
    <listener-class>com.javapitshop.SessionListener</listener-class>
</listener>

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.

SessionListener.java

/**
 * 
 */
package com.vdi.servlet;

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

/**
 * @author Javapitshop
 *
 */
public class SessionListener implements HttpSessionListener {


	@Override
	public void sessionCreated( HttpSessionEvent arg0 ) {
	
	}

	@Override
	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.

@Override
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.

NOTE:

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).

Pom.xml

<dependency>
	<groupId>c3p0</groupId>
	<artifactId>c3p0</artifactId>
	<version>0.9.1.2</version>
</dependency>

 

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"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd


http://www.springframework.org/schema/tx


http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<!-- Employee DB data source. -->
	<bean id="employeeDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<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}" />
	</bean>
	
	<context:component-scan base-package="com.javapitshop.dao">
	</context:component-scan>
</beans>

 

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.

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.employee_db_url=jdbc:mysql://localhost:3306/employee
jdbc.username=root
jdbc.password=root
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=100
jdbc.testConnection=true

 

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.Java

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

@Repository
public class EmployeeJdbcDAO extends BaseDao {

	/**
	 * Instantiates a new employee jdbc dao.
	 *
	 * @param userDataSource the employee data source
	 */
	@Autowired
	public ApplicationJdbcDAO(DataSource employeeDataSource) {
		super(ApplicationJdbcDAO.class);
		this.setDataSource(userDataSource);
	}
	
	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 };
		
		logger.debug(queryString.toString());
		
		// 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"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
		<property name="defaultLocale" value="de" />

	</bean>

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

	<bean
		class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
		<property name="interceptors">
			<list>
				<ref bean="localeChangeInterceptor" />
			</list>
		</property>
		<!-- <property name="pathPrefix" value="**/**.htm" /> -->
		<property name="basePackage"
			value="com.javapitshop.controller" />
	</bean>

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

	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<value>messages</value>
			</list>
		</property>
	</bean>

 

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.

Web.xml

 <!-- Security Filters and their Mappings. -->
 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 SpringContext-Security.xml

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:http>

 <security:authentication-manager>
  <security:authentication-provider>
   <security:user-service>
    <security:user name="shani" password="shani123" authorities="ROLE_USER, ROLE_ADMIN" />    
   </security:user-service>
  </security:authentication-provider>

 </security:authentication-manager>

 

Download Project Source Code

Below is an example of Spring Security using Database. In my case i have used mySql as primary database for authentication and authorization.

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

Web.xml

 <!-- Security Filters and their Mappings. -->
 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

Security URL pattern is defined and queries for authentication of users and their roles. Remember spring as given a standard schema for database. But it can be changed to some extent.

SpringContext-Security.xml

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

 <security:authentication-manager>
  <security:authentication-provider>
   <security:jdbc-user-service data-source-ref="dataSource"

    users-by-username-query="
     select username,password, enabled 
     from users where USERNAME=?" 

    authorities-by-username-query="
     select u.username, ur.authority from users u, user_roles ur 
     where u.user_id = ur.user_id and u.username =?  " 

   />
  </security:authentication-provider>
 </security:authentication-manager>

 

SpringContext-Database.xml

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">

  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/test" />
  <property name="username" value="admin" />
  <property name="password" value="admin" />
 </bean>

 

Download Complete Source Code

 

Polymorphic Calls
In this post I have tried to discuss a simple problem where we made a chain of classes. In above picture Vehicle is an Interface which contains all the basic properties of a vehicle e.g speed, color, engineType etc.
Then we have categorized the vehicle into “Car” and “Bus” which are implementing the “Vehicle” interface and providing some implementation of “getSpeed()” method.
As a “Car” is a generic type and we can sub divide it into different Brands, Types etc. I have categorized it into Brand “Ferrari” which is overriding the “getSpeed()” method and providing us speed of Ferrari.
public interface Vehicle {
        String getSpeed();
         String getColor();
}

 

Vehicle is a Super Type so it is declared as an interface. We can provide all the data members or properties of a vehicle in this interface as methods. Classes which will implement that interface will provide their definitions.
Reason of choosing interface as Super type is
  • it is standard approach to define Property methods in interface and its child classes will provide implementation.
  • A Class can extend only one class but can implement a no of interfaces. So its child classes still can extend any other class.

 

public class Bus implements Vehicle {
public String getSpeed() {
      System.out.println(“Average Speed of a bus is 80 KMPH”);
      return “80 KMPH”;
}
public String getColor() {
      return “Bus is Multi Color”;
}
}
public class Car implements Vehicle {
public String getSpeed() {
        System.out.println(“Average Car Speed will be 100 KMPH”);
        return “100 KMPH”;
}
public String getColor() {
        System.out.println(“Car can be of any color.”);
        return “Any Color”;
}
}

Car and Bus Classes are implementing Vehicle interface and providing implementation of its Property Functions according to their functionality and nature.

public class Ferrari extends Car {
     public String getSpeed() {
     System.out.println(“Maximum Speed of Ferrari is 250 KMPH”);
     return “250 KMPH”;
}
public String getColor() {
      System.out.println(“Color of Ferrari is RED”);
      return “RED”;
}
}

Class Ferrari is extending the Class Car and overriding the functions for providing the definition according to its own specifications. e.g color red, speed 250.

 

Vehicle Factory Class

Now to get rid of traditional methods of creating an object for each class or parent class to access its properties. Factory Pattern is a solution of this problem. It works as a centralized repository of objects which gives you the object if you pass it right parameter e.g car, ferrari, bus.
public class VehicleFactory {
public static Vehicle getVehicleByName(String className) {
      if(className.equalsIgnoreCase(“car”)) {
             return new Car();
      }else if(className.equalsIgnoreCase(“bus”)) {
            return new Bus();
     }else if(className.equalsIgnoreCase(“ferrari”)) {
           return new Ferrari();
    }
    System.out.println(” Invalid Type “);
    return null; 
}
}

 Test Runner Class 

public class TestRunner {
/**
* @param args
*/
public static void main(String[] args) {
Vehicle ferrari = VehicleFactory.getVehicleByName(“ferrari”);
ferrari.getSpeed();
ferrari.getColor();
Vehicle car = VehicleFactory.getVehicleByName(“car”);
car.getSpeed();
Vehicle bus = VehicleFactory.getVehicleByName(“bus”);
bus.getSpeed();
}
}