Saturday, 14 June 2014

Introduction to JavaBeans

Every Java user interface class is a JavaBeans component. Understanding JavaBeans will help you to learn GUI components.JavaBeans is a software component architecture that extends the power of the Java language by enabling well-formed objects to be manipulated visually at design time in a  pure Java builder tool, such as NetBeans and Eclipse.

JavaBean Rules :
  • A JavaBean must have a public, no-argument constructor (a default constructor). This is required so that Java frameworks can facilitate automated instantiation.
  • The JavaBean class attributes must be accessed via accessor and mutator methods that follow a standard naming convention (getXxxx and setXxxx, isXxxx for boolean attributes). It’s important to note that an “attribute” is a named memory location that contains a value, while a “property” refers to this set of methods used to access an attribute. This allows frameworks to automate operations on attribute values.
  • The JavaBean class should be serializable. This allows Java applications and frameworks to save, store, and restore the JavaBean state.That means a bean must implement the Serializable interface to ensure a persistent state.
package player; 
// The class is serialized for IO operations
public class PersonBean implements java.io.Serializable {
 // attributes declared as private
 private String name;
 private boolean counter;
 

 // Default Constructor
 public Person() { }

 // getXxx to access the name attribute
 public String getName() {
  return this.name;
 }

 // setXxxx to mutate the name attribute
 public void setName(String name) {
  this.name = name;
 }

 // isXxxx to access boolean attribute
 public boolean iscounter() {
  return this.counter;
 }

 // setXxx to mutate boolean attribute
 public void setCounter(boolean counter) {
  this.counter = counter;
 }
}
 
import player.PersonBean;
 
/**
 * Class TestPersonBean
 */
public class TestPersonBean {
    /**
     * Tester method  for class PersonBean
     */
    public static void main(String[] args) {
        PersonBean person = new PersonBean();
 
        person.setName("Bob");
        person.setcounter(false);
 
        // Output: "Bob [alive]"
        System.out.print(person.getName());
        System.out.println(person.isCounter() ? " [counter]" : " [alive]");
    }
} 
Advantages:
  • The properties, events, and methods of a bean that are exposed to another application can be controlled.
  • A bean may register to receive events from other objects and can generate events that are sent to those other objects.
  • Auxiliary software can be provided to help configure a java bean.
  • The configuration setting of bean can be saved in a persistent storage and restored at a later time.
 Disadvantages:
  • A class with a nullary constructor is subject to being instantiated in an invalid state. If such a class is instantiated manually by a developer (rather than automatically by some kind of framework), the developer might not realize that the class has been improperly instantiated. The compiler can’t detect such a problem, and even if it’s documented, there’s no guarantee that the developer will see the documentation.
  • Having to create a getter for every property and a setter for many, most, or all of them can lead to an immense quantity of boilerplate code.

Monday, 9 June 2014

Singleton Design Pattern in java

Singleton pattern in Java is one of the most common patterns available and it’s also used heavily in core Java libraries.
A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern.
Java has several design patterns Singleton Pattern being the most commonly used.
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it."
That means this design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.

The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
The key is not the problem and definition. In singleton pattern, tricky part is implementation and management of that single instance.
There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:

 1.Java.lang.Runtime with getRuntime() method
 2.Java.awt.Toolkit with getDefaultToolkit()
 3.Java.awt.Desktop with  getDesktop()

There are at least four ways to implement Singleton pattern in Java.
1) Singleton by synchronizing getInstance() method
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums
This article is an attempt to explain the basics on singleton design pattern.If you want more insight on singleton then i will explain it in detail later.

Monday, 2 June 2014

What is DatabaseMetaData?

DatabaseMetaData is used to know which type of driver we are using and whether is it compatable or JDBC complaint or not. It is used to know all details about database provider as well.Here is the example--
 
package com.rexofcyber.jdbc;
 
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class MyDatabaseMetadata {
 
    public static void main(String a[]){
         
        Connection con = null;
        try {
            con = DriverManager.
                getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
                        ,"user","password");
            DatabaseMetaData dm = con.getMetaData();
            System.out.println(dm.getDriverVersion());
            System.out.println(dm.getDriverName());
            System.out.println(dm.getDatabaseProductName());
            System.out.println(dm.getDatabaseProductVersion());
        } catch (SQLException e) {
         
            e.printStackTrace();
        } finally{
            if(con != null){}
                try {
                    con.close();
                } catch (SQLException e) {
            
                    e.printStackTrace();
                }
            }
        }
    }
}

How to execute any type of query in JDBC?

The Statement.execute() method allows us to execute any kind of query like select, update. It returns boolean. If the return value is true, then it executed select query, get the ResultSet object and read the resulted records. If it returns false, then it can be update query, call getUpdateCount() method to get total records updated.
package com.rexofcyber.jdbc;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class MyExecuteMethod {
 
    public static void main(String a[]){
         
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.
                    getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
                        ,"user","password");
            Statement stmt = con.createStatement();
            //The query can be update query or can be select query
            String query = "select * from emp";
            boolean status = stmt.execute(query);
            if(status){
                //query is a select query.
                ResultSet rs = stmt.getResultSet();
                while(rs.next()){
                    System.out.println(rs.getString(1));
                }
                rs.close();
            } else {
                //query can be update or any query apart from select query
                int count = stmt.getUpdateCount();
                System.out.println("Total records updated: "+count);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            try{
                if(con != null) con.close();
            } catch (Exception ex){}
        }
    }
}


Saturday, 24 May 2014

Puzzle 1: Hello, Goodbye

This program adds an unusual twist to the usual Hello world program. What does
it print?

public class HelloGoodbye {
public static void main(String[] args) {
try {
System.out.println("Hello world");
System.exit(0);
} finally {
System.out.println("Goodbye world");
}
}
}
Solution :
The program contains two println statements: one in a try block and the other in the corresponding finally block. The try block executes its println and finishes execution prematurely by calling System.exit. At this point, you might expect control to transfer to the finally block. If you tried the program, though, you found that it never can say goodbye: It prints only Hello world.
It is true that a finally block is executed when a try block completes execution whether normally or abruptly. In this program, however, the tryblock does not complete execution at all. The System.exit method halts the execution of the current thread and all others dead in their tracks.The presence of a finally clause does not give a thread special permission to continue executing.
When System.exit is called, the virtual machine performs two cleanup tasks before shutting down. First, it executes all shutdown hooks that have been registered with Runtime.addShutdownHook. This is useful to release resources external to the VM. Use shutdown hooks for behavior that must occur before the VM exits.The following version of the program demonstrates this technique,
printing both Hello world and Goodbye world, as expected:

public class HelloGoodbye {
public static void main(String[] args) {
System.out.println("Hello world");
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() {
System.out.println("Goodbye world");
}
});
System.exit(0);
}
}

The second cleanup task performed by the VM when System.exitis called concerns finalizers. If either System.runFinalizersOnExitor its evil twin Runtime.runFinalizersOnExit has been called, the VM runs the finalizers on all objects that have not yet been finalized. These methods were deprecated a long time ago and with good reason. Never call System.runFinalizersOnExitor Runtime.runFinalizersOnExit for any reason: They are among the most
dangerous methods in the Java libraries. Calling these methods can result in finalizers being run on live objects while other threads are concurrently manipulating them, resulting in erratic behavior or deadlock.
In summary, System.exit stops all program threads immediately; it does not cause finally blocks to execute, but it does run shutdown hooks before halting the VM. Use shutdown hooks to terminate external resources when the VM shuts down. It is possible to halt the VM without executing shutdown hooks by calling System.halt, but this method is rarely used. 

Extract a zip file using Java

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
/**
 * This utility extracts files and directories of a standard zip file to
 * a destination directory.
 */
public class UnzipUtility {
    /**
     * Size of the buffer to read/write data
     */
    private static final int BUFFER_SIZE = 4096;
   

    public void unzip(String zipFilePath, String destdirectory)throwsIOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }
 
    private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}

Monday, 31 March 2014

How can you improve Java I/O performance?

Java applications that utilise Input/Output are excellent candidates for performance  tuning. Profiling of Java applications that handle significant volumes of data will show significant time spent in I/O operations. This means substantial gains can be had from I/O performance tuning. Therefore, I/O efficiency should be a high priority for developers looking to optimally increase performance.
The basic rules for speeding up I/O performance are
  • Minimise accessing the hard disk.
  • Minimise accessing the underlying operating system.
  • Minimise processing bytes and characters individually.   
Let us look at some of the techniques to improve I/O performance.

Use bufferingto minimise disk access and underlying operating system. As shown below, with buffering large chunks of a file are read from a disk and then accessed a byte or character at a time.

Without buffering : inefficient code
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
int count = 0;
int b = ;
while((b = fis.read()) != -1){
if(b== '\n') {
count++;
}
}
// fis should be closed in a finally block.
fis.close() ;
}
catch(IOException io){}
Note: fis.read() is a native method call to the underlying system.
With Buffering:yields better performance
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
int count = 0;
int b = ;
while((b = bis.read()) != -1){
if(b== '\n') {
count++;
}
}
//bis should be closed in a finally block.
bis.close() ;
}
catch(IOException io){}
Note:bis.read() takes the next byte from the input buffer and only
rarely access the underlying operating system.

Instead of reading a character or a byte at a time, the above code with buffering can be improved further by reading one line at a time as shown below:

FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
While (br.readLine() != null) count++;