Wednesday, August 29, 2012

What is Liquibase ?

1. Liquibase is an open source database-independent library for tracking, managing and applying database changes.
2. All changes to the database are stored in XML files and identified by a combination of an "id" and "author" tag as well as the name of the file itself.
3. A list of all applied changes is stored in each database which is consulted on all database updates to determine what new changes need to be applied.
4. Liquibase executes changes based on this XML file to handle different revisions of database structures and data.
5. When you first run a changelog, LiquiBase manages those changelogs by adding two tables into your database.
databasechangelog: maintains the database changes that were run.
databasechangeloglock: ensures that two machines don't attempt to modify the database at one time.
6. Limitations do exist such that it will not export triggers, stored procedures, functions and packages.

Sample changeLog file:

 The above is an example of creating table EMPLOYEE and adding columns into it.

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns=""
    <changeSet author="waheed" id="123456789-1">
        <createTable tableName="EMPLOYEE">
            <column autoIncrement="true" name="EMPLOYEE_ID" type="BIGINT">
                <constraints nullable="false" primaryKey="true" />
            <column name="NAME" type="VARCHAR(255)" />
            <column name="GENDER" type="VARCHAR(2)" />
            <column name="COUNTRY" type="VARCHAR(255)" />
            <column name="ABOUT_YOU" type="VARCHAR(255)" />

How to integrate Liquibase with Spring and Hibernate ?

A sample tutorial on how to integrate Liquibase with Spring and Hibernate.

While writing this tutorial, I have added javadoc in the code for better understanding and I believe You already have good knowledge on Spring and Hibernate. The main motto of this tutorial is to give an idea on how you can integrate Liquibase with Spring and Hibernate.

If you are new to Liquibase : Click Here

To integrate liquibase into your project, you need liquibase jars, So download it before starting the project.

I have created an application named "SHLIntegration". The Structure of the project is as follows :

The dependencies are also listed here:

Lets start with Employee class :

1. Create Employee class having getter/setter and add proper JPA annotation to each variable as below.

  public class Employee {

    private long id;

    private String name;
    private String gender;
    private String country;
    private String aboutYou;

.... // getter setter of each object


2. Create liquibase file i,e db-changelog.xml file

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns=""
    <changeSet author="waheed" id="123456789-1">
        <createTable tableName="EMPLOYEE">
            <column autoIncrement="true" name="EMPLOYEE_ID" type="BIGINT">
                <constraints nullable="false" primaryKey="true" />
            <column name="NAME" type="VARCHAR(255)" />
            <column name="GENDER" type="VARCHAR(2)" />
            <column name="COUNTRY" type="VARCHAR(255)" />
            <column name="ABOUT_YOU" type="VARCHAR(255)" />

3. Add liquibase bean in your bean :

    <bean id="LiquibaseUpdater" class="liquibase.integration.spring.SpringLiquibase">
        <property name="dataSource" ref="dataSource" />
        <property name="changeLog" value="classpath:db-changelog.xml" />

 and others beans which are required for Spring/Hibernate.  Check bean file

The complete tutorial :

Please feel free to do comment or drop me a mail regarding any suggestion/Feedback.
Email :


Some ANT task

1. How to build  project from another build.

<target name="project2"
            description="Builds project2 project, required depedency">
        <!-- Build project2 first  -->

        <subant target="dist" verbose="yes" inheritall="false">
            <filelist dir="../com.waheed.project2"
                      files="build.xml" />


2. How to read SVN revision and write into some file

<loadfile property="revision" srcFile="./.svn/entries">
            <headfilter skip="3" lines="1"/>
                <format property="date" pattern="dd/MM/yyyy hh:mm:ss" />
            <echo append="true" file="<FILE_NAME>" >revision=${revision}${line.separator}</echo>

3. How to generate Keystore

    <target name="keystore">
        <delete file="workdir/keystore" failonerror="false"/>
        <genkey keystore="./keystore"
                <param name="CN" value="NAME" />
                <param name="OU" value="NAME_OF_ORGANIZATION_UNIT" />
                <param name="O" value="ORGANIZATION_NAME" />
                <param name="C" value="COUNTRY_NAME" />

4. How to get current time

<target name="time">
            <format property="build-time" pattern="yyyy-MM-dd-HH-mm" />

5 . How to create jar with manifest

 <jar jarfile="${dist}/name_of_jar.jar"
                <!-- Who is building this jar? -->
                <attribute name="Built-By" value="${}" />
                <!-- Information about the program itself -->
                <attribute name="Implementation-Vendor"
                           value="Implementation-Vendor" />
                <attribute name="Implementation-Title"
                           value="Implementation-Title" />
                <attribute name="Implementation-Version" value="1.0" />
                <!-- details -->
                <section name="PATH_TO_MAIN_CLASS">
                    <attribute name="Sealed" value="false" />

6. How to compile source

 <!-- Compile the java code from ${src} into ${build} -->

        <javac destdir="bin" debug="true">
            <src path="src" />
                <pathelement location="../dependency/bin" />
                <fileset dir="../lib">
                    <include name="*.jar" />

7. How to compile source with dependency class path

 <path id="class.path">
        <fileset dir="../lib/folder1">
            <include name="*.jar" />
        <fileset dir="../lib/folder2">
             <include name="*.jar" />

 <!-- Compile the java code from ${src} into ${build} -->
        <javac destdir="bin" debug="true">
            <src path="src" />
            <classpath refid="class.path" />

8.  How to build Zip file

    <property name="" value="product1" />
    <property name="product.version" value="1.0" />

<zip basedir="${dist}" destfile="${dist}/${}-${product.version}.zip">

9. How to build tar file

    <property name="" value="product1" />
    <property name="product.version" value="1.0" />

<exec executable="tar" dir="${dist}">
            <arg value="czf" />
            <arg value="${dist}/${}-${product.version}.tgz" />
            <arg value="." />

10 . How to check OS 

<condition property="isWindows">
        <os family="windows" />

    <condition property="isUnix">
        <os family="unix" />

    <target name="" if="isWindows" depends="a">
<!--  Task to be done-- >

    <target name="dist.unix" if="isUnix" depends="b">

<!--  Task to be done-- >

11.  How to set permission to file

 <chmod perm="500">
            <fileset dir="${dist}">
                <include name="**/*.sh" />
                <include name="jsvc" />

12 .How to read property file

Suppose I have following data in my file and want to read it and write it to another file lets say name

     <property file="${dist}/" prefix="version"/>
       <echo file="${dist}/" append="true">revision ${version.REVISION}${line.separator}</echo>

Spring MVC tutorial

Before Starting, I believe you must have basic idea about JAVA, SPRING and Spring MVC.

For Spring MVC :

In this tutorial , I will just tell you what are the basic thing that you need to start MVC.

Step 1 : Create a class 

public class HelloWorld {
    public String helloWorld() {
         return = "Hello World, Spring 3.0!";

1 . The class HelloWorld  has the annotation @Controller and @RequestMapping("/hello"). When Spring scans this class, it will recognize this bean as being a Controller bean for processing requests. 2 .The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /hello in the URL path.

Step 2. Mapping Spring MVC in WEB.xml

The entry point of Spring 3.0 MVC is the DispatcherServlet. DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in web.xml.

<!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->


<!-- This loads the root webapp Spring context -->


Note that I have mapped /rest/* url pattern with example DispatcherServlet. Thus any url with /rest/* pattern will call Spring MVC Front controller.

                  The REST call would be http://ip:port/rest/hello

If your controller class has some dependency which you have defined in your spring context file.Then you have to load it in <context-param>.(red line).
Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. I have created the file named spring-servlet.xml

3 . Spring Configuration file

Create a file spring-servlet.xml in WEB-INF folder and copy following content into it.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:xsi="" xmlns:task=""
    xmlns:tx="" xmlns:context=""
    xmlns:mvc="" xmlns:util=""

    <!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <context:annotation-config />
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />

    <!-- class name of the controller or If you have package use component-scan -->
    <bean class="com.waheed.spring.hibernate.HelloWorld" />


The highlighted red line allow Spring to load the components from class. This will load our HelloWorld class.

Congratulation..!!! You are done here...

Download source code :

Spring MVC

Spring MVC helps in building flexible and loosely coupled web applications. The Model-view-controller design pattern helps in seperating the business logic, presentation logic and navigation logic. Models are responsible for encapsulating the application data. The Views render response to the user with the help of the model object . Controllers are responsible for receiving the request from the user and calling the back-end services.

When a request is sent to the Spring MVC Framework the following sequence of events happen.
  • The DispatcherServlet first receives the request.
  • The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.
  • The Controller process the request by calling the appropriate service methods and returns a ModeAndView object to the DispatcherServlet. The ModeAndView object contains the model data and the view name.
  • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.
  • Now the DispatcherServlet will pass the model object to the View to render the result.
  • The View with the help of the model data will render the result back to the user.

The new Servlet
•DispatcherServlet requests are mapped to @Controller methods
–@RequestMapping annotation used to define mapping rules
–Method parameters used to obtain request input
–Method return values used to generate responses
•Simplest possible @Controller

public class HelloController {
    public @ResponseBody String hello() {
        return “Hello World”;

Mapping Requests
•By path
•By HTTP method
–POST,PUT,DELETE,OPTIONS and TRACE are also supported
•By presence of query parameter
–Negation also supported: params={“foo”,”!bar”}
•By presence of request header
–Negation also supported

For more details : Click Here

For tutorial:

Sending Email Via JavaMail API Example

From last one month, My internet device is missing from my terrace. So, Mostly I use mobile to access my mail but accessing mail via mobile is very irritating thing because of the slow bandwidth. To send one single mail I have to wait till the mailbox get opened.

This is very simple way to send mail without opening your account. :)

This is the example to show you how to use JavaMail API method to send an email via Gmail SMTP server.

You need mail.jar library to run this code.

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

 * @author abdul
public class SendEmail {

    public static void main(String[] args) {
        final String username="YOUR_USER_NAME"; //abdulwaheed18
        final String password="YOUR_PASSWORD";   //*******

        final String to = "SENDER_EMAIL"; //
        final String from = "YOUR_EMAIL"; //

        Properties props = new Properties();
        props.put("", "");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,password);

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(to));
            message.setText("Hi User,\n Surprise Message.\n Regards,\nWaheed");
            System.out.println(“Message sent Successfully");
        } catch (MessagingException e) {
            throw new RuntimeException(e);

Gmail SMTP Detail :

Friday, August 24, 2012

Spring Auto-Wiring Beans with @Autowired annotation

In Spring, you can use @Autowired annotation to auto wire bean on the setter method, constructor or a field.

There are two ways to can achieve it :
1.Using <context:annotation-config />
    Just Add Spring context and <context:annotation-config /> in bean configuration file

<beans xmlns=""
    xmlns:xsi="" xmlns:p=""

    <context:annotation-config />

2. Using AutowiredAnnotationBeanPostProcessor
Add 'AutowiredAnnotationBeanPostProcessor' directly in your bean configuration file.

And in Class, Just add annotation @Autowired above the setter function as seen below , You can do the same on constructor too:
class A {
private B b;

   public void setB(B b) {
      this.b = b;

Error:No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

To solve this problem. You have to do two things:

1. mark the DAO as transactional or function which is doing database call like:

   public class EmployeeDaoImpl  extends DaoImpl implements EmployeeDao{
    public long addEmployee(Employee employee) {
        System.out.println("Employee:"+employee );
        long id = employeeDao.addEmployee(employee);
        System.out.println("Id1: " );
        return id;

2. Enable the annotation driven transcation management in applicationContext.xml (where your beans are defined):

<beans xmlns=""
    xmlns:xsi="" xmlns:p=""
<!-- Main transaction manager for accessing internal DB -->
    <bean id="transactionManager"
        <property name="sessionFactory" ref="sessionFactory" />
    <!-- enable the configuration of transactional behavior based on annotations -->
  <tx:annotation-driven transaction-manager="transactionManager"/>

That's it. Hope it works for other too.

Keyboard Shortcuts That Work in All Web Browsers


Ctrl+1-8 – Switch to the specified tab, counting from the left.
Ctrl+9 – Switch to the last tab.
Ctrl+Tab – Switch to the next tab – in other words, the tab on the right. (Ctrl+Page Up also works, but not in Internet Explorer.)
Ctrl+Shift+Tab – Switch to the previous tab – in other words, the tab on the left. (Ctrl+Page Down also works, but not in Internet Explorer.)
Ctrl+W, Ctrl+F4 – Close the current tab.
Ctrl+Shift+T – Reopen the last closed tab.
Ctrl+T – Open a new tab.
Ctrl+N – Open a new browser window.
Alt+F4 – Close the current window. (Works in all applications.)

Mouse Actions for Tabs

Middle Click a Tab – Close the tab.
Ctrl+Left Click, Middle Click – Open a link in a background tab.
Shift+Left Click – Open a link in a new browser window.
Ctrl+Shift+Left Click – Open a link in a foreground tab.


Alt+Left Arrow, Backspace – Back.
Alt+Right Arrow, Shift+Backspace – Forward.
F5 – Reload.
Ctrl+F5 – Reload and skip the cache, re-downloading the entire website.
Escape – Stop.
Alt+Home – Open homepage.


Ctrl and +, Ctrl+Mousewheel Up – Zoom in.
Ctrl and -, Ctrl+Mousewheel Down — Zoom out.
Ctrl+0 – Default zoom level.
F11 – Full-screen mode.


Space, Page Down – Scroll down a frame.
Shift+Space, Page Up – Scroll up a frame.
Home – Top of page.
End – Bottom of page.
Middle Click – Scroll with the mouse. (Windows only)

Address Bar

Ctrl+L, Alt+D, F6 – Focus the address bar so you can begin typing.
Ctrl+Enter – Prefix www. and append .com to the text in the address bar, and then load the website. For example, type howtogeek into the address bar and press Ctrl+Enter to open
Alt+Enter – Open the location in the address bar in a new tab.


Ctrl+K, Ctrl+E – Focus the browser’s built-in search box or focus the address bar if the browser doesn’t have a dedicated search box. (Ctrl+K doesn’t work in IE, Ctrl+E does.)
Alt+Enter – Perform a search from the search box in a new tab.
Ctrl+F, F3 – Open the in-page search box to search on the current page.
Ctrl+G, F3 – Find the next match of the searched text on the page.
Ctrl+Shift+G, Shift+F3 – Find the previous match of the searched text on the page.

History & Bookmarks

Ctrl+H – Open the browsing history.
Ctrl+J – Open the download history.
Ctrl+D – Bookmark the current website.
Ctrl+Shift+Del – Open the Clear Browsing History window.

Other Functions

Ctrl+P – Print the current page.
Ctrl+S – Save the current page to your computer.
Ctrl+O – Open a file from your computer.
Ctrl+U – Open the current page’s source code. (Not in IE.)
F12 – Open Developer Tools. (Requires Firebug extension for Firefox.)

Tuesday, August 7, 2012

Use mySQl setup from your virtual machine

Have you ever faced a situation where you want to use your MYSQl from your virtual machine. i,e your MYSQL set up is on the windows and your linux is on VM player and you want to use it rather than installing it again on linux box.

If yes, Then here is the solution.

My System configuration where I have tested.
OS : Windows 7
MYSQL: version 5.5 on windows
RHEL 5 on VM player


1 . Open MYSQL workbench 5
2.  Open your MYSQL from server Administrator.
3.  Goto Security -> Users and Privileges
4.  Replace 'localhost' with '%' in limited connectivity to host matching box.

And you are done here..:)

All credit goes to my Manager..Thanx a lot..:)

List all xml files from the JAR.

Do you want to know which all files are in the jar without extracting it.?

This is a small tutorial where I am listing all the xml files.

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

 * List the name of all xml which is in given jars
 * @author abdul
public class ListXmlFiles {
    /* Stores the xml file name*/
    List<String> list = new ArrayList<String>();

    public List<String> getList() {
        return list;

     * @param args
     * @throws IOException
    public static void main(String[] args) throws IOException {
        ListXmlFiles xmlFiles = new ListXmlFiles();
        JarFile jarFile = new JarFile("./lib/dummyJar.jar");
        Enumeration<JarEntry> e = jarFile.entries();
        while (e.hasMoreElements()) {
        System.out.println("List:" + xmlFiles.getList());

    private void process(Object obj) {
        JarEntry entry = (JarEntry)obj;
        String name = entry.getName();
        if(name.endsWith(".xml")) {

If you want to know all the files name inside,Just removed the if-else filter, It will add all  the filename into the list.
private void process(Object obj) {
        JarEntry entry = (JarEntry)obj;
        String name = entry.getName();


Wednesday, August 1, 2012

Windows Command Prompt Tricks You Probably Don’t Know

1. Send a Command’s Output to the Clipboard
Note: This will work for any command.

Without doing copy and paste the output, We can send the output directly to the clipboard.
ipconfig | clip

2. Open Command Prompt From a Folder

Do you want to open the command promp within a folder from explorer ? All you have to do is hold shift while right  clicking on a folder and the option will appear in the context menu.

3. Command History
We can view our past command  i,e using doskey command.
doskey /history

4. Drag and Drop Files to Change the Current Path

Another neat trick if you are not a fan of opening a command prompt from the context menu is the ability to drag and drop folders onto the prompt and have it automatically enter the path of the folder.

5. Run Multiple Commands In One Go
Want to run multiple command at once?  You can do this by linking them with double ampersands.
ipconfig && netstat

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...