Web Services

Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.EntityRegion

Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.EntityRegion

Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.EntityRegion


Caused by: org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given; please either disable second level cache or set correct region factory using the hibernate.cache.region.factory_class setting and make sure the second level cache provider (hibernate-infinispan, e.g.) is available on the classpath.



  1.  Replace POM dependency for net.sf.ehcache : ehcache-core

  Replace below lines


From below lines


2. set Factory_class in spring.xml file as given below

Replace below lines

				prop key="hibernate.cache.region.factory_class" net.sf.ehcache.hibernate.EhCacheRegionFactory/prop
				prop key="hibernate.cache.use_query_cache"> true/prop

With below lines

				prop key="hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.EhCacheRegionFactory /prop
				prop key="hibernate.cache.use_query_cache">true /prop

3.  Then use setCacheable(true); for your queries in hibernate criteria


Selecting certain fields in Hibernate Criteria using Projections

Selecting certain fields in Hibernate Criteria using Projections

This is not a great post but many people will face this issue and the solution is very simple for which many will spend hours of time to find it.

Issue faced by many are selecting certain fields of the table using hibernate criteria, converting array of Objects (Object[]) to respective custom class object, Even after converting the values for the fields will be set to default rather than actual values of the fields.

Take an example :

  Class Person {
    private Integer personid;
    private String personname;
    private String mobilenumber;
    private String permanentaddress;
    private String localaddress;

    public Integer getPersonid(){ }

    public void setPersonid(Integer personid){ }

    public String getPersonname(){ }

    public void setPersonname(String personname){ }

    //Other fields getter/Setter

In this example assume that you wish to fetch only personid and personname using hibernate criteria

Fetching only selected fields using Hibernate Criteria

  List persons = null;
  Criteria criteria = sessionObject.createCriteria(Person.class);

 persons = criteria.list();

Issue : All fields are getting empty/default values after using hibernate projections

This issue is a very difficult to tackle, because hibernate doesn’t through any exception for this but it returns objects filled with default values of fields.

Solution: The solutions is really simple, just use an alias to each field in projections

//See alias personid and personname for both the fields
//Projections.property(“personid”),”personid”) and Projections.property(“personname”),”personname”)

 criteria.setProjection(Projections.projectionList().add(Projections.property("personid"),"personid").add( Projections.property("personname"),"personname"));


The above solution doesn’t work for One-To-Many relationship also when there is an aggregation, has-a relationship.

A Wrapper to fetch selected fields using hibernate Projections for One-To-Many relationship

Download the library given below and import it in your project, then define a Response Class like PersonResponse.java, which should be exact replica of Person.java , where it holds all details of a person fetched from database person table.

then just use the below code 

personCriteria.setResultTransformer(new AliasToBeanNestedResultTransformer(PersonResponse.class));

Source Code : AliasToBeanNestedResultTransformer

Thanks to : http://stackoverflow.com/a/25770708/526438

Server Sent Events (SSE) using Jersey, spring and Javascript

Server Side Event not firing in Jersey 2.8 using SSE

Notifications were playing a major role in every applications either it is a mobile application or web application or even a desktop application. These days every latest Operating system updates were including Facebook as a service within OS itself and mail notifications were just on your desktop.

It is important to learn how to support realtime notifications in your web applications. Following technologies were considered in the given example




Server Sent Events Javascript Code

Register to Server Sent Events in Javascript


var notificationBaseURL =  "http://myapplication.com/"; //The URL Where your services are hosted
function listenAllEvents() {
	if (typeof (EventSource) !== "undefined") {

		var source = new EventSource(
		source.onmessage = notifyEvent;
	} else {
		console.log("Sorry no event data sent - ");

function notifyEvent(event) {
	var responseJson = JSON.parse(event.data);
	alert("... Notification Received ...");

In the above code the URL is specific to user who have logged in. Every user has to register for notification.

Java Spring Code For Server Sent Events(SSE):


//    NotificationHandler.java

package com.applicationnotifier.Notification.WebServices.Impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jettison.json.JSONObject;
import org.glassfish.jersey.media.sse.EventOutput;
import org.glassfish.jersey.media.sse.OutboundEvent;
import org.glassfish.jersey.media.sse.SseBroadcaster;
import org.glassfish.jersey.media.sse.SseFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.ResponseBody;

import com.applicationnotifier.Notification.framework.impl.NotificationFrameworkFactory;
import com.applicationnotifier.Notification.framework.intf.NotificationFrameworkInterface;
import com.applicationnotifier.dao.notification.NotificationDao;
import com.applicationnotifier.pojo.Form;
import com.applicationnotifier.pojo.notification.Notification;
import com.applicationnotifier.responsepojo.NotificationResponse;

    Registering does following functions
    1. Create a broadcaster object for each notification type
    2. Map Event Output object for each broadcaster to broadcast a message
    3. Broadcast the event

public class NotificationHandler {
	final static Logger logger = LoggerFactory.getLogger(NotificationHandler.class);
	NotificationDao notificationDao;

        A map thats keeps track of each notification and its output event object. broadcaster object.
        SseBroadcaster will perform broadcasting the notification
	Map<String, SseBroadcaster> notificationBroadcasterMap = new HashMap<String, SseBroadcaster>();

     registerForAnEventSummary: will be called when the client registers for notifications
     in javascript we call listenAllEvents() method.
	public @ResponseBody EventOutput registerForAnEventSummary(
			@PathParam("userName") String userName) {
		try {
			NotificationFrameworkFactory factory = new NotificationFrameworkFactory();
			EventOutput eventOutput = new EventOutput();

            /* Returns all types of notifications, for each type of notification there should be an implementation as newMessageNotificationImplementation or newMessageNotificationFramework
                Exmple  newMessageNotification, in this example this notification has a class
			List notificationTypes = getAllNotificationTypes();

			for (String notificationType : notificationTypes) {
				NotificationFrameworkInterface notificationInterface = factory
				String keyVal = getKeyVal(notificationType, userName);
				if (!notificationBroadcasterMap.containsKey(keyVal)) {
                    //Add broadcaster to map
                //Get broadcaster and add event output

			return eventOutput;
		} catch (NullPointerException exception) {
			logger.error("Exception Occurred: ", exception);
		return null;

     getKeyVal : every user must register for each notification
                Notification Key : newMessageNotification_Ram indicates Ram is listening to newMessage notification
	private String getKeyVal(String typeOfEvent, String userName) {

		switch (typeOfEvent) {
		case "newMessageNotification":
        case "likeNotification":
        case "commentNotification":
			return typeOfEvent + "_" + userName;
			return null;

    //Return different types of notifications supported in your application
	private List getAllNotificationTypes() {
		List notificationTypes = new ArrayList();
		return notificationTypes;

        Just returns a Map object for a given json string
	protected HashMap<String, String> getMapFromJson(String message) {
		ObjectMapper mapper = new ObjectMapper();
		HashMap<String, String> value = null;
		try {
			value = mapper.readValue(message, HashMap.class);
		} catch (IOException e) {
			logger.error("Exception Occurred: ", e);
		return value;

        Broad cast notification to all clients which are registered for notification
	public String broadcastNotifications(@FormParam("message") String message) {

		try {
			HashMap<String, String> value = getMapFromJson(message);
			JSONObject responseJson = new JSONObject(value);
			 * System.out .println("received data: " + message);
			OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
			OutboundEvent event = eventBuilder.name("message")
					.data(String.class, responseJson.toString()).build();

            //Things you wish to send to client
			String keyVal = getKeyVal(value.get("ntftyp"),
                                      , value.get("un"));
			System.out.println("broadcasting: " + message + " to: " + keyVal);
			if (notificationBroadcasterMap.get(keyVal) != null) {
				// System.out.println("message is ready for broadcasting");
			} else
				System.out.println("no broadcaster for: " + keyVal);
		} catch (NullPointerException exception) {
			logger.error("Exception Occurred: ", exception);

		return "Message '" + message + "' has been broadcast.";

// NewMessageNotificationBusniessIntf.java

package com.applicationnotifier.Notification.business.intf;

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

import com.applicationnotifier.Notification.framework.impl.NotificationAbstractFramework;

public abstract class NewMessageNotificationBusniessIntf extends NotificationAbstractFramework {
    public boolean notifyNewMessage(HashMap<String, Object> message);

// NewMessageNotificationBusniessImpl.java
package com.applicationnotifier.Notification.business.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.applicationnotifier.Notification.business.intf.NewMessageNotificationBusniessIntf;

    Call these methods when some updates happened in your Database
    Example - Some one sent a message, the messageInsert service will be called (Spring Controller,Service,Repository ) 
    in Service layer create object of NewMessageNotificationBusniessImpl and call these methods to notify
    In these methods just call Post/Get methods , these methods are services for your notifications
        URL - sse/events/broadcast/
    Any call to sse/events/broadcast/ will call a method defined in NotificationHandler class i.e broadcastNotifications
public class NewMessageNotificationBusniessImpl extends
		NewMessageNotificationBusniessIntf {
	public boolean notifyNewMessage(HashMap<String, Object> message) {
		try {
			message.put("msg", message.get("un") + " You have new message ");
			HttpClient httpClient = new HttpClient();

			PostMethod postMethod = null;
            postMethod = new PostMethod(
                            + resourceBundle.getString("applicationnotifier")
                            + resourceBundle
			// postMethod.addParameter(data[0]);
			NameValuePair[] parametersBody = {
					new NameValuePair("message", convertToJson(message)),

			BufferedReader responseReader = new BufferedReader(
					new InputStreamReader(postMethod.getResponseBodyAsStream()));
			String line;
			while ((line = responseReader.readLine()) != null) {
			return true;
		} catch (Exception e) {
			logger.error("Exception Occurred: ", e);
		return false;

package com.applicationnotifier.Notification.framework.impl;

import java.io.IOException;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class NotificationAbstractFramework {
	final static Logger logger = LoggerFactory.getLogger(NotificationAbstractFramework.class);

	protected String convertToJson(Map<String, Object> message) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			return mapper.writeValueAsString(message);
		} catch (IOException e) {
			logger.error("Exception Occurred: ", e);
		return "";

Web Services – Chapter 2

RESTFul Web Services – A First Step

Before starting with RESTFul web services , one must be knowing the basics of web services, We have studied basics of web services in our previous chapter, Once you learn basics, it will be great to go ahead.

As we discussed in previous chapter Web services plays a major role in future of web. We will try to learn how the things will be developed, we will have a hands on with development of web services using java. Before starting with web service development we will like to give step-by-step guide for java setup.

We need java sdk installed, tomcat server installed and eclipse as an IDE for development. Web services can be developed with PHP, C# .net , Ruby on Rails. Since our team is comfortable with java, we would like to write further chapters targeting java for the same.

Set-up for Mac Users
Install Java sdk
1> Download jdk 7 from the link

2> Double click on .dmg file , which opens a window and double click on package file as shown in the fig below.

jdk dmg img

3> Click continue in the installation window

4> Enter user name and password of your system

Install tomcat
1> Download tomcat from the link
(Download the zipped file – zip (pgp, md5) )

2> Unarchive the tomcat folder from your download folder.

3> Open the terminal and execute the following commands

These commands are used just to move the tomcat folder into /user/local folder.

sudo mkdir -p /usr/local

sudo mv ~//apache-tomcat-7.0.47 /usr/local

(Usually it will be sudo mv ~/Downloads/apache-tomcat-7.0.47 /usr/local)

4> Create symbolic link for the tomcat – this helps to keep tomcat updated when we get latest tomcat updates.
First create tomcat folder
sudo rm -f /Library/Tomcat

Create symbolic link of tomcat
sudo ln -s /usr/local/apache-tomcat-7.0.47 /Library/Tomcat

5> To make tomcat executable, the ownership of the folder must be changed
sudo chown -R <your_username> /Library/Tomcat

6> To start and stop tomcat we need to run the scripts, to set the execute permission to scripts run the below command

The installation of tomcat is done!
Check whether tomcat starts smoothly or not by starting tomcat with the script
Screen Shot 2014-06-04 at 8.50.01 pm
knowledgecess:~ cess$ /Library/Tomcat/bin/startup.sh

Using CATALINA_BASE: /Library/Tomcat
Using CATALINA_HOME: /Library/Tomcat
Using CATALINA_TMPDIR: /Library/Tomcat/temp
Using JRE_HOME: /Library/Java/Home
Using CLASSPATH: /Library/Tomcat/bin/bootstrap.jar:/Library/Tomcat/bin/tomcat-juli.jar

knowledgecess:~ cess$ /Library/Tomcat/bin/shutdown.sh
Using CATALINA_BASE: /Library/Tomcat
Using CATALINA_HOME: /Library/Tomcat
Using CATALINA_TMPDIR: /Library/Tomcat/temp
Using JRE_HOME: /Library/Java/Home
knowledgecess:~ cess$

In our next chapter let us try to create a sample on web services in Java.

Web Services – Chapter 1

We know a typical client-server communication model , where a client request for useful data and server responds with the valid data over network. The way of communication might differ based on the type of software running at server side, which means if a server is just an ftp server then one has to get the file by running an ftp command, if the type of resource is just a static html page then a simple http get request is sufficient and the communication can be achieved with a suitable communication protocol. The concept of web service gives real boost to the mode of communication between client and server. The client server model becoming more complex than ever with awesome facilities over the internet. Web services are identified as latest technological changes that is enriching the world of business. Software modules written on any language can talk to each other to transfer a set of resources over the internet. This was not the case before web services, with the help of web services both client and server became loosely coupled. With this overview of web services, let us define the web services and understand the concept in depth.

Definition Of Web Services –

Web service is a mode of communication between two devices provided by a software system running at network address over the web, designed and developed to support interoperable machine-to-machine communication over the internet.

The term interoperable in the above definition means a lot when we discuss about web services. The simplest meaning of interoperability is working together, irrespective of the type of communicating devices , both the devices should be able to share the information by exchanging data in the form of specific data format or communication protocols to produce a meaningful result.

To make the concept more clear , let us take an example which describes where and how web services sits in the entire process of communication.

-Assume that you have a set of huge data stored in your server, the data which is collected from your extensive research on physics. If you would like to share your data to the external world in a very meaningful structured way then you can’t just post every data on your website. Because sharing data in a web site is not a structured way , structured way means according to me , share every bit of data but one should use it as per their need.

If one wants data related to astrophysics could be able to fetch only related data, if one wants data related to modern physics could be able to fetch only related data. To achieve this the only best approach is web services.

Develop a software module that query the related set of data from your server and responds to the client by sending only that piece of information. The client here may be of any kind, It might be a mobile application, tablet application, desktop application or web application. Irrespective of the type of client, your software module responds the right information as per the incoming request. Let us understand this with the help of architectural diagram.

Web Services – Architectural Diagram

Architecture Web Services


Above diagram is self explanatory which describe about 5 modules , the important point that is clear from the architecture is, a web service software module deployed in the server is capable to process request from any type of client and serve the requested information, this is what we call as interoperability. Web services hence take the web technology to the next level.

How is that Practical –

So far what we discussed is just a theoretical approach of understanding web services. Being a software developer you will be interested to learn how to develop/consume web services. Web services can be developed using any server side

language , Java, C# .net, PHP , Ruby On Rails etc.There are mainly two types of web services SOAP Services and RESTFul services.

1. SOAP Services – Web services can be developed by adopting SOAP protocol , where client-server communication happens by describing the details with WSDL ( Web Service Definition Language ). An XML language will be used to define the message format , which will be sent across the network.

2. RESTFul Services – Representational State Transfer is an information transfer , the services responds to the request with a help of unique service URL and set of data as input for the service. XML is not mandatory , the data can be passed either in plain text or JSON format.

We will learn development of RESTFul web services using Java in our next chapter.