Friday, January 30, 2015

mastek tekathon

git init
git add .
git commit -m "first commit"
git remote add origin<team-leader-name>/<RepositoryName>.git

git push -u origin master

If you want to revert changes made to your working copy, do this:
git checkout .

If you want to revert changes made to the index (i.e., that you have added), do this:
git reset

If you want to revert a change that you have committed, do this:
git revert ...

example Name&donorMobile=9876543210&requestType=Platelets&requiredByWhen=2015-01-09%2012:01:01&pincodeForDonation=400606&donationRequestId=10483838

curl -i -X POST -H "Content-Type: application/json" -d @req.json
example Name&donorMobile=9876543210&requestType=Platelets&requiredByWhen=2015-01-09%2012:01:01&pincodeForDonation=400606&donationRequestId=10483838

Once successful, an entry pertaining to your received Http Request can be seen in our simulator application at URL



===== cmds for trystack install=======

sudo apt-get update
sudo apt-get install tomcat7
sudo service tomcat7 status
winscp copy from

sudo cp ~/*.war /var/lib/tomcat7/webapps/

sudo chmod 777 /var/lib/tomcat7

sudo service tomcat7 restart
tail -100f /var/lib/tomcat7/logs/catalina.out


Tuesday, September 23, 2014

ORM Tips

First Off, ORM is tougher than writing declarative SQL, make sure you have experienced developers, who are willing to "really understand" the data model, rather than developers who want to just "code-break-fix"

When you look at any persistent entity attributes think of them as following 3 categories:

  • "flat" attributes, that are stored in the table that the parent entity is mapped to
  • "referred" attributes, these merely refer to other entities, whose life cycle is independent of parent entity. Typically entities shown in dropdowns, lookups, master data entities etc
  • "cascade" attributes, refer to entities that may have CRUD cascades w r t the parent entity

The more the number of cascade attributes, the more the complexity in persisting the current entity
(this can be used for estimations)

Inserts are easy, updates are tricky. Allocate enough time for testing entity update, with different combinations of "cascade" attributes. (null, existing, new entities)

Complex cross entity (readonly) queries, need not go through the ORM. (caution: there are risks of stale/out-of-sync data, if not done properly)

The service code is not tested, till all lazy initialization has been exercised. Developers release the code as working too soon, but only when the services layer is invoked from the controllers, where-in the json serializers try to access the entire depth of the object graph, the code starts throwing data access exceptions. Working with shallow hibernate proxies often lulls us into false sense of security temporarily.

To translate entity objects into VO / TO objects and back, use object oriented code, rather than procedural, so let each VO / TO take care of its own mapping to corresponding entity object.

To test REST services, you can use simple HTML with jquery, but better is JUnit tests which use Spring's RestTemplate as REST Client and make REST service calls. This kind of test is very authentic (exercises controllers realistically)
and more importantly...the test code is strongly typed, so in case your VO changes, the compiler will break your test and catch your attention, this makes refactoring smooth.

Monday, September 8, 2014

Database multi-tenancy using Hibernate 4

With many business applications being written, with intent to be deployed on cloud, there is increasingly a need to design multi-tenancy into your application.

For persistence layer multi-tenant design offers a few options:

  1. separate database per tenant
  2. separate schema, same database per tenant
  3. same schema, same database for all tenant with discriminator column for tenant rows in same table

In this article, I am going to talk more about implementing the options 1 and 2 using the support in hibernate 4, for multi-tenancy.

Also for the database connections, we have choice of having a common database connection pool, from which connections are allocated to each tenant request, or separate connection pools for each tenant.
For the common connection pool approach, each connection before being used for data access, needs to be "primed" for usage against a tenant database or schema, using statements like "use <tenant_schema>" or "use <tenant_database>"

Multi-tenancy in Hibernate

For the "separate connection pool per tenant approach"

First we need to implement a custom connection provider as follows

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;

public class ConnectionProviderImpl implements ConnectionProvider {
 private final BasicDataSource basicDataSource = new BasicDataSource();
 public ConnectionProviderImpl(String database){
                //this should be read from properties file

 public boolean isUnwrappableAs(Class arg0) {
  return false;

 public  T unwrap(Class arg0) {
  return null;

 public void closeConnection(Connection arg0) throws SQLException {

 public Connection getConnection() throws SQLException {
  return basicDataSource.getConnection();

 public boolean supportsAggressiveRelease() {
  return false;


Next we need to implement AbstractMultiTenantConnectionProvider of hibernate, as follows
Here I am maintaining a map of database identifiers against, connection providers.
When hibernate invokes the selectConnectionProvider( ) method with the tenant identifier, we use the tenant identifier to return the "appropriate" connection provider from the map.
It is necessary to implement a method like getAnyConnectionProvider( ), which should return, a sensible - default connection provider.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;

public class MultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
 private HashMap connProviderMap = new HashMap();
 public MultiTenantConnectionProvider(){

  List providerNames = new ArrayList();
  //need to get above from properties file
    for (String providerName : providerNames) {
       connProviderMap.put(providerName, new ConnectionProviderImpl(providerName));
 protected ConnectionProvider getAnyConnectionProvider() {
  System.out.println("inside MultiTenantConnectionProvider::getAnyConnectionProvider");
  return connProviderMap.get("default_db");

 protected ConnectionProvider selectConnectionProvider(String tenantId) {
  ConnectionProvider connectionProvider = connProviderMap.get(tenantId);
  if(connectionProvider == null)
   connectionProvider =  new ConnectionProviderImpl("default_db");
  return connectionProvider;


For common connection pool for all tenants.

We need to implement MultiTenantConnectionProvider of hibernate, as follows
Since we are using the same connection pool, in getConnection(), we need to prime the connection using a SQL statement like 'use <database>', so that the connection's further use will be in database as per tenant_id.
Also in releaseConnection( ), we have a 'use <default_db>' as a fallback.

import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;

public class MultiTenantConnectionProviderWithSingleDBPool implements
  MultiTenantConnectionProvider {
 private final ConnectionProvider connectionProvider = new ConnectionProviderImpl(CurrentTenantIdentifierResolver.DEFAULT_TENANT_ID); 

 public boolean isUnwrappableAs(Class arg0) {
  return false;

 public  T unwrap(Class arg0) {
  return null;

 public Connection getAnyConnection() throws SQLException {
  System.out.println("inside MultiTenantConnectionProvider::getAnyConnection");
  return connectionProvider.getConnection();

 public void releaseAnyConnection(Connection connection) throws SQLException {
  connectionProvider.closeConnection( connection );

 public Connection getConnection(String tenantIdentifier) throws SQLException {
  final Connection connection = getAnyConnection();
  try {
     connection.createStatement().execute( "USE " + tenantIdentifier );
  catch ( SQLException e ) {
     throw new HibernateException(
       "MultiTenantConnectionProvider::Could not alter JDBC connection to specified schema [" +tenantIdentifier + "]",e);
  return connection;

 public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
  try {
   connection.createStatement().execute( "USE default_db" );
  catch ( SQLException e ) {
     throw new HibernateException(
     "Could not alter JDBC connection to specified schema [" +
   tenantIdentifier + "]",e);
  connectionProvider.closeConnection( connection );

 public boolean supportsAggressiveRelease() {
  return false;


refer hibernate docs

Now, to persuade hibernate to use tenant identifier before any database access, we can
  1. manually set the tenant identifier on hibernate session factory
  2. we can implement hibernate tenant identifier resolver

Manually set the tenant identifier on hibernate session factory
This can be done, in a web application in any suitable interceptor where hibernate session is available
Session session = sessionFactory.withOptions()
        .tenantIdentifier( yourTenantIdentifier )

Hibernate tenant identifier resolver can be implemented as follows.
Here I am using a ThreadLocal to get the tenant identifier. The threadlocal itself can be set early on in the http request thread in say, a servlet filter.

import org.hibernate.context.spi.CurrentTenantIdentifierResolver;

public class CurrentTenantIdentifierResolver implements
  CurrentTenantIdentifierResolver {
 public static ThreadLocal _tenantIdentifier = new ThreadLocal();
 public static String DEFAULT_TENANT_ID = "default_db";

 public String resolveCurrentTenantIdentifier() {
  System.out.println("from inside resolveCurrentTenantIdentifier....");
  String tenantId = _tenantIdentifier.get();
  if(tenantId == null)
   tenantId = DEFAULT_TENANT_ID;
  System.out.println("threadlocal tenant id ="+tenantId);
  return tenantId;

 public boolean validateExistingCurrentSessions() {
  return true;


Finally, the hibernate configuration for specifying that we are using hibernate mutli-tenancy, in hibernate.cfg.xml

That's it people,
Happy multi-tenanting :-)


Thursday, April 17, 2014

Using free openshift java PAAS, to run a web application on an online version of tomcat

Many times you have a war file, that you would like to deploy such that the application becomes available online.A classical use case is using a REST service as stub for your mobile app or thin client web app.

Openshift online PAAS is an easy solution for such free hotsitng of a java web application

Create a free account at open shift online 
Download their rhc command line tool
Fire following command to create 1 of 3 free apps, where name of new hosted web app is for example say, restgrails

rhc create-app restgrails tomcat-7

Go to the open shift web console and note down the ssh url of the git repository
setup ssh keys for the open shift git repo using command

rhc setup

If required, place the keys generated in <user-dir>\.ssh into <git-install-dir>\.ssh

fire following command on your local machine

git clone <git_url> restgrails

on your local machine the above git command will create a new directory called restgrails and checkout default web app from openshift git repo to your local machine

cd restgrails

Fire following commands to get rid of the default web app's src and pom.xml, since we will deploy a ready made war file onto the openshift PAAS

git rm -rf src/ pom.xml

git commit -am "deleted default source code"

Now prepare the ready made war file for deploying onto open shift

copy war file to restgrails/webapps/
rename war file to ROOT.war  --this is important if you want to map your webapp to the openshift online app URL

git add .
git commit -am "added new root.war to webapps"
git push --force

Above git push command, will trigger a deploy of the war file into the remote tomcat on open shift and soon the web app will become available online as say

you can tail the tomcat server logs with the following command
rhc tail restgrails

For databases, openshift online does support databases like mongodb, mysql and postgresql, so if your app uses hibernate, it can easily be configured to use online database like say mysql or postgresql, while running it online