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){}
        }
    }
}