Wednesday, September 24, 2014

Basic understanding of Connection Pool With Example

Connection Pool



Baciscally Connection Pool usage is to Avoid making and destroying the Connection object repeatedly.
Connection Pool is like keeping a door of home open instead of locking it and opening it all time whenever need to go Inside.

Connection Pool means Set of Connections which are cashed and shared.
So whenever a resource need a database communication then it will ask the connection pool for the connection and if free connection is available then it will get connection from the pool and will use it.  Once it done with the need of connection it will give the connection back to the Connection Pool, so it will be available for next time.

So here it will not require to create the connection object all the time whenever required. 
and creating and destroying connection object hits the performance of Application

Download following jar files

commons-dbcp.jar
commons-pool.jar
mysql-connector-java-version.n.n.n.jar

Example Code

package pool;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;

public class DataSourceEngine {

    private static DataSourceEngine     datasource;
    private BasicDataSource basicDataSource;

    private DataSource() throws IOException, SQLException, PropertyVetoException {
        basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("root");
        basicDataSource.setUrl("jdbc:mysql://localhost/SampleData");
       
        /* Below configurations are Optional. */
        basicDataSource.setMinIdle(1);
        basicDataSource.setMaxIdle(10);
        basicDataSource.setMaxOpenPreparedStatements(100);

    }

    public static DataSourceEngine getInstance() throws IOException, SQLException, PropertyVetoException {
        if (datasource == null) {
            datasource = new DataSourceEngine();
            return datasource;
        } else {
            return datasource;
        }
    }

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

}

===========
package pool;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DataSourceMain {

public static void main(String[] bag) {

Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        
        try {
            connection = DataSourceEngine.getInstance().getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SELECT * FROM STUDENT");
             while (resultSet.next()) {
                 System.out.println("ROLL_NUMBER: " + resultSet.getString("ROLL_NUMBER"));
                 System.out.println("NAME: " + resultSet.getString("NAME"));
             }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
e.printStackTrace();
} catch (PropertyVetoException e) {
e.printStackTrace();
} finally {
            if (resultSet != null) {
            try {
            resultSet.close(); 
            }  catch (SQLException e) { }
            }
            if (statement != null) {
            try { 
            statement.close(); 
            } catch (SQLException e) { }
            }
            if (connection != null) {
            try { 
            connection.close(); 
            } catch (SQLException e) {}
            }
        }

}
}

Keep Visiting :)

Tuesday, September 23, 2014

Java code to Create log file and write logs in it

It s very simple code just set Environment Variable and run the program. It will create the log file and will write the outputs into the EngineLogs.log file




package filer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/*
 * Author : Raj Kirpalsinh
 * */
class Base{

private String path = null;

Base(String path){
this.path = path;
}

public boolean setStandardLogOutput() {

if(path == null) {
System.out.println("Sorry !! Path is null");
return false;
}

File stdLogDirPath = new File(path);

if(stdLogDirPath.exists()==false) {
System.out.println("Directory path "+path+ " does not exist. Creating the directory path.");
if(stdLogDirPath.mkdirs() == false) {
System.out.println("Could not create directory path : "+path);
return false;
}else {
System.out.println("Directory path created successfully : "+path);
}
}

if(stdLogDirPath.isDirectory()==false) {
System.out.println(path +" is not a directory");
return false;
}

File logFile = new File(path, "EngineLogs.log");
if(logFile.exists()==false) {
System.out.println("Log file "+logFile.getName()+ " does not exist");
boolean isFileCreated = false;
try {
isFileCreated = logFile.createNewFile();
if(isFileCreated == true) {
System.out.println("Log file "+logFile.getName()+ " created at path : "+path);
FileOutputStream fs = new FileOutputStream(logFile,true);
PrintStream ps = new PrintStream(fs); 
System.setOut(ps);
System.setErr(ps);
}else {
System.out.println("Error while creating file  ");
}
} catch (IOException e) {
System.out.println("Exception while creating the logfile. Reason: "+e.getMessage());
e.printStackTrace();
return false;
}

return true;
}
}

public class Engine extends Base {

Engine(String path){
super(path);
}

public static void main(String[] args) {
String ENGINE_HOME = System.getenv("ENGINE_HOME"); 
System.out.println(ENGINE_HOME);
Engine engine = new Engine(ENGINE_HOME);
boolean flag = engine.setStandardLogOutput();
if(flag == false) {
System.out.println("Error while setting the Eninge stardard logs output in a EngineLogs.log file");
}
System.out.println("--Begin--");
System.out.println("--Finish--");
}

}

Keep visiting :) 

How to Avoid NullPointerException ?

There are various ways to Avoid NullPointerException

1) if( null != objName ){ }


2) instead of .toString() method always use String.valueOf(objName);


3) Instead of of returning null collections object from the methods

    try to return empty objects
return Collections.EMPTY_SET;
return Collections.EMPTY_MAP;
return Collections.EMPTY_LIST;

4) while comparing two objects using the obj1.equals(obj2) method

   keep in mind that obj1 should be known and object2 should be unknown.
   means in the argument of .equals() method always pass the unknown object

  These are four simple basic ways. there are many more.


Keep Visiting :) 

  

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...