Tuesday 21 October 2014

How Clone method works in JAVA...???

What is clone of object in Java

An object which is returned by clone() method is known as clone of original instance. A clone object should follow basic characteristics e.g. a.clone() != a, which means original and clone are two separate object in Java heap, a.clone().getClass() == a.getClass() and clone.equals(a), which means clone is exact copy of original object. These characteristic is followed by a well behaved, correctly overridden clone() method in Java, but it's not enforced by cloning mechanism. Which means, an object returned by clone() method may violate any of these rules. By following convention of returning object by calling super.clone(), when overriding clone() method, you can ensure that it follows first two characteristics. In order to follow third characteristic, you must override equals method to enforce logical comparison, instead of physical comparison exists in java.lang.Object. For example, clone() method of Rectangle class in this method return object, which has these characteristics, but if you run same program by commenting equals(), you will see that third invariant i.e. clone.equals(a) will return false. By the way there are couple of good items on Effective Java regarding effective use of clone method, I highly recommend to read those items after going through this article.

How Clone method works in Java

java.lang.Object provides default implementation of clone() method in Java. It's declared as protected and native in Object class, so implemented in native code. Since it's convention to return clone() of object by calling super.clone() method, any cloning process eventually reaches to java.lang.Object clone() method. This method, first checks if corresponding object implements Cloneableinterface, which is a marker interface. If that instance doesn't implements Cloneable then it throws CloneNotSupported in Java, a checked exception, which is always required to be handled while cloning an object. If object pass this check, than java.lang.Object's clone() method creates a shallow copy of object and returned it to the caller. Since Object class' clone() method creates copy by creating new instance, and then copying field-by-field, similar to assignment operator, it's fine for primitives and Immutable object, but not suited if your class contains some mutable data-structure e.g. Collection classes like ArrayList or arrays. In that case, both original object and copy of object will point to the same object in heap. You can prevent this by using technique known as deep cloning, on which each mutable field is cloned separately. In short, here is how clone method works in Java :

1) Any class calls clone() method on instance, which implements Cloneable and overrides protected clone() method from Object class, to create a copy.

  Rectangle rec = new Rectangle(3060);
  logger.info(rec);
      
    try {
         logger.info("Creating Copy of this object using Clone method");
         Rectangle copy = rec.clone();
         logger.info("Copy " + copy);
          
    } catch (CloneNotSupportedException ex) {
         logger.debug("Cloning is not supported for this object");
    }

2) Call to clone() method on Rectangle is delegated to super.clone(), which can be a custom super class or by default java.lang.Object

    @Override
    protected Rectangle clone() throws CloneNotSupportedException {
        return (Rectangle) super.clone();
    }

3) Eventually call reaches to java.lang.Object's clone() method, which verify if corresponding instance implements Cloneable interface, if not then it throws CloneNotSupportedException, otherwise it creates a field-by-field copy of instance of that class and returned to caller.

So in order for clone() method to work properly, two things need to happen, a Class should implement Cloneable interface and should override clone() method of Object class. By the way this was the simplest example of overriding clone method and how it works, things gets more complicated with real object, which contains mutable fields, arrays, collections, Immutable object and primitives.

Key Points to remember...

  1. Clone method is used to create a copy of object in Java. In order to use clone() method, class must implement java.lang.Cloneable interface and override protected clone() method from java.lang.Object. A call to clone() method will result in CloneNotSupportedException, if that class doesn't implement Cloneable interface.
  2. No constructor is called during cloning of Object in Java.
  3. Default implementation of clone() method in Java provides "shallow copy" of object, because it creates copy of Object by creating new instance and then copying content by assignment, which means if your Class contains a mutable field, then both original object and clone will refer to same internal object. This can be dangerous, because any change made on that mutable field will reflect in both original and copy object. In order to avoid this, override clone() method to provide deep copy of object.

Java - Exception Hierarchy

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:
  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.





All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using thethrow keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}
For more info about throw click here

The finally Keyword:

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   //The finally block always executes.
}

Monday 20 October 2014

Installing SSL Certificate on Linux Tomcat Server

SSL (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral. With a secure web server, clients can connect to your server secure in the knowledge both that it is who it claims to be and that the transaction is well-encrypted so their data is safe.

  • Here are the few steps to install SSL Certificate.

1. First create a keystore file using below command.
keytool -genkey -alias domainname.com -keyalg RSA -keystore keystore.jks -keysize 2048

2.Generate an CSR(Certificate Signing Request).
keytool -certreq -alias domainname.com -keystore keystore.jks -file domainname.csr

3.Import root certificate.
keytool -import -alias root -keystore keystore.jks -trustcacerts -file root.crt

4. Import intermidiate certificate.
keytool -import -alias intermed -keystore keystore.jks -trustcacerts -file intermediate.crt

5. Install your certificate.
keytool -import -alias domainname.com -keystore keystore.jks -trustcacerts -file keystore.crt


  • Configuration of connector in Apache - In tomcat server.xml file, you have to add some parameters to the connector tag like SSLEnabled, Address, Keystore file, Password of keystore file etc.

<Connector port="443" protocol="HTTP/1.1" address="192.168.2.111" SSLEnabled="true"
maxThreads="500" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="/home/user/keystore_yuspeed.jks"
keystorePass="password" />