Author Archives: devender kumar

About devender kumar

java/j2EE developer


read xlsx file in java

In this post of java tutorials we will see how to read xlsx file . We need few jar  for this. So before running this program please add following jars in your classpath. This program and jar files used in this are available in github repository.


When i run this program here is output

cellvalue :Product Category
cellvalue :Product Subcategory
cellvalue : productcode

cellvalue :productHeight
cellvalue :productWidth
cellvalue :productWeight
cellvalue :productDiameter
cellvalue :numberOfItems
cellvalue : numberOfLights
cellvalue :imageurl1
cellvalue :imageurl2
cellvalue :imageurl3
cellvalue :Lighting
cellvalue :Chandeliers
cellvalue :PH-CH-01
cellvalue :
cellvalue :
cellvalue :
cellvalue :Lighting
cellvalue :Chandeliers
cellvalue :PH-CH-02
cellvalue :
cellvalue :
cellvalue :

I hope this is somehow helpful to you. If there is any modification need please do share i with me to improve it.


Sorting list of maps based on a key, value pair values

In this post of java tutorial i will see how to Sort list of maps based on value of a single <key, sortingCriteriaValue> pair of maps. For example let we have student list of maps. Map have three key value pair having name, collage and course of students. We want to sort student list based on name of student.

List<Map<String, String>> student = new ArrayList<Map<String, String>>();

student.add(new HashMap<String, String>() {{
put(“name”, “devender kumar”);
put(“collage”, “PIET”);
put(“course”, “”);

student.add(new HashMap<String, String>() {{
put(“name”, “ankush jain”);
put(“collage”, “ARYA”);
put(“course”, “”);

student.add(new HashMap<String, String>() {{
put(“name”, “ankit jain”);
put(“collage”, “PSOM”);
put(“course”, “MBA”);


For this we need to Implement your own Comparator<Map<Key, Value>> based on map.get(“name”). Let see the complete program

When we run this program then we will see sorted list of student based on their name.

before sorting [{, name=devender kumar, collage=PIET}, {, name=ankush jain, collage=ARYA}, {course=MBA, name=ankit jain, collage=PSOM}]
after sorting [{course=MBA, name=ankit jain, collage=PSOM}, {, name=ankush jain, collage=ARYA}, {, name=devender kumar, collage=PIET}]

This is all in this post. Hope this is helpful.

create github repository from command line or console

Hi in this tutorial we will see how we can create github repository with command line or console. We can simply create repository in github with with UI and can use it. But some people like it to be created from console without visiting account via browser. It is very simple to create repository in github.

We use curl tool to create repository . When we search google then we can easily find curl command to create directory. But the problem that i faced in all the answer was problem parsing json. I found one answer that got me rid of this silly error. It was because of double quote. To remove this error we need to add backslash before every double quote.

Here is error that i was getting

json parse error

when we use  backslash before every double quote then we do not face any problem.

curl -u ‘user’ -d ‘{\”name\” : \”directory-name\” , \”description\” : \” description about directory\”}’

It will ask password of your github account and if you enter correct password then your repository will get created.

When we create directory with curl command the we get various information about this repository on console including git url ,clone url etc like this

“git_url”: “git://”,
“ssh_url”: “”,
“clone_url”: “

Now we have created repository on github we can our project add files in this repository .

Following commands will be sufficient to push your project into github

git init    initialized Git repository in current directory

git commit -m “first commit”

git remote add origin

here origin is alias name of When making changes next time we do not need to write url . we will use origin in alias of

In case you have already created origin as alias name to some other git repository then you would encounter problem like this

fatal: remote origin already exists.

To avoid this we need to remove existing repository alias from origin then need to assign  again. Here is command we use to remove existing repository from origin alias name.

git remote rm origin

then we need to again assign alias name to origin of our git repository

git remote add origin

once we have done it we need to push file into github repository with following command

git push -u origin master

Here master is the name of branch.

When making changes next time we just need following three command

git add .

git commit -m “your message for changes”

git push origin master.

get gmail account contacts using oauth 2.0 in java

In yahoo account contacts list with openid and OAuth we saw how to import yahoo account contacts. This may be useful in many scenario like inviting contacts on you website , sending some kind of information to user’s contacts etc.

In this post we will see how to import your google account contacts using Oauth 2.0. There are three basic steps :-

  1. Get user consent code
  2. Use user consent code to obtain access_token
  3. Use access_token to get data from particular API.

To retrieve contacts we need to create application project. To create project login in your google account and visit here.

Now in order to create new project select create new project  as shown below create new project gmail contact import

In next step enter project name and check i agree checkbox shown belowcreate new project gmail account contact import

In a few second your project will be created and you will see it as selected project as shown below.

select project gmail account contact import

Select your project from list and then click on APIs & auth section on LHS as shown below.

APIs and auth gmail account contact import

Click on credential. and select OAuth 2.0 client ID as shown belowAPI credential

We need to configure consent screen for userconfigure consent screen

In next screen fill the detail that will be visible to user. This logo will be visible when user will be prompted to Authorize your App. These all can be changed later. After filling details click on Save.project name

Select Application type as Web Application. and file name in next screen and click Create. Authorized redirect URIs can be changed later.create

Your project is ready now.credential project gmail account contact import

Click on project name to see client id and client secret. You can also change your redirect URI here.credential key and secret project gmail account contact import

Now just one more step in Application creation which is to enable API. Click on APIs in APIs & auth section and then click on contact API as shown api google enable

In next screen click on Enable API button

enable api

That all we are done with creation of Application. Note down client id and client secret. These are everything for us.

Now let see small coding part. First of all we need to get user consent code.


Simple link to redirect user for consent. When user accept and allow app to use contact then user will be redirected to redirect_uri that we give as an parameter. Note that this redirect url and the uri that we specify in google application that we have created must be same. Otherwise google will give mismatch redirect uri error.


When user give consent to use contact the user will be redirected at this jsp page as we have mention it in redirect uri. We use user consent token to get access token and then use that access token to retrieve actual information.In this case we will retrieve user contacts of google account.

Scope of all google APIs is available here . Main point i have already covered in code comments. Still there are some point that i will revise for more clarity. Above code is available at javafreakers github directory.

Google API Scope
Calendar Data API http(s)://
Contacts Data API http(s)://
Documents List Data API http(s)://
Sites Data API http(s)://
Spreadsheets Data API http(s)://
Calendar Resources HTTPS Read Only
Groups Rosters HTTPS Read Only
Nicknames HTTPS Read Only
Users HTTPS Read Only

When i run this and allow app to access my contacts here are some of my contacts

email and pic

That is all in this post. Hope it was useful. If you have any problem or doubt you can contact me. My contact information is available on About Me page of this site. If there is any suggestion to improve please let me. Have fun keep smiling and enjoy a lot every moment.


what is Application context level hierarchy in spring web application

Hi in this article of spring we will see what is applicationcontext , what is applicationcontext level hierarchy in spring web application, Why we need this hierarchy level, how applicationcontext is configure in spring web application etc. It is mostly theoretical article but it is very useful to understand spring application architecture.Now let begin with what is applicationcontext.

What is applicationcontext

Applicationcontext is container where beans live. In spring application we define beans most often in config files. Now for these bean to get instantiated a spring application context instance is created and  the config files in which bean configuration is given is loaded. Spring application context parse these files and  instantiate bean. When it is creating beans it store beans in Map. On completion of bean creation Map has all beans that are specified in config file. So application context act as a container for beans.

Why need applicationcontext hierarchy

When we are working with spring web application then we provide applicationcontext in two level.

  1. root applicationcontext(applicationContext)
  2. servlet specific applicationcontext(Webapplicationcontext)

Note: If your application is small than there is no need to create applicationcontext hierarchy. You can place all beans within a single config file which is your spring-serlvet.xml file.

But if your application is of large size and there are lot of beans in different module we should always use hierarchy level of context. The reason behind this hierarchy is that some of bean may be used throughout application i.e inside other beans  for example some service bean lets say userService may be used in many controllers of different modules.

Other beans that are used within specific context. For example let say we have a web application and there are many modules lets say student,  faculty and admin and so on and there is no relationship between beans of there modules. So beans for student can be defined in spring-servlet1 and beans for faculty can be defined in spring-servlet2 and so on. 

The reason for defining bean of these module in different spring-servlet is mapping of HTTP request, code clean-ness and remove confusion. Let say  HTTP request for student <url-pattern>/student/*</url-pattern> should be mapped in Controllers of student module. So we can configure a seprate spring-servlet.xml for it and can define controller of student module in it. Let say if we want to add or modify or remove any bean in a stuent module then we can do it easily in spring-servlet.xml file

If we put all beans of all module in a single spring-servlet file then if we want to modify any beanthen it is tedious to find that particular bean out of lots of beans in same file. Although there is no harm in putting all bean in single file but when the project size grow then it became difficult to manage.

Now let come to our main question why do we need hierarchy of application context. As we have seen above that beans related to particular module should be placed in its related spring-servlet file.

Now let suppose there are some beans like dao, service and spring security bean that are common in all modules. So we may defile these bean separately in some other file so that they can be share in all module.
For this purpose we may put these bean inside root application context. Root application context is shared in
all serlvet specific application context.

The root application context is parent of all servlet specific application context and is created prior to servlet specific application context.

We put all web-specific configuration like Handler Mappings etc in servlet specific application context and all non web-specific configuration like service dao and spring security concern etc in root application context.

root application context is created by ContextLoaderListener which is declared in web.xml

How applicationcontext is configure in spring web application

In above section we have seen why applicationcontext hierarchy is important if application size is large. Now let see how to configure this application context in spring web application. As we have seen there are two level of application context.

  1. root application context
  2. servlet specific application context

To configure root level application context we use ContextLoaderListener. ContextLoaderListener create a spring container that is shared between all servlet and filters. It look for context-param element in web.xml.


The context-param element contains the declaration of a web application’s servlet context initialization parameters. If context-param is not present in  web.xml then it will look for default applicationcontext.xml under Web-INF folder and if applicationcontext.xml present then it create beans by parsing config file. If it does not found applicationContext.xml cofig file under Web-INF then it will throw FileNotFoundException.

If context-param elemnt is present then it pick xml configuration file available in param-value element of context-param element. Like in above it will look for config file applicationContext -hibernate.xml in classpath and instantiate bean defined in this file and put in container.

ContextLoaderListener implement destroy method that will destroy beans when server shutdown.  Bootstrap listener to start up and shut down Spring’s root WebApplicationContext.

Now let’s see how to configure servlet specific context.

<servlet-class> org.springframework. web.servlet. DispatcherServlet </servlet-class>

Here bean defined in spring-servlet-context.xml will be registred in servlet-specific application context. Spring will  parse spring- servlet- context.xml and register bean defined in this config file. If <init-param> is not used to declare config file then spring will look spring-servlet.xml file under Web-INF folder.

<servlet-class>org.springframework .web.servlet. DispatcherServlet</servlet-class>

This is servlet name followed by servlet postfix. So here spring will look for spring-servlet.xml config file in Web-INF file.

We can also inject bean defined in root application context in servlet specific context like this

<bean id=”studentController” class=”com. javafreakers. StudentController>
<property name=”studentService” ref=”studentService”/> <!–studentService is defined in applicationcontext–>

Now let see how to declare multiple servlet specific context.

<servlet-name> admin</servlet-name>
<servlet-class>org.springframework. web.servlet. DispatcherServlet</servlet-class>

<servlet-name> student</servlet-name>
<servlet-class>org.springframework. web.servlet. DispatcherServlet</servlet-class>

<servlet-name> faculty</servlet-name>
<servlet-class>org.springframework. web.servlet. DispatcherServlet</servlet-class>

<servlet-name> admin</servlet-name>

<servlet-name> student</servlet-name>

<servlet-name> faculty</servlet-name>

Here are three servlet specific context.

This is all in this tutorial. hope it has helped you in understanding  application context and webapplication context. I will come up with some more tutorial very soon. Take care and Enjoy.

google search pagination example

pagination example in hibernate

In this article we will pagination example with hibernate . In application that uses large data it is always good practice to use pagination. Like in google search we see only first 10 search record on each page like this

google search pagination example

This offer benefit that the search time is less as getting ten record take less time than getting all the records from DB. It also limit page size. So response is quick.

One more benefit is that user only see best record of choice . User dont get confuse with too many record and can see choice record easily among limited record than from all the possible records.

In this article we will see example of product list. There are many product in DB . We will show only ten products at a time. It should look like this hibernate pagination example

The directory structure  is shown below for this example . Code for this article is provided on javafreakers github director.  There are three package of java classes . Controller package contain class which take request and return response. dao packge contain interface ProductDao  and its implementation package daoImpl which contain class ProductDaoImpl . This class contain DB transactions code. model package contain class which is simple pojo class.

Web-Inf contain  views folder and classes folder. In views folder there is a jsp file which disply products detail. classes folder contain spring-config package which contain file applicationContext-hibernate.xml for hibernate configurations information. file contain database regarding information i.e DB name, Driverclass name etc.

spring-servlet.xml file contains spring beans information.

hibernate paginator example directory structure

Now let see coding part. Although most of code is explained with comments but still i will try to explain it in detail.


web.xml file contain root configuration information. <servlet-mapping> element tell that any request with .html extension will be delivered to spring and handled by spring.

contextConfigLocation will help to locate configuration file from class path.


spring-servlet.xml define spring  specific beans. The Element <context:component-scan> Scans the classpath for annotated components that will be auto-registered as Spring beans. By default, the Spring-
provided @Component, @Repository, @Service, and @Controller stereotypes will be detected.  InternalResourceViewResolver bean is used to return response with the help of  prefix and suffix property. Spring will scan  prefix folder for suffix file extension to return response to user. In this example InternalResource ViewResolver will look in directory /WEB-INF/views/ for .jsp file. The name of file is return from controller class.

ProductDaoImpl is laso registred as spring bean.


These are xml configuration for hibernate. We have used PropertyPlaceholderConfigurer bean to get database configuration information from file. It use annotatedClasses properties to locate Entity classes which are configured with @Entity JPA annotation. In this example class is configured with this annotation.

jdbc.prperties file contain databse name , database driver name, database username and password.


Redirect to another page which is ProductHome for product list.


On this jsp page we are displaying records that we have set in session in controller class. This code is explained fully in comments.

Controller class listen user request and return response. In this we have a method inserProduct() which is basically to insert record in DB.

productsHome method is all logical part that is managing pagination functioning. Most of things have been cleared in comments of the code. When user request first time then we are returning first ten record . After that when user request with specified page number which is offset we are returning first ten record starting with offset number*10.

We have set size of total number of record , page number list that is to be display on jsp page and  product list in session.

This is interface for ProductDaoImpl class. It has three method. Detail of these method given below in  ProductDaoImpl. have three methods . One saving records in DB. One is for getting total numbers of record in DB. One method for getting product list for particular page. In the method getProduct() we have used criteria API for  getting Record for a particular page number. We use criteria.setFirstResult( ) method to tell hibernate to tell the starting record number . I.e first record and criteria.setMaxResults() to tell the number of record that need to be fetch after first record. For example suppose we have set first record as 15 and max record as 20 then hibernate will get us record from 15 to 34 .

In getSize() method we have again used Criteria to know total number of record present in Product table. is simple pojo class with properties and its getters and setters method. There is nothing to explain in it.

When you run this project first time then replace productsHome.html in index.jsp file with addProduct.html so that it can insert some record in DB. After that Undo code of index.jsp so that when you run this project again it display product table. Below is onload screen. Here start is not visible because we are in beginning.

hibernate paginator example onload first page screenshot

Here is screen when we click any page in between start and End . User can click on start ot End to go in beginning or End directly.

hibernate pagination example

When User is at the end page then End button is not visible but start button is visble to take user in beginning directly.

hibernate paginator example last page screenshot


Well that is all in this post of hibernate tutorials. Hopes this pagination article will help you  a lot. I will come back soon with next article. Till then take care stay happy stay blessed and enjoy.

Difference between session.get and session.load method

difference between session.get() and session.load() method in hibernate

In this post of hibernate we will see difference betwwen the two methods of fetching record from database. We will see difference between session.get() and session.load() method of fetching single record from DB. This is important question from interview prospective also.

He basic difference in these two approaches is that session.get() method fetch record from DB immediatly but session.load() method does not query to database immedialy instead it create a proxy (Dummy object) and return that dummy object. This dummy object does not contain value of actaul object. Here is image that will make clear

Difference between session.get and session.load method

Difference between session.get and session.load method

When we access data of object using getters then hibernate will query in database and then it will fetch actaul object from DB if it exist in database otherwise it will throw org.hibernate.ObjectNotFoundException: No row with the given identifier exists .

In case of session.getMethod if the record with given identifier does not exist then it does not throw ant exception instead it just return null.

Now let see it with example.


When we run above program and record does not exist with given id

I got proxy object.
Hibernate: select as id0_0_, student0_.emailId as emailId0_0_, as name0_0_, student0_.regNo as regNo0_0_ from Student student0_ where
Exception in thread “main” org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.freakers.getvsload.Student#4]

As you can see from output when we use session.load() methos then hibernate query to database only when we access data of object not at the time the load() method is called. At time when load() method is called it just create proxy( Dummy object).

Let see output when the record with given primary key exist in DB.

I got proxy object.
Hibernate: select as id0_0_, student0_.emailId as emailId0_0_, as name0_0_, student0_.regNo as regNo0_0_ from Student student0_ where

When we are accessing emailId from object then hibernate query DB and feetch actaul record from DB.


In session.get() method hibernate query to dataBase immediatly as the get() method called. If record with given primary key does not exist the it will reurn null otherwise it will return actaul object. Let see same example with session.get() method

Here is output when the record with given primary ley does not exist in DB.

Hibernate: select as id0_0_, student0_.emailId as emailId0_0_, as name0_0_, student0_.regNo as regNo0_0_ from Student student0_ where
I got original object.
Exception in thread “main” java.lang.NullPointerException

Here you can see hibernate query immediatly when get() method is called and it reurn null when record does not found in DB with given primary key.

Let see output when the record with given primary key exist in DB.

Hibernate: select as id0_0_, student0_.emailId as emailId0_0_, as name0_0_, student0_.regNo as regNo0_0_ from Student student0_ where
I got original object.

Now question arise what is use of load method when we have get method to fetch record.

Let suppose there is a scenario where we are not accessing data of object we just need to assign the object to some other object like this

Here we are not accessing data of student object. Instead we are just assigning student object to course object. So in this case we done need to fetch this record from DB. Here load() method can be usefull because it is creating object (proxy object) without doing any query to DB.

Note: Make sure that this object really exist in DB in such scenario. Otherwise it will lead serious problem.

This is all in this post oh hibernate tutorial. Hope this is helpfull to you. I will get back with some more interesting and usefull hibernate tutorial.

what is hibernate

org.hibernate.AnnotationException: No identifier specified for entity

Hi in this post we will see one more exception that occur because some time we forgaet to mention which field in our entity class will be primary key column. To remove this exception we need to tell hibernate which propery of entity class will be out primary key column. Let see simple example how this exception occur then we will resolve it


When we will run above program then hibernate will throw Exception in thread “main” org.hibernate.AnnotationException: No identifier specified for entity.

To remove this exception we need to tell hibernate which propery of entity class will be out primary key column.

This is all in this hibernate tutorial . This was pretty simple and small post. Hope it has help you.


what is hibernate GenerationException: ids for this class must be manually assigned before calling save()

In this post of hibernate we will see one more exception that often occure because some time we forget to specify genration stretagy of primary key column for record in Entity class and neither we give it manually.

Here is simple example of student entity class we are trying to save without specifying genration stretagy of primary column .


Here we are not setting up primary key and neither we have specify any genration stretagy in student class. When we will try to run above example then ids for this class must be manually assigned before calling save(): exception will be given by hibernate.

We need to modify Student class and add  genration stretagy for primary key genration. We can also overcome from this exception by supplying primary key before saving object.

Modified Class is below

This is all in this tutorial. I will get back with almost similar next tutorial.

adpter class example in java

java Adapter class example

Hi in this post of core java tutorial i will discuss about Adapter class in java. Why adpter class is used. Adpter is design pattern in java. Adpter is somthing that connect two component.

adpter class example in java

adpter class example in java

Adapter is a pattern that provides default (often empty) implementation of interface or abstract class. . It is useful because very often you do not really use all methods declared by interface, so implementing the interface directly is not usefull.

Let see with example

In the example Pin is interface that contacin five methods.

Adpter class give default implementation to Pin interface methods.

Changer class extend Adpter class and override one of its method. So instead of implementing five method out of which four are of no use in Changer class it just uses one method which it override from Adpter class.

This is all in this tutorial of core java. I will get back soon with next interesting tutorial.