Wednesday, June 3, 2015

META-INF in Java

About JAR

JAR file is a file format based on the popular ZIP file format and is used for aggregating many files into one.
It is essentially a zip file that contains an optional META-INF directory.

About The META-INF Directory

META-INF directory is an optional directory structure contained in a JAR file, a file format containing java classes files and/or resources using the well-known ZIP file format.
A JAR file is normally created using a command-line jar tool or java.util.jar API in the Java package.
In META-INF directory, there is MANIFEST.MF file which is used to define extension and package related data and an INDEX.LIST file which contains location information for packages defined in an application or extension.
The INDEX.LIST file is normally generated using “–i” option of the jar command line tool. As a JarIndex implementation process it is used by class loaders to hasten the class loading process.
Other important files in META-INF Directory are x.SF and x.DSA where x stands for base file name. The x.SF is the signature file for the JAR file and the x.DSA is a signature block file related to the x.SF.
Also there exists a services sun directory in the META-INF Directory which stores all the service provider configuration files.

Summarized info. about META-INF

The META-INF Directory consists of the following files, which is used to configure the applications, extensions, class loaders and services:
  1. MANIFEST.MF ------> it is used to define extension and package related data.
  2. index.list ------> It contains the location information for packages defined in an application or extension.
    1. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process.
  3. x.SF -------> The signature file for the JAR file. 'x' stands for the base file name.
  4. x.DSA --------> The signature block file associated with the signature file with the same base file name.
    1. This file stores the digital signature of the corresponding signature file.
  5. services/ -------> This directory stores all the service provider configuration files.
  • Note-
For further reference:-
http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html

What is User-Defined Exception?

Developer can able to create their Own Exception Class by extending Exception Class from java.lang API. And the toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.

The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax. throw new MyException("I threw my own exception.") To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:

public myMethodName() throws MyException

package com.java.learning;

/**
* @author Achappan
*
*/
public class MyOwnException extends Exception {
private int age;
public MyOwnException(int age) {
  this.age = age;
}
@Override
public String toString() {
 // TODO Auto-generated method stub return "Age cannot be negative "+age;
 }
}


package com.java.learning;
public class MyOwnExceptionClassTest
{
/** * @param args */
public static void main(String[] args) throws MyOwnException{
 int age = getAge();
  if (age < 0){
        throw new MyOwnException(age); }else{ System.out.println("Age entered is " + age);
   }
}
static int getAge(){ return -10; }
}

What is singleton class?


Singleton class is used to create only one instance of the class. Its preventing to create multiple Objects and it is used to create the connection pool for example to maintain single database connection object.
The singleton class created using private constructor 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.

To implement this design pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor

public class SingletonObjectDemo {
      // Note that the constructor is private 
     private SingletonObjectDemo()
    {
         // Optional Code 
    }


Step 2: Create a Method for getting the reference to the Singleton Object

public class SingletonObjectDemo {
  
      private static SingletonObject singletonObject; // Note that the constructor is private private        

      SingletonObjectDemo() {
         // Optional Code 
     } 

      public static SingletonObjectDemo getSingletonObject() { 
               if (singletonObject == null) { 
                singletonObject = new SingletonObjectDemo();
              } 
      return singletonObject;
   }


We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.

public static synchronized SingletonObjectDemo getSingletonObject() 

It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone(); 

This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException { 
              throw new CloneNotSupportedException(); 


The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.

class SingletonClass {
      private static SingletonClass singletonObject;
    
     /** A private Constructor prevents any other class from instantiating. */ 
     private SingletonClass() { 
        // Optional Code 
      } 
   
     public static synchronized SingletonClass getSingletonObject() { 
          if (singletonObject == null) { 
                singletonObject = new SingletonClass();
          } 
       return singletonObject;
  } 

public Object clone() throws CloneNotSupportedException { 
            throw new CloneNotSupportedException(); 
  } 
}

public class SingletonObjectDemo {
       public static void main(String args[]) { 
       // SingletonClass obj = new SingletonClass();
   //Compilation error not allowed
       SingletonClass obj = SingletonClass.getSingletonObject(); // Your Business Logic   
       System.out.println("Singleton object obtained"); 
 }
}

Another approach

We don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.

public class SingletonClass {
        private static SingletonClass ourInstance = new SingletonClass(); 
        public static SingletonClass getInstance() { 
                  return singletonObj;
        } 
        private SingletonClass() { }
}

Java Debugging Tips with Eclipse

Debugging helps us to identify and fix defects in the application. We will focus on run-time issues and not compile time errors. Eclipse is suitable for debugging using most of the IDEs like NetBeans too.

Before to know about debugging tips just keep the below points in your mind.

  • Do not use System.out.println as a tool to debug.
  • Enable detailed log level of all the components involved.
  • Use a log analyzer to read logs.

 1. Conditional Breakpoint

Just click on the left pane (just before the line number)  to create a breakpoint. In debug perspective, ‘Breakpoints’ view will list the breakpoint created. 



2. Exception Breakpoint

In Breakpoints view there is a button labeled as J! We can use that button to add a java exception based breakpoint. For example we want the program to halt and allow to debug when a NullPointerException is thrown we can add a breakpoint using this.

 

3. Watch Point

When a chosen attribute is accessed or modified program execution will halt and allow to debug. Select a class variable in Outline view and from its context menu select Toggle Watchpoint. This will create a watch point for that attribute and it will be listed in Breakpoints view.

4. Evaluation (Display or Inspect or Watch)

Ctrl+Shift+d or Ctrl+Shift+i on a selected variable or expression will show the value. We can also add a permanent watch on an expression/variable which will be shown in Expressions view when debug is on.


5. Change Variable Values

We can change the value of a variable on the fly during debug. Choose a variable and go to Variables view and select the value, type and enter.


6. Stop in Main

In Run/Debug Settings, Edit Configuration we can enable a check box that says Stop in main. If enabled when we debug a java program that launches with a main method, the execution halts at first line of main method.


7. Environment Variables

Instead of going to System properties to add an environment variable, we can conveniently add it through Edit Configuration dialog box.


8. Drop to Frame

We can just return the control to any frame in the call stack during debug. Changes made to variables will not be reset. Choose the stack level which you want to go back and restart debug from there and click the drop to frame button from debug toolbar.


9. Step Filter

When we Step Into (F5) a method we may go into external libraries (like java) and we may not need it. We can add a filter in preferences and exclude packages.


10. Step Into, Over and Return

  • F5 – Step Into: moves to next step and if the current line has a method call the control will go into the first line of the called method.
  • F6 – Step Over: moves the control to next line. If there is a method call in the current line, it executes the method call internally and just moves the control to next line.
  • F7 – Step Return: When done from inside a method the control will move to the calling line from where the current method is invoked.
  • F8 – Move to next breakpoint.

Monday, June 1, 2015

Java 6 Some Features and Enhancements

    1. Collections Framework Enhancements 

      The purpose of changes in this API is to provide better bi-directional collection access. 

      These new collection interfaces are provided:

    • Deque - a double ended queue, supporting element insertion and removal at both ends. Extends the Queue interface.
    • BlockingDeque - a Deque with operations that wait for the deque to become non-empty when retrieving an element, and wait for space to become available in the deque when storing an element. Extends both the Deque and BlockingQueue interfaces. (This interface is part of java.util.concurrent.)
    • NavigableSet - a SortedSet extended with navigation methods reporting closest matches for given search targets. A NavigableSet may be accessed and traversed in either ascending or descending order. This interface is intended to supersede the SortedSet interface.
    • NavigableMap - a SortedMap extended with navigation methods returning the closest matches for given search targets. A NavigableMap may be accessed and traversed in either ascending or descending key order. This interface is intended to supersede the SortedMap interface.
    • ConcurrentNavigableMap - a ConcurrentMap that is also a NavigableMap. (This interface is part of java.util.concurrent.)
             The following concrete implementation classes have been added:
             These existing classes have been retrofitted to implement new interfaces:
    • LinkedList - retrofitted to implement the Deque interface.
    • TreeSet - retrofitted to implement the NavigableSet interface.
    • TreeMap - retrofitted to implement the NavigableMap interface.
             Two new methods were added to the Collections utility class:
    • newSetFromMap(Map) - creates a general purpose Set implementation from a general purpose Map implementation. There is no IdentityHashSet class, but instead, just use
      Set<Object> identityHashSet=
          Collections.newSetFromMap(
              new IdentityHashMap<Object, Boolean>());
      
    • asLifoQueue(Deque) - returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
            The Arrays utility class now has methods copyOf and copyOfRange that can efficiently resize,  truncate, or copy subarrays for arrays of all types.

             Before:
     
          int[] newArray = new int[newLength];
          System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
    
           
            After:

         int[] newArray = Arrays.copyOf(a, newLength);
     
    
    

    2. Java Web Start and Java Plug-in Common Enhancements 

    Cache and System Format

    The format of the cache is completely changed and should never be assumed. Any existing code using the previous cache format for Java Web Start or Java Plug-in will no longer work. Existing applications in the Java Web Start cache will be upgraded and converted to the new cache format the first time you run a Java Web Start application, or if you launch the cache viewer using javaws -viewer. 
    The system cache will be upgraded and converted to the new format the first time you launch Java Web Start in system mode, or if you just launch javaws -system.

    Download Engine and Cache Consolidation

    The caching mechanism and download engine are redesigned and consolidated between Java Web Start and Java Plug-in. This brings several new features to Java Web Start, previously available only in Java Plug-in and vice versa. They are :
    • Caching can be disabled using the Java Control Panel.
    • Java Web Start honors the maximum cache size set using Java Control Panel.
    • Java Web Start can start a cleanup thread to remove Least Recently Used(LRU) items from the cache when approaching the maximum cache size.
    • The <no-cache> directive is now supported. When the no-cache directive is used , an update check is made to make sure the cached contents are same as at the URL. The resource is then downloaded into the cache and the expiration field is ignored.
    • The expiration-date is supported. If a downloaded resource contains an expiration date, it will not be used after that date.

    Secure Versioning

    In Java SE 6 unsigned Java Web Start applications that specify a version other than the latest one will trigger a security warning, requiring explicit user permission before the application will run. Signed Java Web Start applications are not affected.

    Other Enhancements

    Java Web Start and Java Plug-in now support CRL (Certificate Revocation Lists) and OCSP (Online Certificate Status Protocol) for verifying the certificates.
    Java Control Panel provides an option to select the default SSL handshaking protocol. The default is set to SSLv3 and SSLv2. You can also change it to TSL.
    The Java Console is excluded from modality. By using the new modality features of AWT in Java 6, you can interact with Java Console even when your application is displaying a modal dialog.
    All dialogs and screens of Java Web Start and Java Plug-in are redesigned to be more user friendly, intuitive, and accessible.

    3. Internationalization Support

    Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes. Sometimes the term internationalization is abbreviated as i18n, because there are 18 letters between the first "i" and the last "n."
    An internationalized program has the following characteristics:
    • With the addition of localization data, the same executable can run worldwide.
    • Textual elements, such as status messages and the GUI component labels, are not hardcoded in the program. Instead they are stored outside the source code and retrieved dynamically.
    • Support for new languages does not require recompilation.
    • Culturally-dependent data, such as dates and currencies, appear in formats that conform to the end user's region and language.
    • It can be localized quickly.
    
    
    
    

    4. IO Support

    java.io

    One new class is provided:
    • Console - Contains methods to access a character-based console device. The readPassword() methods disable echoing thus they are suitable for retrieval of sensitive data such as passwords. The method System.console() returns the unique console associated with the Java Virtual Machine.
    The following new methods were added to File:
    Constructors were added to the following class:
    The behavior of the following method was modified:
    • The File.isFile() Windows implementation has been modified to always return false for reserved device names such as CON, NUL, AUX, LPT, etc. Previously it returned true, which customers considered a bug because it was inconsistent with behavior for devices on Unix.

    java.nio

    • A new java.nio.channels.SelectorProvider implementation that is based on the Linux epoll event notification facility is included. The epoll facility is available in the Linux 2.6, and newer, kernels. The new epoll-based SelectorProvider implementation is more scalable than the traditional poll-based SelectorProvider implementation when there are thousands of SelectableChannels registered with a Selector. The new SelectorProvider implementation will be used by default when the 2.6 kernel is detected. The poll-based SelectorProvider will be used when a pre-2.6 kernel is detected.
    • The system property sun.nio.ch.disableSystemWideOverlappingFileLockCheck controls whether java.nio.channels.FileChannel.lock() checks whether regions are locked by other instances of FileChannel. Unless this system property is set to true, FileChannel.lock() will throw an OverlappingFileLockException if an application attempts to lock a region that overlaps one that is locked by another instance of FileChannel. The system property exists to provide compatibility with previous releases which do not implement the JVM-wide overlapping file lock check.

     

    What is collection?

    A collection is an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.

    Saturday, March 2, 2013

    Servlets

    What is servlet?

    Servlet is a java progrom it acts as a middle layer between web server and database server.  It is used to build a dynamic webpages for web applications. It handles the http requests from web browser and after request processing will receive response from web server and send it back to the browser to display the result page.

    Advantage of Servlets:

    1. Better performance
    2. Handle multiple requests concurrenlty.
    3. Alternative to CGI script
    4. Platform independent

    Servlet Architecture:

    Servlets Architecture