Friday, May 24, 2013

What is Mercurial ?

Mercurial is a fast, lightweight Source Control Management system designed for efficient handling of very large distributed projects. It is mainly implemented using the Python programming language. It is supported on Windows and Unix-like systems, such as Mac OS X and Linux.

All of Mercurial's operations are invoked as arguments to its driver program hg, a reference to the chemical symbol of the element mercury.

Mercurial's major design goals include high performance and scalability, decentralized, fully distributed collaborative development, robust handling of both plain text and binary files, and advanced branching and merging capabilities, while remaining conceptually simple. 

How you can benefit from Mercurial

  1. It is fast and powerful, It efficiently handles projects of any size and kind. Every clone contains the whole project history, so most actions are local, fast and convenient.
  2. Mercurial supports a multitude of workflows and you can easily enhance its functionality with extensions.
  3. It is easy to learn and use
  4. It is lightweight.
  5. It scales excellently.

How to read certificates using CertificateFactory class

In my previous blog, I have explained how can you create self signed certificate using bouncy castle API and how to import it into keystore.

This tutorial will explain how to read existing certificate file using class.


 * Reads the certificate and import into Java keystore.
 * @author abdul
public class ReadCertificateFile {

     * @param args
     * @throws Exception
    public static void main(String[] args) throws Exception {

        ReadCertificateFile readCertificateFile = new ReadCertificateFile();

        // Path of the certificate file
        FileInputStream fis = new FileInputStream("YOUR_CERTIFICATE.cert");

         * Returns a CertificateFactory object of the specified certificate
         * type.
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
         * Read the certificate from the specified input stream, and returns it
         * as a Certificate object. It can read certificate in both binary (DER
         * encoded) and printable (RFC standard) formats.
         */ cert = cf.generateCertificate(fis);

        System.out.println("Certificate Details: ");
        /*Returns the type of this certificate factory*/
        System.out.println("Type = " + cert.getType());
        System.out.println("toString = " + cert.toString());

        PublicKey key = cert.getPublicKey();
        System.out.println("PublicKey Object Info: ");
        System.out.println("Algorithm = " + key.getAlgorithm());
        System.out.println("Format = " + key.getFormat());
        System.out.println("toString = " + key.toString());

        // save/import certificate into keystore

    private void saveCert(Certificate cert) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        // import your certificate into keystore
        keyStore.setCertificateEntry("YOUR_ALIAS_NAME", cert);

        // name of keystore "
        File file = new File(".", "YOUR_KEYSTORE_NAME"); FileOutputStream(file),


Tuesday, April 9, 2013

Eclipse - Tips & Tricks

This article is for those who use Eclipse. Keyboards shortcuts are very important for comfortable and quick editing. Here are the list of most important shortcuts in Eclipse :
For a full list of shortcuts, you can also check by pressing Ctrl+Shift+L.
  1. Ctrl +3 Focus into the Quick Access search box which allows you to execute any Eclipse command.
  2. Ctrl+SHIFT+T Search dialog for Java Type, Start typing the name and the list gets smaller. Try typing the capital letters of the class only (e.g. type "NPE" to find "NullPointerException")
  3. Ctrl+SHIFT+R Search dialog for resources, e.g. Xml files, text files, or files of any other type.
  4. Ctrl+E Open Editor Drop down, Presents a popup window listing currently opened files.
  5. Ctrl+O Quick Outline, Show all methods of the current class, Press Ctrl+O a second time to include inherited methods.
  6. Ctrl+SHIFT+space Context Information
  7. Ctrl+Shift+O Organize Imports, Adjusts the imports statements in the current Java source file
  8. F3 Open Declaration ,Navigate to the declaration of the selected variable . This works much like a browser hyperlink.
  9. Ctrl + hover to methods,variables Ask for Open Declaration, Implementation, Super Implementation or return types.
  10. Alt+Left/Right Backward/Forward History, Works like a browser's back/forward button.
  11. Ctrl + L Go to a specific line number.
  12. F4 Open Type Hierarachy
  13. Ctrl+Alt+H Open Call Hierarchy. Show where a method is called from.
  14. Alt + SHIFT + R Use this to rename type, method, or field. All existing references will be refactored as well.
  15. Alt+Shift+M Extract method, Use this to extract a new method from existing code. The parameter list and return type will be automatically created.
  16. Ctrl+Shift+P Go to the matching bracket.
  17. SHIFT+ENTER /Ctrl+SHIFT+ENTER Insert a line below or above the current line.
  18. Ctrl + /, Ctrl+7, Ctrl +\ Add or Remove block comment.
  19. Ctrl +F6 Switch among the editor.
  20. Ctrl + F7 Switch among open views.
  21. Ctrl + F8 Switch among perspectives.
  22. Alt +/ It does the word completion based on the set of words already present in the current file.
  23. Ctrl + I It correct the indention for block of Java code or an entire class.
  24. Ctrl + . or Ctrl + , It will navigate to next or previous error.
  25. Ctrl+F11, F11, Run or Debug the Application.
  26. F5,F6, F7, F8 Step into function, Next Step (line by line) , Step out , Skip to next breakpoint.
  27. Ctrl +1 Give quick fix code.
  28. Ctrl + D Delete the current line.
  29. Ctrl + SHIFT + G Search for current cursor positioned word reference in workspace.
  30. Ctrl +Page Up/Page Down Switch to next editor / switch to previous editor
  31. Alt + - Open Editor Window Option menu.
  32. Ctrl +F10, then n It will show or hide the line numbers
  33. Ctrl + q It will jump to last location edited
  34. Ctrl + SHIFT + f It will format all code in Editor using code formatter.
  35. Alt + SHIFT + J or /** and then press Enter Add javadoc Element Comment ( adds '/** ... */')
  36. Alt + SHIFT + V Move selected element to other class or file (With complete method or class selected)
  37. Ctrl + DEL Delete next element
  38. Ctrl + BACKSPACE Delete previous element. 
    Note : I have not added basic shortcut like Ctrl+S to save the file.
    Feel free to comment If you find something is incorrect or update me more :)

Wednesday, April 3, 2013

Hibernate Configuration

To inform Hibernate from where to find mapping information of Java classes to database tables or configuration setting related to database, All such information is usually supplied by Hibernate Configuration Object. It is managed by an instance of org.hibernate.cfg.Configuration. An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application’s Java types to an SQL database. The mappings are compiled from various XML mapping files or from Java 5 Annotations.

Hibernate provides following types of configurations
  1. hibernate.cfg.xml – A standard XML file which contains hibernate configuration and which resides in root of application’s CLASSPATH 
  2. – A Java compliant property file which holds key value pair for different hibernate configuration strings. 
  3. Programmatic configuration – This is the manual approach. The configuration can be defined in Java class. 

1. hibernate.cfg.xml : The hibernate.cfg.xml file is a standard XML file which contains all the configuration parameters like database connection, class mappings etc. This file needs to be placed root of CLASSPATH of application.

Below is the sample hibernate.cfg.xml file :
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration> <session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/SampleApp</property>
<property name="connection.username">root</property>
<property name="connection.password">root123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<!-- Drop and re-create the database schema on startup -->
<property name="">update</property>
<!-- Mapping files POJO -->
<mapping class="com.hibernate.pojo.Host"/>

2. file :
This is the easiest way to get started with Hibernate. Create a file and place it in root of your applications CLASSPATH.
Below is the sample file:

hibernate.dialect = org.hibernate.dialect.MySQLDialect
 3. Programmatic Configuration

We can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:
Configuration cfg = new Configuration()

An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:
Configuration cfg = new Configuration()

A org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:
 Configuration cfg = new Configuration()
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.connection.datasource", "jdbc:mysql://localhost/SampleApp")
.setProperty("hibernate.order_updates", "true");

Refer here for more details : 

Tuesday, April 2, 2013

What is Hibernate ?

What is Hibernate ?
  1. Hibernate is an  open source java based library used to work with relational databases. 
  2. The term Object/Relational Mapping refers to the programming technique for converting data between relational databases and object oriented programming languages such as Java, C# etc.
  3. It is a very powerful ORM solution build on top of JDBC API.
  4. It was initiated by Gavin King in 2001.
  5. It is a persistence framework which is used to store and retrieve data from database. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application
  6. Hibernate  makes use of persistent objects called POJOs (Plain Old Java Objects).
  7. Hibernate maps Java classes(POJO) to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks.
  8. These objects works as a data carrier called DTO (Data Transfer Object). They are used to carry data between different layers.

Hibernate Position

Advantages of Hibernate :

  1. Hibernate takes care of mapping Java classes to database tables using annotation or XML files. You don't need to write any code to map it.
  2.  It provides simple APIs for storing and fetching Java objects directly to and from the database.
  3. If there is change in database or in any table then the only need to change XML file properties. and Java classes which are related to the table.
  4. No need of SQL knowledge, you just need to work on familiar Java data types.
  5. It does not require an application server to operate.
  6.  Reduce database access complexity by easy fetching techniques.
  7. It has easy and simple query for data access.
  8. It is layers architecture and you can use the components as per your application need.
  9. Hibernate is database independent and you can use any database of your choice. It supports all major RDBMS like HSQL Database Engine, DB2/NT, MYSQL, PostgreSQL, FrontBase, Oracle, Microsoft SQL Server, Database,  Sybase SQL Server,  Informix Dynamic Server.
  10. It also provide caching framework that works with Hibernate. You can use any one in your application to improve the performance of your application.

 Hibernate Architecture :

The figure given below represents the architecture of Hibernate :


Hibernate framework uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.

Below are some definitions of the object depicts in above diagram :
  • Persistent Object : These are short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one Session. Once the Session is closed, they will be detached and free to be used in any application layer (for example, directly as data transfer objects to and from presentation).
  • Transient Object : Instances of persistent classes those are not currently associated with a Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed Session.
  • Configuration (org.hibernate.cfg.Configuration ): The configuration of Hibernate is handled by the instance of org.hibernate.cfg.Configuration . It is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.
    Configuration cfg = new Configuration()
  • SessionFactory (org.hibernate.SessionFactory ) : Session factory is a thread safe, immutable cache of compiled mappings for a single database. Configuration object is used to create a SessionFactory object. Only single instance of session factory is required for an application, so it is based on a singleton pattern. Typically SessionFactory is require for per database using a separate configuration file. So in case If you are using multiple databases then you would have to create multiple SessionFactory objects. The SessionFactory is heavyweight object so usually it is loaded at the start of the application.
    SessionFactory sessions = cfg.buildSessionFactory();
  • Session (org.hibernate.Session): The session object provides an interface between the application and data stored in the database. It is a lightweight object and it wraps JDBC connection. It is factory of Transaction, Query and Criteria. It holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.
    Session session = sessions.openSession(); 
  • Transaction (org.hibernate.Transaction): It is a single-threaded, short-lived object used by the application to 
    specify atomic units of work. It is Optional. It provides methods for transaction management.  
  • Query :  Query object use Hibernate Query Language(HQL) or SQL to fetch data from the database. 
  • Criteria : Criteria object are used to create and execute object oriented criteria queries to retrieve objects. 

Thursday, March 7, 2013

What is RPM and How to build your RPM?


RPM (RPM Package Manager) is a popular utility for installing software on Unix-like systems, particularly Red Hat Linux. The name RPM variously refers to the .rpm file format.
It is an open packaging system available for anyone to use. It allows users to take source code for new software and package it into source and binary form such that binaries can be easily installed and tracked and source can be rebuilt easily. It also maintains a database of all packages and their files that can be used for verifying packages and querying for information about files and/or packages.

Design Goals

RPM provides the capability to install an entire application with a single command, to track the files it put on the system, and to remove those files by using another single command.
  • Make it easy to get packages on and off the system.
  • Make it easy to verify a package was installed correctly.
  • Make it easy for the package builder.
  • Make it start with original source code.
  • Make it work on different computer architecture


RPM packages are provided as compressed archive files that contain one or more files, as well as instructions specifying installation information about those files, including the ownerships and permissions that should be applied to each file during installation.
The instructions can also contain scripts to be run after installation or before uninstallation. These package files are extremely convenient, they provide a single file that can be easily transferred between machines for installation rather than having to transfer each file to be installed. To help in installation and management, all package files are labeled with highly identifiable names.
Package files have four-part names, which typically look something like:
The four parts of each name are separated from each other by dashes or periods. The structure of the package file name is
name-version-release.architecture.rpm where
name - > name of an application or package that the archive installs on the system version → version number of the software that is contained in the package file release → release of that version of the software the package file contains architecture → architecture identifies the system types for which the package file is appropriate

Building RPMs

When building RPMs, go through the following steps:
  • Set up the directory structure.
  • Place the sources in the right directory.
  • Create a spec file that tells the rpmbuild command what to do.
  • Build the source and binary RPMs.

The following sections provide details for these steps.

Setting up the directory structure

RPM requires a set of directories (as listed in below Table)in which to perform the build. While the directories locations and names can be changed, unless there's a reason to do so, it's best to use the default layout. Note that if you've installed RPM, the build directories are most likely in place already.

RPM directories

The directory in which the sources are unpacked, and the software is built.
Contains the binary package files created by the build process.
Contains the original sources, patches, and icon files.
Contains the spec files used to control the build process.
Contains the source package files created by the build process.

The RPMS directory usually has a number of architecture-specific subdirectories, such as the following (on an Intel architecture system):
athlon, i386, i486, i586, i686, noarch.

By default, Red Hat Linux systems expect RPMs to be built in the /usr/src/redhat directory.

Do not build RPMs while logged in as root as root can alter any file on the system. Mistakes in building packages can have serious consequences if you are logged in as root.

To build RPMs, At a minimum you need only two things:
  • source code in the SOURCES directory
  • spec file in the SPECS directory

 Placing your sources into the directory structure

The first thing we need to do in order to build a package is to place all the source file directly in the /usr/src/redhat/SOURCES directory. It will be easier if you create a tarball of the source you want to build and then place in the SOURCES directory.
The convention for these tarball files is package-version.tar.gz. For example:

Creating the spec file

The spec file is nothing more than a text file with a special syntax and having extension .spec. It defines all the actions the rpmbuild command should take to build your application, as well as all the actions necessary for the rpm command to install and remove the application.
The normal naming convention is to name the file with the package name and a .spec filename extension.
The following sections describe these spec file sections and the necessary syntax in each section.

Introduction section

The introduction section contains information about the package, the type of information.
Example :
  • Summary : This is a one line description of the package.
  • Name: This must be the name string from the rpm filename you plan to use.
  • Version : This must be the version string from the rpm filename you plan to use.
  • Release : This is the release number for a package of the same version.
  • Copyright : This line tells how a package is copyrighted.
  • Group : This is a group that the package belongs to in a higher level package tool or the Red Hat installer.
  • Buildroot : This line allows you to specify a directory as the "root" for building and installing the new package.
  • %description: This is a multi−line field that should be used to give a comprehensive description of the package.


prep section

This is the second section in the spec file. It is short for prepare, defines the commands necessary to prepare for the build. If you are starting with a compressed tar archive (a tarball) of the sources, the prep section needs to extract the sources. The prep section starts with a %prep statement.
For example:
%setup -q

build section

The build section contains the commands to build the software. Any sh commands can go here. It starts with a %build statement.
./configure CXXFLAGS=-O3 --prefix=$RPM_BUILD_ROOT/usr

Install section

The install section holds the commands necessary to install the newly built application or library. In most cases, your install section should clean out the Buildroot directory and run the make install command. The install section starts with an %install statement.
make install

Clean section

The clean section cleans up the files that the commands in the other sections create, It starts with a %clean statement. %clean

Files section The files section lists the files to go into the binary RPM, along with the defined file attributes. It starts with a %files statement


While working on one of my project, Once there was a requirement where I have to deploy the tomcat, place the war into the tomcat at the appropriate directory and also start the tomcat on the client machine using rpm.
To achieve above task, I went through the following steps;
  1. Created RPM build directory structure.
  2. Placed our tar file into SOURCE directory.
  3. Spec file into SPEC directory
I have uploaded the rpm structure on the with spec file and tar file. You can refer it for better understanding.
Note : For security purpose, while creating tar I have removed the war file. So to make it working,
Download the tar file from SOURCES, untar it and then add your war file with name “mxlcloudsso.war” and tar it again and place into SOURCES directory.

To build the rpm :
rpmbuild -ba $redhat/SPECS/mxl_installer.spec
The rpm file will get created under $redhat/RPMS/noarch directory structure.

To install the package:
rpm -i mfe-cloudsso-sl-installer-1.0.0-1.noarch.rpm
It will install the tomcat on your machine, deploy your war file in tomcat ,start the tomcat.

To remove the package:
rpm -e mfe-cloudsso-sl-installer
Note : To remove the rpm, We just need the package name.

Useful command :

To build RPMs with the rpmbuild command, use the following basic syntax:
rpmbuild -bBuildStage spec_file
The -b option tells rpmbuild to build an RPM. The extra BuildStage option is a special code that tells the rpmbuild command

Build all, both a binary and source RPM
Build a binary RPM
Build (compile) the program but do not make the full RPM, stopping just after the %build section
Prepare for building a binary RPM, and stop just after the %prep section.
Create a binary RPM and stop just after the %install section
Check the listing of files for the RPM and generate errors if
the buildroot is missing any of the files to be installed
Build a source RPM only


Thursday, February 21, 2013

How to integrate Web Application with Salesforce via Oauth

This tutorial shows you the basic of Oauth. We have created a Java Web Application that authenticates the user to salesforce via Oauth 2.0 and then we have performed few CRUD operation via the new API.


  • SSL enabled Tomcat Server as we have deployed our Web Application on tomcat. Click here for instruction on How to enable SSL on apache Tomcat 7.0
  • Salesforce Remote Access Application. Click here for instruction on How to create Remote Access Application on Salesforce?
  • Download the application from here and change the name to Services.

Run the Project:

Check out the project from the above URL, import into the eclipse and Run as a Server.

Navigate your browser to https://localhost:8443/Services. You will see the following page:

Click on the link and it will take you the salesforce page for Authentication :

Once you are login into salesforce, It will ask you to allow the Oauth_Apps to access your data:

After clicking on “Approve”button, You will see the below page with few CRUD operation output :

Note : You have provided your credentials to the website not to the requesting application. This is Oauth in Action. Once you are authorize accessing to your data, The control will return back to your application with generated token using which you can interact with the salesforce data.

Code Description:


In the Servlet initParams, We have defined the clinetSecret, clientId and the redirectUri, You can change it as per your remote application.
@WebInitParam(name = "clientId", value = "3MVG9Y6d_Btp4xp5hntckvnA5QVKsxlc4RUx9CbJndYCQQS4oO7jHAVspS0WdeCXBJlMXO1e9hwQSCjCBB71H"),
// clientSecret is 'Consumer Secret' in the Remote Access UI
@WebInitParam(name = "clientSecret", value = "4518803906379506686"),
// This must be identical to 'Callback URL' in the Remote Access UI
@WebInitParam(name = "redirectUri", value = "https://localhost:8443/Services/OAuthServlet/callback"),
@WebInitParam(name = "environment", value = ""), })

Here our Java Web Application act as a third-party website or termed as “client” which operate on behalf of a user. It first sends the request to which authenticates the user, obtain the user's authorization(i,e Approve/Deny page) and issues an access token which client can use while interacting with the resource server I,e salesforce instance.

When the Servlet initializes, it constructs authUrl, to which it redirects the user to authenticate and authorize access to data:
try {
authUrl = environment+ "/services/oauth2/authorize?response_type=code&client_id="
+ clientId + "&redirect_uri="+ URLEncoder.encode(redirectUri, "UTF-8");}

The authUrl contains the configuartion which identifies the salesforce remote application.It also creates the tokenUrl which it uses to obtain the access token.
The response.sendRedirect(authUrl) authenticates the users, obtains authorization for the web app to access the user’s data(first time) and then redirects the user back to redirectUri: https://localhost:8443/Services/OAuthServlet/callback

When control returns to the Servlet, we use the returned data to build a POST request and send it to tokenUrl and we get the response(access token and instance Url) from authorization server in JSON format.

As we have access token, Here we have just perform few CRUD operation i,e showAccounts, createAccount,deleteAccount and updateAccounts. In every HttpClient calls, we set a request header, Authorization to the value OAuth, followed by a space, and the access token. It is essential to do this for every interaction with the REST API; failure to do so results in a 401 ‘Unauthorized’ error when submitting the request.


The application demonstrates how to authenticate and retrieve an access token using Oauth 2.0 and how we can do perform CURD operation with the help of access token.


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