What is try-with-resources in Java 7 or above?

try-with-resources + java 7 + feature

Java designer has finally came up with better solution for closing resource. try-with-resources introduced in Java 7. Its one of noticeable feature of Java 7 and currently used by developers around the world.

The try-with-resources statement ensures that all your resources like BufferedReader, FileInputStream, ObjectInputStream, etc... closed at the end of statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Source Code
import java.io.BufferedReader;
import java.io.FileReader;

public class TryWithResourcesExample {
   public static void main(String[] args) {
      /**
       * Resources declared in parentheses `()` after `try` keyword 
       * implements java.io.Closeable interface.
       * 
       * Note: 
       * - Even if exception occurs both the resources will be closed.  
       * - close methods of resources are called in the opposite order of their creation.
       */
      try(
      /* Create object of FileReader */
   FileReader objFileReader = new FileReader("D:\\Dropbox\\Notes.txt");
   /* Create object of BufferedReader using object of FileReader */
   BufferedReader objBufferedReader = new BufferedReader(objFileReader);
 ){
   /* Print the first line of file */
   System.out.println(objBufferedReader.readLine());
      }catch(Exception ex){
   ex.printStackTrace();
      }
   }
}

Note
  • - Even if exception occurs all resources will be closed.
  • - close methods of resources are called in the opposite order of their creation.


How to Serialize and Deserialize object in Java?


javadoc
To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

Deserialization is the process of converting the serialized form of an object back into a copy of the object.

Source Code (User.java)
Any object that implements Serializable interface is eligible for Object Serialization.
import java.io.Serializable;

public class User implements Serializable{
    private transient long id;
    private String Firstname;
    private transient String Lastname;
    private transient boolean status;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }
    
    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}

transient keyword
Any variable or object declared with transient keyword will not be stored in Serialize Object. It will give you default value particular data type.
  • Boolean Data type: transient boolean will give false value in Object Deserialization.
  • Numeric Data types: transient int, double, long, float will give 0 value in Object Deserialization.
  • String Data type: transient String will give null value in Object Deserialization.
  • Any Object: transient ANY_OBJECT will give null value in Object Deserialization.

Source Code (SerializeObject.java)
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Serialization Code...");
        /* Creating an object of User */
        User objUser = new User();
        
        /* Set properties of User object */
        /* Id will be set to `0` in serialized object because it is declared as `transient` */
        objUser.setId(111l);
        /* Set Firstname */
        objUser.setFirstname("Vicky");
        /* Lastname will be set to `null` in serialized object because it is declared as `transient` */
        objUser.setLastname("Thakor");
        /* Status will be set to `false` in serialized object because it is declared as `transient` */
        objUser.setStatus(true);
        
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileOutputStream to store object in file [Windows: C:\Users\CurrentUser\User.ser(i.e: `.ser` Standard File Extension)] */
                FileOutputStream objFileOutputStream = new FileOutputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectOutputStream to write objUser on file. */
                ObjectOutputStream objObjectOutputStream = new ObjectOutputStream(objFileOutputStream);
            ){
            /* Write object on file. */
            objObjectOutputStream.writeObject(objUser);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Source Code (DeSerializeObject)
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeSerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Deserialization Code...");
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileInputStream to get serialized file. */
                FileInputStream objFileInputStream = new FileInputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectInputStream to read User object from file. */
                ObjectInputStream objObjectInputStream = new ObjectInputStream(objFileInputStream);
           ){
            /* Read the User object from file. We've to cast it to our object */
            User objUser = (User) objObjectInputStream.readObject();
            /* Print the properties of User object */
            System.out.println(objUser.getId());
            System.out.println(objUser.getFirstname());
            System.out.println(objUser.getLastname());
            System.out.println(objUser.isStatus());
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Output (DeSerializeObject.java)
Object Deserialization Code...
0
Vicky
null
false

An Example of HttpSessionAttributeListener in Java


HttpSessionAttributeListener, is used to keep track of every HttpSession attribute Added, Replaced or Removed in your current web application.

Source Code
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class SessionAttributeListener implements HttpSessionAttributeListener {
    /**
     * Called when any servlet/jsp in application add the Attribute in HttpSession 
     * @param event 
     */
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        /**
         * Get the attribute name.
         * Attribute name is always in String
         */
        String strAttributeName = event.getName();
        /**
         * Get the attribute value
         * Attribute value can be String, Object, etc...
         */
        Object objAttributeValue = event.getValue();
        /* Print the value of AttributeName and AttributeValue */
        System.out.println("Attribute added: [" + strAttributeName + " : " + objAttributeValue + "]");
    }

    /**
     * Called when any servlet/jsp in application override/replace/add_same_attribute_to the HttpSession
     * @param event 
     */
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        /**
         * Get the attribute name.
         * Attribute name is always in String
         */
        String strAttributeName = event.getName();
        /**
         * Get the attribute value
         * Attribute value can be String, Object, etc...
         */
        Object objAttributeValue = event.getValue();
        /* Print the value of AttributeName and AttributeValue */
        System.out.println("Attribute removed: [" + strAttributeName + " : " + objAttributeValue + "]");
    }

    /**
     * Called when any servlet/jsp in application try to remove the attribute from HttpSession
     * @param event 
     */
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        /**
         * Get the attribute name.
         * Attribute name is always in String
         */
        String strAttributeName = event.getName();
        /**
         * Get the attribute value
         * Attribute value can be String, Object, etc...
         */
        Object objAttributeValue = event.getValue();
        /* Print the value of AttributeName and AttributeValue */
        System.out.println("Attribute replaced: [" + strAttributeName + " : " + objAttributeValue + "]");

    }
}

Attach SessionAttributeListener in your web application through web.xml . Add following code in you web.xml between web-app tag.
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
...
...
    <servlet>
        <servlet-name>SessionAttributeServlet</servlet-name>
        <servlet-class>com.javaquery.servlet.SessionAttributeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionAttributeServlet</servlet-name>
        <url-pattern>/SessionAttributeServlet</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>com.javaquery.Listeners.SessionAttributeListener</listener-class>
    </listener>
</web-app>

Source Code (Sample Servlet)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionAttributeServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            HttpSession httpSession = request.getSession();
            /* SessionAttributeListener.attributeAdded(HttpSessionBindingEvent event) will be called */
            httpSession.setAttribute("username", "vicky.thakor"); 
            /* SessionAttributeListener.attributeRemoved(HttpSessionBindingEvent event) will be called */
            httpSession.setAttribute("username", "rajpriya.chudasama");
            /* SessionAttributeListener.attributeReplaced(HttpSessionBindingEvent event) will be called */
            httpSession.removeAttribute("username");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}

How to compile Freestyle/Simple Java Project in Jenkins?

Jenkins Freestyle Project Logo

We were testing certain features of Jenkins. We were trying to set-up simple Java Project with ANT. There ain't any simple article available over Internet and it took hours to set-up so I thought let me share my experience with you.

Step 1: Create Simple Java Project using Eclipse.

Step 2: Open Jenkins and Click "New Item", Provide Job name, Select "Freestyle Project" and Click OK to create new Jenkins Job. Follow the image.



Step 3: On next page click on "Advance" under Advanced Project Options. Follow the image.



Step 4: Select "Use custom workspace" and Provide Directory path and Display name. Follow the image.



Step 5: Under Build section select "Ant Version". Target is name of <target> tag in build.xml. You can choose it as per you convenient but it should be same in build.xml and here in Jenkins. Follow the image.



Step 6: Click on "Advanced" under Build section and write "Build File" name commonly used build.xml. Follow the image.



Step 7: Click on "Apply"

Step 8: Create "build.xml" under root directory of your project. Follow the image.


Step 9: Copy paste the following content in your build.xml. Change Project name and default value (*if applicable)
<?xml version="1.0" encoding="UTF-8"?>
<project name="JenkinsSampleProject" default="compile" basedir=".">
 <!-- ANT will start execution from here by finding target "compile"  -->
 <target name="compile" depends="clean">
  <!-- Java compile parameters here  -->
  <javac debug="true" debuglevel="lines,vars,source" srcdir="src" destdir="bin" />
 </target>

 <!-- "compile" target depends on "clean" so It'll delete "bin" folder if exists and 
   create new "bin" folder for compiles class file -->
 <target name="clean">
  <delete dir="bin" />
  <mkdir dir="bin" />
 </target>
</project>

Step 10: Go to Jenkins and click on "Build Now"


Unknown Source in Exception or Stacktrace of Java

Unknown Source in Exception or Stacktrace of Java

Its very rare situation when you face this issue in Java Programming. Possibly there are very few people have seen this error. This exception occur when you compile your Java code with no "debugging information" flag.

Why such provision in Java?
This option given by Java to prevent hacking. When you compile your code "without debugging information" then it won't show line number in exception instead it shows "Unknown Source".


Solution For any Integrated Development Environment (IDE)
I've not tested this setting with any IDE but find the code compilation settings in your IDE and set flag as per your requirement.

-g ~ This will compile code with debugging information [Shows line number in exception]
-g:none ~ This will compile code without debugging information [Won't show line number/Unknown Source]


Source Code
/**
 * ------------------------------------------
 * This will shows line number in exception
 * ------------------------------------------
 * javac -g UnknownSourceExample.java 
 * java UnknownSourceExample
 * 
 * ------------------------------------------
 * This won't shows line number in exception
 * ------------------------------------------
 * javac -g:none UnknownSourceExample.java 
 * java UnknownSourceExample
 */
public class UnknownSourceExample{
 public static void main(String args[]){
  System.out.println(10/0);
 }
}

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at UnknownSourceExample.main(UnknownSourceExample.java:3)
------------------------------------------  
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at UnknownSourceExample.main(Unknown Source)

Jenkins / ANT Compilation
We've just setup Jenkins for scheduled war compilation and on exception we face UnknownSource issue. We are still in learning phase and didn't know that we've to set debug attribute in build.xml of ANT. If you are also facing same issue then here is the solution that may help you.

Find code compilation tag <javac> in your build.xml, add debug and debuglevel attribute in it and now build your project through Jenkins so it'll show line number in exception instead Unknown Source. Your tag will look like as follow...
<javac debug="true" debuglevel="lines,vars,source" destdir="bin" srcdir="src"/>

Hibernate Disjunction with Example

Hibernate Disjunction with Example

Hibernate Disjunction, is used to add multiple condition in SQL query separated by OR clause within brackets. To generate following query using Hibernate Criteria we need to use Disjunction.

Query
select
 this_.id as id0_0_,
 this_.username as username0_0_,
 this_.email as email0_0_ 
from
 user_master this_ 
where
(
 this_.username=? 
 or this_.username=?
)

Source Code
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;

/**
 * Hibernate Conjunction with Example
 * @author javaQuery
 */
public class HibernateDisjunctionExample {

    public static void main(String[] args) {
 /* Create hibernate configuration. */
        Configuration objConfiguration = new Configuration();
        objConfiguration.configure("com\\hibernateassist\\hbm\\hibernate.cfg.xml");

        /* Open session and begin database transaction for database operation. */
        SessionFactory objSessionFactory = objConfiguration.buildSessionFactory();
        Session session = objSessionFactory.openSession();
        
        /* Create criteria */
        Criteria criteria = session.createCriteria(User.class);
        
        /* Create object of Disjunction */
        Disjunction objDisjunction = Restrictions.disjunction();
        /* Add multiple condition separated by OR clause within brackets. */
        objDisjunction.add(Restrictions.eq("Username", "vicky"));
        objDisjunction.add(Restrictions.eq("Username", "thakor"));
        
        /* Attach Disjunction in Criteria */
        criteria.add(objDisjunction);
        
        /* Execute criteria */
        criteria.list();
    }
}

Hibernate Conjunction with Example

Hibernate Conjunction

Hibernate Conjunction, is used to add multiple condition in SQL query separated by AND clause  within brackets. To generate following query using Hibernate Criteria we need to use Conjunction.

Query
select
 this_.id as id0_0_,
 this_.username as username0_0_,
 this_.email as email0_0_ 
from
 user_master this_ 
where
(  
 this_.username=? 
 and this_.username=? 
)

Source Code
Following code will generate above given query.
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Restrictions;

/**
 * Hibernate Conjunction with Example
 * @author javaQuery
 */
public class HibernateConjunctionExample {

    public static void main(String[] args) {
        /* Create hibernate configuration. */
        Configuration objConfiguration = new Configuration();
        objConfiguration.configure("hibernate.cfg.xml");

        /* Open session and begin database transaction for database operation. */
        SessionFactory objSessionFactory = objConfiguration.buildSessionFactory();
        Session session = objSessionFactory.openSession();
        
        /* Create criteria */
        Criteria criteria = session.createCriteria(User.class);
        
        /* Create object of Conjunction */
        Conjunction objConjunction = Restrictions.conjunction();
        /* Add multiple condition separated by AND clause within brackets. */
        objConjunction.add(Restrictions.eq("Username", "vicky"));
        objConjunction.add(Restrictions.eq("Username", "thakor"));
        
        /* Attach Conjunction in Criteria */
        criteria.add(objConjunction);
        
        /* Execute criteria */
        criteria.list();
    }
}