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);
		 criteria.setProjection(Projections.projectionList().add(Projections.property("personid")).add(Projections.property("personname")));

 criteria.setResultTransformer(Transformers.aliasToBean(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

Regular Expressions : How Exactly they work internally ?

Regular Expressions : How Exactly they work internally ?

Regular expressions were playing major role in computers from several decades, they are not as simple as we think. They are need extensive computational power, a decade before regular expressions were a big headache for computer programmers and scientists because they were consuming lot of time to complete the task.

History behind Regular Expressions :

A neuroscientist  who tried to understand how the human brain could produce complex patterns using simple cells that are bound together. In 1943, Warren McCulloch and Walter Pitts published “A logical calculus of the ideas immanent in nervous activity”.  this paper had a great influence on computer science during that time. In 1956, mathematician Stephen Kleene developed this model one step further. In the paper “Representation of events in nerve nets and finite automata” he presents a simple algebra. The terms Regular Sets and Regular Expressions were born from then. As mentioned above, Kleene’s algebra had only two operations and one function. In 1968, the Unix pioneer Ken Thompson published the article “Regular Expression Search Algorithm” in Communications.

A Pattern in regular expression :

How to learn regular expressions ? How to understand regular expressions?. They look confusing to understand regular expression but regular expressions are an elegant way to do some string manipulations.

We have studied finite automata and the regular expressions all just works on this theory, but Most modern programming languages (Perl, Python, Ruby, Java (and JVM based languages), C#) do not use this approach rather they use recursive backtracking approach. But finite automata is really good to understand regular expressions with its state diagrams and not a bad idea to implement in this approach may be recursive backtracking is better. So do you need a help to understand regular expression? here it is…

Let us take one example, Validating an email address

If this is your regular expression

[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)

The respective state diagram might look like below

Regular expression state diagram

Regular expression state diagram

 

Regular expression parser Source Code

If you want to try out with your own regular expression code you can better go through here 

http://www.codeproject.com/Articles/5412/Writing-own-regular-expression-parser

 

International Yoga Day : India is witnessing great change

International Yoga Day : India is witnessing great change

Today is International Yoga day. By the way what do we think of Yoga ? How can one define Yoga ? What are the key benefits of doing yoga ? Please read What Is Yoga to understand Yoga as described by Patanjali. Today is the first ever International Yoga Day and 21st June is the Yoga day. There are overall 50 nations all around the world including china, US, back Narendra Modi’s call to celebrate 21st June as International Yoga Day. 

Why 21st June As International Yoga Day?

The first yoga practitioner (Adi Yogi) is said to have begun imparting the knowledge of yoga to the rest of mankind on this day and became the first guru (Adi Guru) (Wiki) and from the perspective of yoga, the Summer Solstice marks the transition to Dakshinayana, the first full moon after summer is the lengthiest day.

Let me explain few asanas 

Sarvangasana – Mother of all asanas

Let me start with Sarvangasana , One asana which takes care of entire body, those who practice Sarvangasana daily will feel young and energetic always. Like how mother strives for harmony and happiness in the home, Sarvangasana strives harmony and happiness in human body.

Sarvangasana

Sarvangasana

Benefits

  • There are several endocrine organs or ductless glands in the human system which bathe in blood , absorbs the nutrients from the blood and secrete harmones for proper functioning of balanced and well developed body and brain 
    Many asana have direct effect on the glands , Sarvangasana take care of thyroid and parathyroid glands 
  •  Venous blood flow to the heart without any strain due to gravity helps for Healthy blood circulation around neck and chest.  As a result person suffering from breathlessness , palpitation, asthma, bronchitis, throat ailmens get relief.
  • Nerves will be soothed and headaches even chronic ones disappear 
  •  Continuous practice will eradicates common colds and other nasal disturbances 
  •  Those suffering from hyper tension , nervous breakdown, insomnia are relieved 
  • Bowels moves freely and constipation vanishes , as a result the system frees from toxins and feels highly energetic 
  • Recommended for urinary disorder an uterine displacements, menustrual trouble , piles and hernia 
  • It helps to reveal epilepsy low vitality and anaemia 
    If a person practices sarvanagasana daily will feel new vigour and strength and will be happy and confident 
  •  It activates the abdominal organs and relieves people suffering from ulcers

More Asanas –

1. Vajrasana : Start your daily Yoga with this asana, this is the only asana which you can do after having food also.

vajrasana

vajrasana

Benefits :

  • Calms the mind
  • Brings strength in back
  • Improves digestion and removes constipation
  • Good for urinary problems
  • Increases sexual organs
  • Good for digestive organs

2.  Vrksasana

Vrksasana

Vrksasana

Benefits 

  • Tones the legs muscles
  • Brings strength in legs 
  • Improves concentration – Very very good for concentration

3. Utthita Trikonasana

uttitha trikonasana

uttitha trikonasana

Benefits

  • Tones up legs muscles and removes stiffness in legs
  • removes stiffness in hips and reduces fat around hips
  • Corrects minor deformity in legs and allows them to develop evenly
  • Relieves backaches and neck sprains
  • Strengthen the ankles and develops the chest

4. Parivrtta Trikonasana

Parivrtta Trikonasana

Parivrtta Trikonasana

Benefits

  • Tones the thigh, Calf and hamstring muscles
  • The spine and muscles of the back gains strength and function properly
  • Increases the blood supply around lower part of spinal region and hence functions normally
  • Relieves pain in the back, viggorates the abdominal organs and strengthens the hip muscles

5. Virabhadrasana I

Virabhadrasana I

Virabhadrasana I

Benefits

  • In this pose chest is fully expanded and helps deep breathing
  • Relieves stiffness in shoulders and back
  • tones up the ankles and knees and cures stiffness of the neck
  • Reduces fat round the hips

 6. Salabhasana

Salabhasana

Salabhasana

Benefits

  • The pose aids digestion and relieves gastric troubles and flatulence 
  • Spine is stretched back it becomes elastic
  • Relieves pain in the sacral and lumbar regions 
  • Persons suffering from slipped discs will be benefited more
  • Bladder and the prostate glands also benefited 

7. Maha Mudra – Very powerful Asana should not be practices without a Guru

Maha Mudra

Maha Mudra

Benefits 

  • Tones up abdominal organs
  • Very good for kidneys and adrenal glands
  • Women suffering from prolapsed womb find relief as it pulls the womb up.
  • Person suffering from spleen alignment and from enlargement of the prostate gland will be benefited

Maha mudra destroys the death and many other pains. There is nothing that one cannot eat or has to avoid. All foods regardless of taste and even when deadly poisonous is digested. He who practises Mahamudra, overcomes consumption, leprosy, piles, enlargement of spleen, indigestion.

Thank You Modi Ji : We love you…

~~~ Celebrate International Yoga Day ~~~

        Happy International Yoga Day

Learn Yoga : Books recommended to become master in Yoga

1. Light on Yoga by B K S Iyengar 

Light on Yoga

Light on Yoga

http://www.flipkart.com/light-yoga-english/p/itme8gzshrhhbj3e?q=Light+on+Yoga+%28English%29&as=on&as-show=on&otracker=start&as-pos=p_1_light+on+yoga&pid=9788172235017

2. Light on Pranayama 

Light on Pranayama

Light on Pranayama

http://www.flipkart.com/light-pranayama-english/p/itme3u4busmjzn45?pid=9788172235413&ref=L%3A5808097100663242948&srno=p_1&query=Iyengar+Pranayama&otracker=from-search

Controversies Over International Yoga Day

It is sad to hear that people giving religious touch to Yoga and finally decided to leave Suryanamaskar one of the powerful Asana. Those who are arguing as India is accused of pushing ‘Hindu agenda’ on Muslims. Please grow-up.

Amazon EC2 : Connect to server using Putty

Amazon EC2 : Connect to server using Putty

Read our previous post : HOW TO CREATE AND CONFIGURE AMAZON EC2 FREE TIER ACCOUNT 

Generate the private key from the pem file

  1. To connect to Amazon server using Putty you need to have .ppk file. This can be generated from the .pem file which you have downloaded while creating the instance.

Open the puttygen.exe (if you don’t have please download from the net http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html ) to create the .ppk file from the .pem file.

Open the puttygen

a) Click on the load and load the pem (make file type as All) file.

Give the passphrase and confirm it. Then click on the save private Key.

putty key generator

putty key generator

 

Login to amazon linux box using putty

b) Now open the putty provide all the details as mentioned below

HostName : your amazon instance address (Public IP) or Public DNS

Port: 22

Go to Auth and give the private key file path.

Go to Data and provide the defaulr user: ec2-user

Amazon EC2 Putty login

Amazon EC2 Putty login

 

Amazon EC2 Putty Configuration

Amazon EC2 Putty Configuration

 

c) Click on Open in putty. It will ask for passphrase to enter provide the passphrase which you have entered while generating the private key.

After successful login you should be able to see this

SSH Login to Amazon EC2

SSH Login to Amazon EC2

 

Now you are successfully logged into Amazon ec2 box. Welcome to the amazon Linux box

Installation of Apache in the Box

  1. The amazon linux box will come with default java. No need to install separately (if you want you can install the other version of java)

To check the directory of java use the below command

 

1.	 The amazon linux box will come with default java. No need to install separately (if you want you can install the other version of java)
To check the directory of java use the below command
echo ${JAVA_HOME}

2.	You can install the Apache tomcat using the below command
sudo service tomcat7 start
	Or you can also copy paste the apache into some specific path using winzip
	Create directory share/tomcat/ inside /usr. 
	Copy the Apache from your local drive to usr/share/tomcat directory
3.	You can install the web-server using the below command:
sudo yum groupinstall -y "Web Server".
Use the below command to start and stop the webserver:
sudo service httpd start and sudo service httpd stop
4.	Deploy the war file into the WebApp folder in the apache tomcat then start the tomcat.
Access the application using the http://PublicIPAddress:8080/ApplciationName

Some usefull links and commands regarding setting up the your amazon server

Amazon EC2 mysql configuration

Amazon EC2 mysql configuration

http://www.excelsior-usa.com/articles/tomcat-amazon-ec2-advanced.html#port80

Amazon Cloud EC2 : Create and configure free tier account

Amazon Cloud EC2 : Create and configure free tier account

Are you searching for Free tier amazon AWS EC2 guide or tutorial ? Those who are working on Setup, configure and maintaining AWS amazon Server EC2 and S3 bucket. Here is the perfect guide for you. Sys Admins will love the guide.

Steps to create Amazon EC2 cloud account, 

1. GO to EC2 console and click on Instances at the left panel and Click on Launch Instance 

Create Amazon EC2 account

Create Amazon EC2 account

2. Select the AmazonMachine Image (AMI) which you want. (I have selected the 1st one ie amazon linux AMI)

Chose Amazon Machine (AMI)

Chose Amazon Machine (AMI)

 

3. By default General purpose is selected ie free-tier (t2.micro type). (You can select the any instance type you want based on your requirement) (I have selected the free tier t2.micra which comes with 1 GB ram by default)

Amazon EC2 Instance type

Amazon EC2 Instance type

 

4. Click Next tab at the below to configure the corresponding details. And in configure Security Group step select the Select an existing security group radio button and then Click on Review and Launch

5. Click on Review and Launch.

6. Once you click on Launch it will ask you to create key pair. Select Create New Key Pair from the drop down and give some name and click on Download key pair (It will helpful in future to connect Amazon server using putty). It will download one .pem file with the given name

7. Click on Launch Instances, this completed the creation of Amazon instances. In the next screen click on the view instances

Amazon EC2 launch instance

Amazon EC2 launch instance

 Amazon EC 2 DB instance creation 

1. Click on Services at the top bar select RDS at the left panel, Select DataBase under all services and then select RDS

Amazon EC2 DB creation

Amazon EC2 DB creation

2. Click on instances at the left panel and click on Launch DB Instance.

Amazon EC2 DB instance create

Amazon EC2 DB instance create

 

3. Select the required DB engine. (I am selecting MySql)

4. Production Select the No radio button for the free tier version and click on next step.

Amazon EC2 DB instance free tier

Amazon EC2 DB instance free tier

 

5. Fill the DB details in with the below details.

License Model : General-public-license

DB Engine Version : 5.6.2.3

DBInstance Class : db.t2.micra -1vCPU, 1 GB RAM

Multi-AZ Deployment : No

Storage Type : General Purpose (SSD)

Allocated Storage : 5

Provide the DB instance identifier, Master username and Passwor (these details will be usefull later for DB connection from the application or to connect from the sql clients)

Click on Next Step : Configure the advance details as shown below image for free tier.

Amazon EC2 DB Instance Advanced Settings

Amazon EC2 DB instance Advanced Settngs

Amazon EC2 DB instance Advanced Settings

 

Amazon EC2 DB instance Advanced Settings 1

Amazon EC2 DB instance Advanced Settings 1

 

5. Click on the Launch DB Instances and click on view DB instance to see the DB details. (It may take some time to create the DB)

Amazon EC2 Launch DB Instance

Amazon EC2 Launch DB Instance

 

Also Read : How to Configure Amazon EC2 Security group 

Also Read : An Interesting Article on how Facebook using aircrafts, laser beam to provide internet to remote areas on earth

Also Read : Interesting Article on How Facebook Using Artificial Intelligence, Facebook identifies you based on your hair style, your dressing, your standing posture

Also Read Windows 10 upgrade is available : See what you have to do if you can’t wait 🙂

Also Read : 8 Ways IOT will change your life .

Also Read : Is Google+ struggling ?

Solar powered Smartphones : Solar thin plate at back of the smartphone

Solar powered Smartphones : Solar thin plate at back of the smartphone

What will be the impact on environment due to usage of smart phones ? how much energy they consume ? this might look silly because after all a smartphone how much it can consume ?

fine let us analyse the data …

How much electricity your Gadgets use ?

An iPhone 6 plus battery spec is 2915 mAh battery (11.1 Wh), for your information 1Wh is a unit of energy equivalent to one watt (1 W) of power expended for one hour (1 h) of time.1 Wh represents 3600 joules of energy. Your iPhone uses 11.1Wh, now assuming you will charge your phone every day, so it means every year your phone consumes 4000Wh of energy per year.

now think about number of iPhone users , yeah here is the stats. Apple sold a whopping 74.4 million iPhones over the 90 day period. Which means 74400000 iPhones ( assuming all are iPhone 6 plus ). So the total amount of energy will be 1,97,60,00,00,000Wh.

A CFL bulb uses 767KWh per year, now converting 1,97,60,00,00,000Wh. to KWh gives us 29,76,00,000Wh

so using this much power we can use 389CFL bulbs for a year. Wait I am just considering iPhone 6 here.

We have Micromax,Samasung Galaxy series, HTC, Motorola etc. 

Now let us take a look into total number of mobile phones used in the world 🙂

 

Total number of mobiles in the world

Total number of mobiles in the world

 

Its a huge number – so energy being used ???

Why it is necessary to think about Solar Powered Smart phones ?

Considering the above stats it is really a good idea to think about keeping a solar plate attached to the back of your smart phone and completely avoid using electricity for charging. If you start using 3G you have charge your phone atleast two times in a day,  playing videos and games at least three-four times you have to charge in a day.

Let us look into few more stats – The below data is almost 3-4 years old 

61% of smart phone subscriptions, 4221 Mega joules of energy which is equivalent to 32gallons of Gas and emits 112Kgs of CO2.

Transferring 1GBit of data over 3G network will use 933 Mega joules of energy, If every one left their cell phone charger plugged It would waste electricity enough to power 28000 homes.

Reference : http://www.techi.com/2011/01/the-environmental-impact-of-cell-phones/

Finally at Mobile World Congress in Barcelona, a prototype has been shown that uses a display as solar panel to charge the battery.

Solar powered smartphone screen

Solar powered smartphone screen

 

 

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

Springs

Jersey2.8

Javascript

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(
				notificationBaseURL+"applicationnotifier/sse/events/register/"+loggedInUserName);
		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;

/*
    A CLASS THAT REGISTERS NOTIFICATIONS
    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
 */

@Singleton
@Path("/events")
public class NotificationHandler {
	
	final static Logger logger = LoggerFactory.getLogger(NotificationHandler.class);
	@Autowired
	@Qualifier("notificationDaoImpl")
	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.
     */
	@Path("/register/{userName}")
	@Produces(SseFeature.SERVER_SENT_EVENTS)
	@GET
	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
                newMessageNotificationFramework.java
             
             */
			List notificationTypes = getAllNotificationTypes();

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

			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;
        		
		default:
			return null;
		}
	}

    //Return different types of notifications supported in your application
	private List getAllNotificationTypes() {
		List notificationTypes = new ArrayList();
		notificationTypes.add("newMessageNotification");
		notificationTypes.add("likeNotification");
		notificationTypes.add("commentNotification");
		return notificationTypes;
	}

    /*
        Just returns a Map object for a given json string
     */
	@SuppressWarnings("unchecked")
	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
     */
	@Path("/broadcast")
	@POST
	@Produces(MediaType.TEXT_PLAIN)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	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")
					.mediaType(MediaType.TEXT_PLAIN_TYPE)
					.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");
				notificationBroadcasterMap.get(keyVal).broadcast(event);
			} 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
 */
@Service
public class NewMessageNotificationBusniessImpl extends
		NewMessageNotificationBusniessIntf {
	
    @Override
	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("localhost:8080")
                            + resourceBundle.getString("applicationnotifier")
                            + resourceBundle
                                    .getString("sse/events/broadcast/"));
			
			// postMethod.addParameter(data[0]);
			NameValuePair[] parametersBody = {
					new NameValuePair("message", convertToJson(message)),
					};
			postMethod.setRequestBody(parametersBody);
			httpClient.executeMethod(postMethod);

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


//NotificationAbstractFramework.java
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 "";
	}
}



Severe Exception : Struts tags without the associated filter

Severe Exception : Struts tags without the associated filter

SEVERE: Servlet.service() for servlet jsp threw exception
The Struts dispatcher cannot be found.  This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - [unknown location]
	at org.apache.struts2.views.jsp.TagUtils.getStack(TagUtils.java:60)
	at org.apache.struts2.views.jsp.StrutsBodyTagSupport.getStack(StrutsBodyTagSupport.java:44)
	at org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:48)
	at org.apache.jsp.jsp.failure_jsp._jspx_meth_s_005fif_005f0(failure_jsp.java:122)
	at org.apache.jsp.jsp.failure_jsp._jspService(failure_jsp.java:85)
	at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
	at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
	at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
	at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
	at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:488)
	at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
	at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
	at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:476)
	at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:420)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:208)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:722)


			




Jun 12, 2015 10:44:16 AM org.apache.catalina.core.StandardHostValve custom
SEVERE: Exception Processing ErrorPage[exceptionType=java.lang.Throwable, location=/jsp/failure.jsp]
org.apache.jasper.JasperException: The Struts dispatcher cannot be found.  This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - [unknown location]
	at org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
	at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
	at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
	at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
	at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:488)
	at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
	at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
	at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:476)
	at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:420)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:208)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:722)

Solution
if we want to use struts tags then request must pass through servlet filter. It can be done by mapping all the request to servlet filter by using. For these kind of issues check with all ur requests (actions) mapped in struts.xml.

In my case the issues was different and strange, In JSP null array list was being iterated using struts tags some things like below 

<c:forEach var=”itemImage” items=”${items.getImages()}”> where items.getImages() was null.

 

SEVERE: Exception sending context initialized event to listener instance of class

SEVERE: Exception sending context initialized event to listener instance of class

This issue typically appear during upgrading java from java 1.7 to java 1.8, and for Java 8 spring 3 does’t work, spring 4 upgrade is compulsory.

 

Exception :


			




SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/Spring-servlet.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:548)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4994)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.getDeclaredMethods(Unknown Source)
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:570)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:489)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:502)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:473)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:241)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1059)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1032)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1471)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1216)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
    ... 20 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.engine.FilterDefinition
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    ... 41 more

Solution
Hibernate 3
———————————
<bean id=”transactionManager”
        class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
        <property name=”sessionFactory” ref=”sessionFactory” />
</bean>
    
<bean id=”sessionFactory”
    class=”org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”>
</bean>

Hibernate 4
———————————
<bean id=”transactionManager”
        class=”org.springframework.orm.hibernate4.HibernateTransactionManager”>
        <property name=”sessionFactory” ref=”sessionFactory” />
</bean>

<bean id=”sessionFactory”
    class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>
</bean>

pom.xml changes

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.0.0.Final</version>
</dependency>

Future Of Technology : Imagine the future

Future Of Technology : Imagine the future

Where we are heading ? What will be the future ? The whole world is evolving just due to few big elephants, yeah Google,Apple,Facebook and Microsoft. Thousands of companies every day emerging out and directly or indirectly these big elephants are source for all these evolution in technology, they are changing the world.

Read : 8-ways-the-internet-of-things-iot-will-change-the-way-you-live

We have seen great inventions happened in last decade, Everything which was there upon the table now came to your finger tips, you can speak to your mobile and yeah it responds you back nicely. Apple Siri changed the way of communication with its touch interface in iPhone and voice interface in Siri, google now and microsoft’s Cortana.

Microsoft took one step ahead with its Hologram that is one of the awesome idea, but how much that would be complete we have to see only when we get it in use. Google’s self driving car and now Apple in the same line.

What else ??

An Era of Adopting to Technology

This is very old story now, 5 years before people use to say we should adopt technology, use technology and grow your business, use technology and optimise your tasks, use technology schedule your duty oh what not? It became big problem for old generation who never understood how to use computers and how to learn to use applications etc.

Observing closely the recent evolution in technology proves that, that era has gone now, it is taking a new shape and evolving even more sophisticatedly and smartly. then What we could expect out it ?

An Era of Technology being adopted to humans

Does’t it looks funny ? or does it make any sense ? yes of course it makes sense. Softwares are becoming smart with the intelligent algorithms, devices are becoming smarter with ultimate sensors, It is not just your touch, it is not just your voice now your movements and pattern are being analysed by algorithms and your device decides what to do next ! Google Search becoming clever every day it can understand the context you are working and you can query as if you are speaking to some one. Apple announced latest OS, the main focus is to make their device intelligent, It understands where you are, it understands what you are looking for it suggests you.

Operating systems are becoming smarter day by day, the data you are going to access are local more native centric, machines knew what you want, they understand you better than any one else 🙂

Future Is In Artificial intelligence ?

Looks like These big elephants are creating market for it, Apple’s HomeKit and google’s Brillo making every object you are using at home connected, your every device may start understanding what you are and they serve you what exactly you want and when exactly you want.

You home lock is connected to you phone, your kitchen is fully under your control, your lights will get on as you enter and off as you are leaving the room, algorithms understand your behaviour by analysing the data collected and will suggest you which food you can have now, they alerts you when you are eating high calorie food because your weight is under control since you started Yoga 🙂

artificialIntelligence

artificialIntelligence

Future Of Robotics !

So far robots were made for space missions, for military and for research areas but its the time to have a robot for your personal assistance everything what a human can do, now machines can do much better than him, Robotics in home appliances will be popular soon. Google is investing in robotics not only this much there are Top 10 Robotics companies which are expected to change the future of robotics.

iRobot

iRobot

Automation Industry

Thanks to ipv6, you can generate as many ip addresses using ipv6 where you can automate each and every device of every home in the world, Thanks to the concept of Internet Of Things where every device is connected to cloud directly, google’s Brillo is an example for IoT. You automate everything, control everything just using your smart phone, yeah really smart phone 🙂

Future Of Technology ?

One can imagine now what would be the future of Technology, Everything is connected, Everything under your control, Everything is automated, Everything is smart and intelligent, Everything just in front of your door. Rather than asking what you want, now your devices, your softwares will say what you need 🙂

 

Imagine the Future !

Companies investing heavily to make your life simpler, but we are really neglecting the mother nature, we are really forgetting environmental issues, our soil is polluted due to waste gadgets, chemicals etc our air is polluted, oceans are polluted. globalisation bringing more and more problems to us. We should really encourage and appreciate the use of renewable energy sources and make our future even better.

Use of solar panel for you mobile to charge, use of solar power to make ur robot work at home, use of intelligent architecture to cool your home/office, what else can be done ? just invent anything keeping environment in mind.

Enjoy the future because you have no work to do, you will be the laziest animal on this planet 🙂