Thursday, April 25, 2013

Get java sql connection from hibernate session

Get java sql connection from org hibernate Session

Hi we can get java sql connection object from org hibernate session object.
As i write a function getJavaSqlConnectionFromHibernateSession, which take session as an argument and return connection object.

private Connection getJavaSqlConnectionFromHibernateSession(Session session){
    SessionFactoryImplementor sessionFactoryImplementor = null;
    ConnectionProvider connectionProvider = null;
    java.sql.Connection connection = null ;
    try {
        sessionFactoryImplementor = (SessionFactoryImplementor)session.getSessionFactory();
        connectionProvider = (ConnectionProvider)sessionFactoryImplementor.getConnectionProvider().getConnection();
        connection = connectionProvider.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;
}
----------------------------------------------------------
Even we can use such kind of stuff.

private void doDBWork(){
    session.doWork(
            new Work() {
                public void execute(Connection connection) throws SQLException
                {
                     // here you get the java sql connection object and do any DB Work with it
                }
            }
        );
    session.disconnect();
}


Above stuff is suggested by JBoss. For more info you can visit Hibernate Session API docs at following url
http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/Session.html



Tuesday, April 23, 2013

Call private method of a class in java

Hi All,

We can execute/call/invoke private method of a Class with the help of Reflection and Mockit.
I give an example in which i have one class Student and that class having one private method showStudentDetails.
I have one another class StudentHack in which i execute that private method in two different methods.

Let us have a Student class
package com.om.demo;

public class Student {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
   
    private void showStudentDetails(){
        System.out.println("Student Name : "+name);
    }
}

Let us have another class StudentHack which Hack Student class

package com.om.demo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import mockit.Deencapsulation;

public class StudentHack {

    // Object of Student class
    private Student student = null;
    // Name of the private method
    private String methodName = "showStudentDetails";

    {
        student = new Student();
        student.setName("Ram");
    }

    public static void main(String[] args) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            NoSuchMethodException, SecurityException {

        StudentHack studentHack = new StudentHack();
        studentHack.callPrivateMethodWithReflection();
        studentHack.callPrivateMethodWithMockit();
    }

    public void callPrivateMethodWithReflection()
            throws IllegalArgumentException, IllegalAccessException,
            InvocationTargetException, NoSuchMethodException, SecurityException {
        // Name of the class
        Class c = Student.class;
        // Create method instance
        Method method = c.getDeclaredMethod(methodName);
        // Allow to access private method
        method.setAccessible(true);
        // call private method
        method.invoke(student, new Object[] {});
    }

    public void callPrivateMethodWithMockit() {
        Deencapsulation.invoke(student, "showStudentDetails");
    }
}


As shown above we can execute private method of a class with the help of Reflection and Mockit

Call private method with Reflection
    Step 1.    Create instance of java.lang.reflect.Method i.e. Method method = c.getDeclaredMethod(methodName);
            where methodName is an argument, which we want to call
    Step 2.    Allow to access private method i.e. method.setAccessible(true);
    Step 3.    Invoke private method i.e. method.invoke(student, new Object[] {});
            Here new Object[] {} is the array of objects which represents argument of method.
            If method contains argument then we need to pass arguments here.

Call private method with Mockit
    Step 1. Deencapsulation.invoke(student, "showStudentDetails");
            If method contains argument then we pass array of Object as 3rd argument.
            i.e. Deencapsulation.invoke(student, "showStudentDetails", new Object[] {});

Wednesday, April 17, 2013

Execute Log4j Logger statements in JUNIT to increase the code coverage

Execute Log4j Logger statements in JUNIT to increase the code coverage

Let us have a Student class

class Student{

    private static final Logger LOGGER = Logger
            .getLogger(Student.class);
    public void showStudent(){
        LOGGER.debug("Enter in showStudent method");
        /*
            Method Body
        */
        LOGGER.debug("Exit from showStudent method");
    }
}

Let us have another Test class StudentTest, which test the functionality of Student class

class StudentTest extends TestCase {

    private static final Logger LOGGER = Logger
            .getLogger(Student.class);
    Student student;       
    @Before
    public void setUp() throws Exception {
        student = new Student();
        LOGGER.setLevel(Level.DEBUG);
    }
   
    @Test
    public void testShowStudent(){
        student.showStudent();
    }
}

In this class we create a Logger object, and pass Student.class as an argument.
    private static final Logger LOGGER = Logger
            .getLogger(Student.class);

           
and set loglevel in setUp() method
    LOGGER.setLevel(Level.DEBUG);
   
Now when we execute student.showStudent() method in our test case then its logger statements also executes because we create an instance of Logger object and set its level to debug (i.e. Level.DEBUG)