Monday, March 12, 2012

Java JVM Shutdown Hook - tutorial

JVM shutdown hooks provide a clean and simple mechanism for registering application-specific behavior that performs the required cleanup work when a JVM terminates.

It is a Java feature that let you have a piece of Java code run whenever the JVM terminates under one of the following conditions:

  - The program exits normally, such as when the last non-daemon thread exits or when the                         Runtime.exit() method is invoked.

  -  The virtual machine is terminated in response to a user interrupt, such as typing CTRL-C, or a                      system-wide event, such as user logoff or system shutdown (for example, the JVM receives               one of  the interrupt signals SIGHUP (Unix Only), SIGINT, or SIGTERM).

A shutdown hook is a Java class that extends java.lang.Thread and is get registered with the Runtime.addShutdownHook()method. Your application may install multiple shutdown hooks. On JVM termination, each shutdown hook will be started and will run concurrently, so the normal rules of thread synchronization apply. You can write shutdown hooks to do anything that a normal thread would do; the JVM will treat them like any other.

Generally we write a shutdown hook to do any last-minute tidying, such as flushing memory buffers, closing files, or displaying an exit message. The JVM will always wait until all shutdown hooks have completed before continuing with the rest of the shutdown sequence, so it is important that your shutdown hooks do actually complete.

The following example shows how to write and install a Java shutdown hook.

/**
 * Implementation of JVM shutdown hook
 *
 * @author abdul
 *
 */
public class ShutDownHook {
    public static void main(String args[]) {
        ShutDownHook hook = new ShutDownHook();
        System.out.println( "Running Main Application..." );
        // Java code to register shutdown hook:
        hook.attachShutDownHook();
        // You can unregister the shutdon hook too.
        hook.removeShutdownHook();
        System.out.println("Exit");
    }

    Thread shutdown =new Thread() {
        @Override
        public void run() {
            //Do your cleaning stuff here eg closing connection,Saving some logs etc
            System.out.println("Inside Add Shutdown Hook");
        }
    };

    private void attachShutDownHook() {
        Runtime.getRuntime().addShutdownHook(shutdown);
        System.out.println("Shut Down Hook Attached.");
    }

    public void removeShutdownHook(){
        Runtime.getRuntime().removeShutdownHook(shutdown);
    }
}

 


There is also a method named removeShutdownHook, which also takes the reference to the Thread object as a parameter. This method allows you to remove a Thread from the list of threads to be started by the VM before it closes (Runtime.getRuntime().removeShutdownHook(shutdown); for the above shutdown hook example).

FAQ On JVM Shutdown Hook API

Thursday, March 8, 2012

Java HashMap Example

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.

The following constructors are defined:  
HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)

 

Hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read.

Here is the code:
 
import java.util.HashMap;
import java.util.Map;

/**
 *
 * This Java HashMap example describes the basic operations performed on the HashMap
 * @author abdul
 *
 */
public class HashMapExample {
    public static void main(String args[]){
       
        // constructs a new empty HashMap with default initial capacity       
        Map<Integer,String> hashMap = new HashMap<Integer,String>();
      
        // adding value into HashMap
        hashMap.put(new Integer(1),"DELL");
        hashMap.put(new Integer(2),"SONY");
        hashMap.put(new Integer(3),"LENOVO");
        hashMap.put(new Integer(4),"SAMSUNG");
        hashMap.put(new Integer(5),"HP");
    
        //To get the size of HashMap       
        System.out.println("HashMap Size: " + hashMap.size());
     
        // To Find particular value from the HashMap:
        if(hashMap.containsValue("HP")){
            System.out.println("HashMap contains HP");
        }else{
            System.out.println("HashMap does not contain HP");
        }
      
        //To find particular key in HashMap
        if( hashMap.containsKey(new Integer(2)) ){
            System.out.println("HashMap contains key");
        }else{
            System.out.println("HashMap does not contain key");
        }
      
        /*
        Use get method of HashMap to get value mapped to particular key.       
        Signature of the get method is,       
        Object get(Object key)       
        */
      
        String value = hashMap.get(new Integer(5));       
        System.out.println("Value : " + value);

        //To get the key value pair of hashMap
        for (Map.Entry<Integer, String> entry1 : hashMap.entrySet()) {
            Integer key = entry1.getKey();
            String data = entry1.getValue();
            System.out.println("key value : " + key + "\t" + data );

        }
 
        // To remove something from the hashmap      
        System.out.println( hashMap.remove(new Integer(4)) + " removed from the hashMap");
       
        //Display value of HashMap
        System.out.println("HashMap : " + hashMap );
    }
}

Output:
HashMap Size: 5
HashMap contains HP
HashMap contains key
Value : HP
key value : 1    DELL
key value : 2    SONY
key value : 3    LENOVO
key value : 4    SAMSUNG
key value : 5    HP
SAMSUNG removed from the hashMap
HashMap : {1=DELL, 2=SONY, 3=LENOVO, 5=HP}

How to get free disk space of a drive in java ?

JDK 1.6 provides few new methods  getTotalSpace(),getFreeSpace(), bundled with java.io.File. These methods provides essential information regarding disk space.

getFreeSpace() method-   Returns the number of unallocated bytes in the partition named by this abstract path name.
getTotalSpace() method - Returns the size of the partition named by this abstract pathname.


Here is the code: 

import java.io.File;

/**
 * Program that returns the number of unallocated bytes , total space in the partition.
 *
 * @author abdul
 *
 */
public class DiskDetail {
    public static void main(String[] args) {
        File file = new File("C:");
        long totalSpace = file.getTotalSpace(); // total disk space in bytes.
        long freeSpace = file.getFreeSpace(); // unallocated / free disk space
        long  diskUsage = (totalSpace - freeSpace);
       
        System.out.println("Total size : " + totalSpace + " bytes");
        System.out.println("Space free : " + freeSpace + " bytes");
        System.out.println("Used Space : " + diskUsage + "bytes");
    }
}

Output:
Total size : 107373129728 bytes
Space free : 44510306304 bytes
Used Space : 62862823424bytes

Reference: 

http://docs.oracle.com/javase/6/docs/api/java/io/File.html 


 

Friday, February 24, 2012

JAXB - II (jaxb.index file and ObjectFactory)

I was getting a Exception like, javax.xml.bind.JAXBException: "doesnt contain ObjectFactory.class or jaxb.index" while trying to create a JAXBContext using JAXBContext.newInstance(String contextPath).

It took me a while to figure out what went wrong. So now that I've got things working correctly, I thought I'd post this example and solution to hopefully save you some time.

When we create a marshaller, we first need to create a JAXBContext via its newInstance() factory method. You can create a context for a specific JAXB class  or you can create a context for a list of packages.

There are two ways to resolve this issue : 
  - By creating ObjectFactory
  - By adding jaxb.index file

jaxb.index :

The jaxb.index file is a text file contains a listing of the classes on the containing package that have JAXB annotations.
Note : The name of the clases is their simple name not their classified name.
 

Rather than creating a ObjectFactory, I guess adding a jaxb.index file is much easy part. Just you need to add class names to the file and place the file in the package (directory) where your JAXB annotated classes reside.
Its just the class name, not the fully qualified name (the package name is determined by the directory you placed the file in) or the.class name.

     JAXBContext context = JAXBContext.newInstance(className.getClass().getPackage().getName());

If the package following package does not have jaxb.index file, this change will cause the test to throw the JAXBException. Add the file and everything works great.

Thursday, February 23, 2012

Java Architecture for XML Binding (JAXB)

Overview:
 - Java Architecture for XML Binding (JAXB) is a Java standard that defines how Java objects are converted to/from XML (specified using a standard set of mappings).


 - It defines a programmer API for reading and writing Java objects to / from XML documents and a service provider which / from from XML documents allows the selection of the JAXB implementation

 - It makes reading  and writing of XML via Java very easy.

 - It allows Java developers to access and process XML data without having to know XML or XML processing


 - It is used heavily by JAX-WS

 

 - It provides ways to generate XML content from a Java representation , to generate a Java representation from XML file , to generate XML schema from Java Objects

 - The JAXBContext class provides the client's entry point to the JAXB API. It provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations: unmarshal, marshal and validate.


- A client application obtains new instances of this class via the newInstance(contextPath) method.            
          JAXBContext jc = JAXBContext.newInstance( "customer.class" );
The contextPath contains a list of Java package names that contain schema derived interfaces




Marshalling :

The Marshaller class provides the client application the ability to convert a Java content tree back into XML data. 


Here is a simple example that unmarshals an XML document and then marshals it back out:

          JAXBContext jc = JAXBContext.newInstance( "Customer.class" );
          Unmarshaller u = jc.createUnmarshaller(); 
          Customer customer = (Customer)u.unmarshal( new File( "test.xml" ) );
          Marshaller m = jc.createMarshaller(); m.marshal( customer, System.out );


Unmarshalling
:

The Unmarshaller class provides the client application the ability to convert XML data into a tree of Java content objects. 


For example: 
       JAXBContext jc = JAXBContext.newInstance( "customer.class" ); 
       Unmarshaller u = jc.createUnmarshaller();
       Customer customer = (Customer)u.unmarshal( new File( "test.xml" ) ); // ok                                                                                                            
                                                                                          to be continued...

References:

http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/JAXBContext.html
http://stackoverflow.com/questions/5964996/convert-java-object-to-xml
http://ooxs-be.goracer.nl/EN/java/Java%20and%20XML%20Binding.html

Tutorial:
https://github.com/abdulwaheed18/JAXB-Basic-Tutorial

Monday, February 20, 2012

OSGi for Beginners

Open Services Gateway initiative framework (OSGi)

1. What is OSGi ?
 
OSGi is a specification. The core of the OSGi specification defines a component and service model for Java. The components and services can be dynamically activated, de-activated, updated and de-installed.
A very practical advantage of OSGi is that every bundle must define its exported Java packages and its required dependencies. This way you can effectively control the provided API and the dependencies of your plug-ins.

OSGi bundles:

The OSGi specification defines the OSGi bundle as the unit of modularization.
A bundle is a cohesive, self-contained unit, which explicitly defines its dependencies to other modules and services. It also explicitly defines its external API.

Technically OSGi bundles are .jar files with additional meta information. This meta 
information is stored in the "META-INF" folder in the "MANIFEST.MF" file.
bundle = identity & dependency info + jar

The "MANIFEST.MF" file is part of a standard jar specification to which OSGi adds additional metadata. Any non-OSGi runtime will ignore the OSGi metadata. Therefore OSGi bundles can be used without restrictions in non-OSGi Java environments.

Bundle-SymbolicName and Version:

Each bundle has a symbolic name which is defined via the Bundle-SymbolicName property. and a version number in the Bundle-Version property.
The Bundle-Version and the Bundle-SymbolicName uniquely identifies a bundle in OSGi.Both properties are defined in the "MANIFEST.MF" file.
 
Bundle dependencies and public API:

Via the "MANIFEST.MF" file a bundle can define its dependency to other bundles or packages. OSGi will throw a ClassNotFoundException, if a class from a bundle tries to access a class without a defined dependency to it.
 
In the MANIFEST.MF file a bundle also defines the Java packages which should be exported and therefore available to other bundles (as API). Packages which are not exported are not visible to other bundles.

All these restrictions are enforced via a specific OSGi classloader. Each bundle has its own classloader. Access to restricted classes is not possible, also not via reflection.

A bundle can define that it depends on a certain version (or a range) of another bundle, e.g. bundle A can define that it depends on bundle C in version 2.0, while bundle B defines that it depends on version 1.0 of bundle C.

Bundle Lifecycle:

With the installation of a bundle in the OSGi runtime this bundle is persisted in a local bundle cache. The OSGi runtime is then trying to resolve all dependencies of the bundle.
If all required dependencies are resolved the bundle is in the status "RESOLVED" otherwise it is in the status "INSTALLED".
If several bundles exist which would satisfy the dependency, then the bundle with the highest version is taking. If the versions are the same, then the bundle with the lowest ID will be taken. If the bundle is started, its status is "STARTING". Afterwards it gets the "ACTIVE" status.


OSGi offers the following advantages:

Reduced complexity: Developing OSGi means developing modules ie bundles. They hide their internals from other bundles and the communication is through well defined interfaces.Hence the later changes can be easily accommodated without affecting other modules.

Reuse : The OSGi component model makes the integration of third party components very easy.

You can install, uninstall, start, and stop different modules of your application dynamically without restarting the container.

Your application can have more than one version of a particular module running at the same time.

OSGi provides very good infrastructure for developing service-oriented applications, as well as embedded, mobile, and rich internet apps. 

Some of the currently popular implementations of the OSGi specs :

Apache Felix:
Eclipse Equinox
Knopflerfish

Popular application servers which use OSGi technology :

Weblogic – Oracle Weblogic Application Server
WebSphere – IBM Websphere JEE Application Server

REFERENCE:

Thursday, February 16, 2012

Java Reflection: Annotations

What are Java Annotations?

Annotations is a new feature from Java 5. Annotations are a kind of comment or meta data you can insert in your Java code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection. The annotation can be attached to Classes, Methods,Parameters,Fields etc.

How to create custom Annotation?

To create an annotation we use the interface keyword and add an @ symbol infront of it. The @ symbol will tell the compiler that it doing some business with an annotation.

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
The @ in front of the interface marks it as an annotation. Once you have defined the annotation you can use it in your code.Here is an example of class annotation:
@MyAnnotation(value="Class Annotation")
public class MyClass {
}
The two directives in the annotation definition, @Retention(RetentionPolicy.RUNTIME) and @Target(ElementType.TYPE), specifies how the annotation is to be used. 
  @Retention(RetentionPolicy.RUNTIME) means that the annotation can be accessed via reflection at runtime. If you do not set this directive, the annotation will not be preserved at runtime, and thus not available via reflection.

@Target(ElementType.TYPE) means that the annotation can only be used ontop of types (classes and interfaces typically). You can also specify METHOD or FIELD, or you can leave the target out alltogether so the annotation can be used for both classes, methods and fields.
 

Class Annotations

You can access the annotations of a class, method or field at runtime. Here is an example that accesses the class annotations:

Class aClass = MyClass.class;
Annotation[] annotations = aClass.getAnnotations();

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("value: " + myAnnotation.value());
    }
}
You can also access a specific class annotation like this:

Class aClass = MyClass.class;
Annotation annotation = aClass.getAnnotation(MyAnnotation.class);

if(annotation instanceof MyAnnotation){
    MyAnnotation myAnnotation = (MyAnnotation) annotation;
    System.out.println("value: " + myAnnotation.value());
}

Method Annotations

Here is an example of a method with annotations:
public class MyClass {
  @MyAnnotation(value = "Method Annotation")
  public void doSomething(){}
}
 
You can access method annotations like this:

Method method = ... //obtain method object
Annotation[] annotations = method.getDeclaredAnnotations();

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("value: " + myAnnotation.value());
    }
}
 
You can also access a specific method annotation like this:

Method method = ... // obtain method object
Annotation annotation = method.getAnnotation(MyAnnotation.class);

if(annotation instanceof MyAnnotation){
    MyAnnotation myAnnotation = (MyAnnotation) annotation;
    System.out.println("value: " + myAnnotation.value());
}


Parameter Annotations

It is possible to add annotations to method parameter declarations too. Here is how that looks:


public class MyClass {
  public static void doSomethingElse(
        @MyAnnotation(value="Parameter Annotation") String parameter){
  }
}
 
You can access parameter annotations from the Method object like this:

Method method = ... //obtain method object
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Class[] parameterTypes = method.getParameterTypes();

int i=0;
for(Annotation[] annotations : parameterAnnotations){
  Class parameterType = parameterTypes[i++];

  for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("param: " + parameterType.getName());
        System.out.println("value: " + myAnnotation.value());
    }
  }
}
 
Notice how the Method.getParameterAnnotations() method returns a two-dimensional Annotation array, containing an array of annotations for each method parameter.

Field Annotations

Here is an example of a field with annotations:

public class MyClass {
  @MyAnnotation(value = "Field Annotation")
  public String myField = null;
}
 
You can access field annotations like this:

Field field = ... //obtain field object
Annotation[] annotations = field.getDeclaredAnnotations();

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("value: " + myAnnotation.value());
    }
} 
 
You can also access a specific field annotation like this:


Field field = ... // obtain method object
Annotation annotation = field.getAnnotation(MyAnnotation.class);

if(annotation instanceof MyAnnotation){
    MyAnnotation myAnnotation = (MyAnnotation) annotation;
    System.out.println("value: " + myAnnotation.value());
}



The whole tutorial is on the github:
https://github.com/abdulwaheed18/Annotation-Tutorial

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...