14 April 2012

Java Checked Exception and RuntimeException


Java provides two main exception types:
  • Runtime Exceptions :Runtime exceptions extend from either java.lang.RuntimeException or java.lang.Error.
  • Checked exceptions. All checked exceptions extend from java.lang.Exception
Runtime exceptions
  • The method signature does not need to declare runtime exceptions
  •  Caller to a method that throws a runtime exception is not forced to catch the runtime exception
  •  Runtime exceptions extend from RuntimeException or Error
Checked exceptions:
  •  method must declare each checked exception it throws
  •  caller to a method that throws a checked exception must either catch the exception or throw the exception itself
  •  Checked exceptions extend from Exception
Checked exceptions indicate an exceptional condition from which a caller can conceivably recover. Runtime exceptions indicate a programmatic error from which a caller cannot normally recover.

Checked exceptions force you to catch the exception and to do something about it. You should always catch a checked exception once you reach a point where your code can make a meaningful attempt at recovery. However, it is best not to catch runtimeexceptions. Instead, you should allow runtime exceptions to bubble up to where you can see them.

07 April 2012

Java Semaphores


A Semaphore is a thread synchronization construct that can be used either to send signals between threads to avoid missed signals, or to guard a critical section like you would with a lock. Java 5 comes with semaphore implementations in the java.util.concurrent package so you don’t have to implement your own semaphores. Still, it can be useful to know the theory behind their implementation and use.

Here is a list of the topics covered in this text:
1. Simple Semaphore
2. Using Semaphores for Signaling
3. Counting Semaphore
4. Bounded Semaphore
5. Using Semaphores as Locks

Simple Semaphore

Here is a simple Semaphore implementation:

public class Semaphore {
  private boolean signal = false;

  public synchronized void take() {
    this.signal = true;
    this.notify();
  }

  public synchronized void release() throws InterruptedException{
    while(!this.signal) wait();
    this.signal = false;
  }

}

The take() method sends a signal which is stored internally in the Semaphore. The release() method waits for a signal. When received the signal flag is cleared again, and the release() method exited.
Using a semaphore like this you can avoid missed signals. You will call take() instead of notify() and release() instead of wait(). If the call to take() happens before the call to release() the thread calling release() will still know that take() was called, because the signal is stored internally in the signal variable. This is not the case with wait() and notify().

The names take() and release() may seem a bit odd when using a semaphore for signaling. The names origin from the use of semaphores as locks, as explained later in this text. In that case the names make more sense.

Using Semaphores for Signaling

Here is a simplified example of two threads signaling each other using a Semaphore:

Semaphore semaphore = new Semaphore();

SendingThread sender = new SendingThread(semaphore);

ReceivingThread receiver = new ReceivingThread(semaphore);

receiver.start();
sender.start();
public class SendingThread {
  Semaphore semaphore = null;

  public SendingThread(Semaphore semaphore){
    this.semaphore = semaphore;
  }

  public void run(){
    while(true){
      //do something, then signal
      this.semaphore.take();

    }
  }
}
public class RecevingThread {
  Semaphore semaphore = null;

  public ReceivingThread(Semaphore semaphore){
    this.semaphore = semaphore;
  }

  public void run(){
    while(true){
      this.semaphore.release();
      //receive signal, then do something...
    }
  }
}

Counting Semaphore

The Semaphore implementation in the previous section does not count the number of signals sent to it by take() method calls. We can change the Semaphore to do so. This is called a counting semaphore. Here is a simple implementation of a counting semaphore:

public class CountingSemaphore {
  private int signals = 0;

  public synchronized void take() {
    this.signals++;
    this.notify();
  }

  public synchronized void release() throws InterruptedException{
    while(this.signals == 0) wait();
    this.signals--;
  }

}

Bounded Semaphore

The CoutingSemaphore has no upper bound on how many signals it can store. We can change the semaphore implementation to have an upper bound, like this:

public class BoundedSemaphore {
  private int signals = 0;
  private int bound   = 0;

  public BoundedSemaphore(int upperBound){
    this.bound = upperBound;
  }

  public synchronized void take() throws InterruptedException{
    while(this.signals == bound) wait();
    this.signals++;
    this.notify();
  }

  public synchronized void release() throws InterruptedException{
    while(this.signals == 0) wait();
    this.signals--;
    this.notify();
  }
}

Notice how the take() method now blocks if the number of signals is equal to the upper bound. Not until a thread has called receive will the thread calling take() be allowed to deliver its signal, if the BoundedSemaphore has reached its upper signal limit.

Using Semaphores as Locks

It is possible to use a bounded semaphore as a lock. To do so, set the upper bound to 1, and have the call to take() and release() guard the critical section. Here is an example:
BoundedSemaphore semaphore = new BoundedSemaphore(1);

...

semaphore.take();

try{
  //critical section
} finally {
  semaphore.release();
}

In contrast to the signaling use case the methods take() and release() are now called by the same thread. Since only one thread is allowed to take the semaphore, all other threads calling take() will be blocked until release() is called. The call to release() will never block since there has always been a call to take() first.
You can also use a bounded semaphore to limit the number of threads allowed into a section of code. For instance, in the example above, what would happen if you set the limit of the BoundedSemaphore to 5? 5 threads would be allowed to enter the critical section at a time. You would have to make sure though, that the thread operations do not conflict for these 5 threads, or you application will fail.
The relase() method is called from inside a finally-block to make sure it is called even if an exception is thrown from the critical section.

Java Thread Pools


Thread Pools are useful when you need to limit the number of threads running in your application at the same time. There is a performance overhead associated with starting a new thread, and each thread is also allocated some memory for its stack etc.

Instead of starting a new thread for every task to execute concurrently, the task can be passed to a thread pool. As soon as the pool has any idle threads the task is assigned to one of them and executed. Internally the tasks are inserted into a Blocking Queue which the threads in the pool are dequeuing from. When a new task is inserted into the queue one of the idle threads will dequeue it successfully and execute it. The rest of the idle threads in the pool will be blocked waiting to dequeue tasks.

Thread pools are often used in multi threaded servers. Each connection arriving at the server via the network is wrapped as a task and passed on to a thread pool. The threads in the thread pool will process the requests on the connections concurrently. A later trail will get into detail about implementing multithreaded servers in Java.
Java 5 comes with built in thread pools in the java.util.concurrent package, so you don’t have to implement your own thread pool. Still it can be useful to know a bit about the implementation of a thread pool anyways.

Here is a simple thread pool implementation:

public class ThreadPool {

  private BlockingQueue taskQueue = null;
  private List threads = new ArrayList();
  private boolean isStopped = false;

  public ThreadPool(int noOfThreads, int maxNoOfTasks){
    taskQueue = new BlockingQueue(maxNoOfTasks);

    for(int i=0; i< } thread.stop(); threads){ : thread for(PoolThread this.isStopped="true;" stop(){ void synchronized public this.taskQueue.enqueue(task); stopped?); is IllegalStateException(?ThreadPool new throw if(this.isStopped) task){ execute(Runnable thread.start(); PoolThread(taskQueue)); threads.add(new i++){>
public class PoolThread extends Thread {

  private BlockingQueue taskQueue = null;
  private boolean       isStopped = false;

  public PoolThread(BlockingQueue queue){
    taskQueue = queue;
  }

  public void run(){
    while(!isStopped()){
      try{
        Runnable runnable = (Runnable) taskQueue.dequeue();
        runnable.run();
      } catch(Exception e){
        //log or otherwise report exception,
        //but keep pool thread alive.
      }
    }
  }

  public synchronized void stop(){
    isStopped = true;
    this.interrupt(); //break pool thread out of dequeue() call.
  }

  public synchronized void isStopped(){
    return isStopped;
  }
}

The thread pool implementation consists of two parts. A ThreadPool class which is the public interface to the thread pool, and a PoolThread class which implements the threads that execute the tasks.
To execute a task the method ThreadPool.execute(Runnable r) is called with a Runnable implementation as parameter. The Runnable is enqueued in the blocking queue internally, waiting to be dequeued.
The Runnable will be dequeued by an idle PoolThread and executed. You can see this in the PoolThread.run() method. After execution the PoolThread loops and tries to dequeue a task again, until stopped.

To stop the ThreadPool the method ThreadPool.stop() is called. The stop called is noted internally in the isStopped member. Then each thread in the pool is stopped by calling PoolThread.stop(). Notice how the execute() method will throw an IllegalStateException if execute() is called after stop() has been called.
The threads will stop after finishing any task they are currently executing. Notice the this.interrupt() call in PoolThread.stop(). This makes sure that a thread blocked in a wait() call inside the taskQueue.dequeue() call breaks out of the wait() call, and leaves the dequeue() method call with an InterruptedException thrown. This exception is caught in the PoolThread.run() method, reported, and then the isStopped variable is checked. Since isStopped is now true, the PoolThread.run() will exit and the thread dies.

Configure hibernate with struts


A tutorial to show how to integrate Hibernate with in a web application developed with Apache Struts 1.x.


Steps of the integration :
  1. Create a new Hibernate Struts plug-in file to set the Hibernate session factory in servlet context, and include this file in struts-config.xml file.
  2. In Struts, get the Hibernate session factory from servlet context, and do whatever Hibernate task you want
1. Hibernate Struts Plug-in
Create a Hibernate Struts Plug-in, get the Hibernate session factory, store it into the servlet context for later user –servlet.getServletContext().setAttribute(KEY_NAME, factory);.


package com.mkyong.common.plugin;

import java.net.URL;
import javax.servlet.ServletException;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernatePlugin implements PlugIn {
   private Configuration config;
   private SessionFactory factory;
   private String path = "/hibernate.cfg.xml";
   private static Class clazz = HibernatePlugin.class;

   public static final String KEY_NAME = clazz.getName();

   public void setPath(String path) {
      this.path = path;
   }

   public void init(ActionServlet servlet, ModuleConfig modConfig)
      throws ServletException {

      try {

      //save the Hibernate session factory into serlvet context
         URL url = HibernatePlugin.class.getResource(path);
         config = new Configuration().configure(url);
         factory = config.buildSessionFactory();
         servlet.getServletContext().setAttribute(KEY_NAME, factory);

      } catch (MappingException e) {
         throw new ServletException();
      } catch (HibernateException e) {
         throw new ServletException();
      }

   }

   public void destroy() {
      try {
         factory.close();
      } catch (HibernateException e) {
         e.printStackTrace();
      }
   }
}

2. struts-config.xml

Include the Hibernate Struts plug-in into the Struts configuration file (struts-config.xml).
<struts-config>
    ...
    <plug-in className="com.mkyong.common.plugin.HibernatePlugin">
       <set-property property="path" value="/hibernate.cfg.xml"/>
    </plug-in>
 ...
<struts-config>

3. Get the Hibernate session factory

In Struts action class, you can get the Hibernate session factory from servlet context.
servlet.getServletContext().getAttribute(HibernatePlugin.KEY_NAME);
and do whatever Hibernate task as normal.




package com.mkyong.customer.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.mkyong.common.plugin.HibernatePlugin;
import com.mkyong.customer.form.CustomerForm;
import com.mkyong.customer.model.Customer;

public class AddCustomerAction extends Action{

  public ActionForward execute(ActionMapping mapping,ActionForm form,
 HttpServletRequest request,HttpServletResponse response)
  throws Exception {

        SessionFactory sessionFactory =
          (SessionFactory) servlet.getServletContext()
                            .getAttribute(HibernatePlugin.KEY_NAME);

 Session session = sessionFactory.openSession();

 CustomerForm customerForm = (CustomerForm)form;
 Customer customer = new Customer();

 //copy customerform to model
 BeanUtils.copyProperties(customer, customerForm);

 //save it
 customer.setCreatedDate(new Date());

 session.beginTransaction();
 session.save(customer);
 session.getTransaction().commit();

 return mapping.findForward("success");

  }
}

Hello Example - Axis Implementation


This article shows how to use AXIS from Apache to host Web Services using Tomcat5.

What is Web Service?

Web service is a collection of methods that can be accessed over internet using SOAP (Simple Object Access Protocol). SOAP itself is making use of HTTP and XML to encode and trasfer data.
Web services are interoperable , which means a Web service created in Java can be accessed from .NET and vice-versa.

What is AXIS?

AXIS is SOAP engine which works on server and client. It allows Java classes to be deployed as Web services so that they can be accessed from anywhere.
AXIS stands for Apache Extensible Interaction System. It is an open-source project and implements standard JAX-RPC API of Java.


How to install Axis?

Axis must be downloaded from axis.apache.org. It comes as a simple .zip file axis-bin-1_3.zip Extract this zip file to D drive will result in a folder with the name d:\axis-1_3.
Copy axis directory of d:\axis-1_3\webapps into webapps directory of Tomcat5.
Start Tomcat and test whether the Axis web application is running using http://localhost:8080/axis . Please change port number 8080 with port number that you use for Tomcat in your system.
Test whether Axis has access to all required libraries by using http://localhost:8080/axis/happyaxis.jsp. If any core libraries are missing, make sure you copy them to either WEB-INF/lib directory of Axis or common\lib directory of Tomcat.

Creating and comsuming a simple Web service

The following procedure explains how to create a invoke a simple web service, which has a single method sayHello().
  1. Create the following class and place it in axis directory under the name Hello.jws.
    public class Hello
    {
    
     public String sayHello( String name)
     {
       return  "Hello," + name;
     }
    }
  2. Test the web service by giving the url http://localhost:8080/axis/Hello.jws.
    You must see the message saying that there is a web service installed. Click on wsdl hyperlink to see WSDL for the service.
  3. Once service is deployed successfully then run the client by first setting the CLASSPATH and PATH as follows:
    set AXIS_HOME=d:\axis-1_3
    set AXIS_LIB=%AXIS_HOME%\lib
    set AXISCLASSPATH=.;%AXIS_LIB%\axis.jar;%AXIS_LIB%\commons-discovery-0.2.jar;%AXIS_LIB%\commons-logging-1.0.4.jar;%AXIS_LIB%\jaxrpc.jar;%AXIS_LIB%\saaj.jar;%AXIS_LIB%\log4j-1.2.8.jar;%AXIS_LIB%\xml-apis.jar;%AXIS_LIB%\xercesImpl.jar
    
    set classpaht=.;%classpath%;%AXISCLASSPATH%
    
    path c:\jdk1.5.0\bin
    You have to copy xercesimpl.jar and xml-apis.xml or something similar to it must be copied into lib directory of d:\axis-1_3.HelloClient.java is the client program to access web serice.


    import org.apache.axis.AxisFault;
    import org.apache.axis.client.Call;
    import org.apache.axis.client.Service;
    import org.apache.axis.encoding.XMLType;
    import org.apache.axis.utils.Options;
    
    import javax.xml.namespace.QName;
    import javax.xml.rpc.ParameterMode;
    import java.net.URL;
    
    public class HelloClient
    {
      public static void main(String args[])  throws Exception
      {
    
        Service  service = new Service();
        Call     call    = (Call) service.createCall();
        call.setTargetEndpointAddress( "http://localhost:8080/axis/Hello.jws");
        call.setOperationName("sayHello");
        Object ret = call.invoke( new Object[] {"Srikanth"} );
        String res  = (String) ret;
        System.out.println(res);
       }
    }
  4. Then complie and run the following client.javac HelloClient.javajava HelloClientYou must see message saying Hello,Srikanth. If you get any warning regarding Log4j, ignore them.Installing a Web service by just copying .jws file into axis directory is called as drop-in deployment.

Deploying Web Serice using Custom deployment

The following example demonstrates how to deploy a web serice using a .class of Java. We want to expose a few methods (or all) of a Java class as web methods in web service. This can be done by the following procedure:
  1. Create Hello.java as follows:
    public class Hello
    {
    
     public String sayHello( String name)
     {
       return  "Hello," + name;
     }
    }
  2. Compile Hello.java and copy Hello.class into WEB-INF/classes directory of axis application in Tomcat.
  3. Create Hello.wsdd , which contains details of the sercice as follows:
    <deployment name="test" xmlns="http://xml.apache.org/axis/wsdd/"
        xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
    
      <service name="hello" provider="java:RPC">
        <parameter name="className" value="Hello"/>
        <parameter name="allowedMethods" value="*"/>
      </service>
    </deployment>
  4. Run AdminClient to deploy service in Hello.wsdd as follows:java org.apache.axis.client.AdminClient -lhttp://localhost:8080/axis/services/AdminService deploy.wsdd
  5. Test web service by using http://localhost:8080/axis/services/hello. You must see a page saying this is a web service.
  6. Create the HelloClient.java as follows:
    import org.apache.axis.AxisFault;
    import org.apache.axis.client.Call;
    import org.apache.axis.client.Service;
    import org.apache.axis.encoding.XMLType;
    import org.apache.axis.utils.Options;
    
    import javax.xml.namespace.QName;
    import javax.xml.rpc.ParameterMode;
    import java.net.URL;
    
    public class HelloClient
    {
     public static void main(String args[])  throws Exception
     {
       Service  service = new Service();
       Call     call    = (Call) service.createCall();
       call.setTargetEndpointAddress( "http://localhost:8080/axis/services/hello");
       call.setOperationName("sayHello");
    
       Object ret = call.invoke( new Object[] {"Srikanth"} );
       String res  = (String) ret;
       System.out.println(res);
      }
    }
  7. Compile and run HelloClient to get call sayHello() method. The return value will be Hello,Srikanth .

Conclusion

Axis really made the process of creating and deploying web serice in Java very simple. All that you have to create a web service is Tomcat5.x and Axis and a Java compiler (J2SE 5.0).
For further information, refer to axis.apache.org. Also remember axis comes with full documenation in docs directory.
Click Currency Converter Example to see how to create a currency conveter web service and corresponding client.

Spring MVC Request flow


Spring MVC helps in building flexible and loosely coupled web applications. The Model-view-controller design pattern helps in seperating the business logic, presentation logic and navigation logic. Models are responsible for encapsulating the application data. The Views render response to the user with the help of the model object . Controllers are responsible for receiving the request from the user and calling the back-end services.

The figure below shows the flow of request in the Spring MVC Framework.
When a request is sent to the Spring MVC Framework the following sequence of events happen.
  • The DispatcherServlet first receives the request.
  • The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.
  • The Controller process the request by calling the appropriate service methods and returns aModeAndView object to the DispatcherServlet. The ModeAndView object contains the model data and the view name.
  • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.
  • Now the DispatcherServlet will pass the model object to the View to render the result.
  • The View with the help of the model data will render the result back to the user.

02 April 2012

Find duplicates in a array of elements


You are given an array of elements. Some/all of them are duplicates. Find them in 0(n) time and 0(1) space. Property of inputs - Number are in the range of 1..n where n is the limit of the array.

Algorithm -
1. Read input from startPos
2. If input is within the maxRange or it's not in correct place then it's a candidate to be replaced else incrementStartPos
3. finalPosition for input is input[i]

4. if finalPosition < maxRange then swap input with finalPosition and increment finalPosition with MaxRange

5. else no need to swap as previous instances of this element are recorded at finalPos so just increment finalPosition with MaxRange to record another instance

6. if input at startPos is in correct place or reached zero then increment startPos++ till you go through end of Array

7. Iterate through the array and divide each element with maxRange. The divisor indicates how many times a element was repeated and 0 indicates a missing element

Example 

1. Since the number's are in the range of 1..n
2. Start with a[0] and put that element in the right place and increase the element by n (sg:: if a[0]=8 and n=10 then a[8] = 18) to ensure that this element has been placed correctly.
3. Put a[8] in step1 in a[0] if (a[i] < n ) and repeat step2 till a[0] = 11 (1+n(10) = 11) in which case move to a[1]
4. At any point if you get a[i] > n which means this element is a duplicate increment a[i] +nEg: if an array had
(2, 3, 4, 3, 2}
1. n=5 after step1 we'll get
{3, 7, 4, 3, 2}
2. now a[0] = 3 so again in loop we'll get
{4, 7, 8, 3, 2}
3. now a[0] = 4 so again in loop we'll get
{3, 7, 8, 9, 2}
4. a[0] = 3 so again in loop we'll get { , 7, 13, 9, 2}
5. since a[0] is empty move to a[1] and in loop we find it's at the right place so move to next, 8, 9 are also in place so we move to last element and have the final array as
{ , 12, 13, 9, }
Now to find how many are duplicates divide every element by 5 and take the mod => m = (a[i] mod n) -1
this gives you how many times an element is repeated.


Approach and correctness
--------------------------
since we need to do in 0(n) and numbers are in 1..n we need to put one element in correct location in O(n) time and we also need to identify duplicates so increment that element by 'n'.

Java Code 

 public static void main(String[] args) {
int[] inputArr = {0, 4, 3, 4, 1};
findDuplicates(inputArr, 4);
printDuplicatesAndMissingElements(inputArr);
int[] inputArr1 = {0, 2, 3, 4, 3, 2};
findDuplicates(inputArr1, 5);
printDuplicatesAndMissingElements(inputArr1);
}


private static void findDuplicates(int[] inputArr, int maxRange) {
// for simplicity reasons we will assume nothing is there in 0 index of array
// and start from 1
int i = 1;
int maxArrLength = inputArr.length;
while(true) {
if ( i > maxArrLength - 1)
break;
int finalPos = inputArr[i];
System.out.println(" Read :: " + inputArr[i]);
if (finalPos > maxRange) {
//this element is already in final position skip and move further looking for elements within maxRange
i++;
continue;
}
int finalPosElement = inputArr[inputArr[i]];
int startPos = i;
int startPosElement = inputArr[i];
// if startPos element isn't in place and it's within the maxRange..
// then candidate for swap or reaching final pos...
if (inputArr[startPos] != i ||
inputArr[startPos] <= maxRange) {
if (finalPosElement > maxRange) {
// if finalposElement > maxRange then no swapping required
// just add maxRange to denote multiple entry
inputArr[finalPos] += maxRange;
//make startPosElement as 0
inputArr[startPos] = 0;
System.out.println("No swapping required incemented " + inputArr[finalPos] );
}
else {
//swap
int temp = startPosElement;
inputArr[startPos] = finalPosElement;
inputArr[finalPos] = temp + maxRange;
System.out.println("Swapped : " + startPosElement + " with " +finalPosElement);
}
}
printArray(inputArr);
// if the element in current evaluated position isn't still correct repeat the above again
if (inputArr[startPos] == i ||
inputArr[startPos] > maxRange) {
System.out.println(" Read :: "+ inputArr[startPos] + " it's already in place");
inputArr[startPos] += maxRange;
i++;
}
else if (inputArr[startPos] == 0){
i++;
continue;
}
else {
continue;
}
}
}
private static void printArray(int[] inputArr) {
for (int i=1; i < inputArr.length; i++) {
System.out.print(inputArr[i] +",");
}
System.out.println("");
}
private static void printDuplicatesAndMissingElements(int[] inputArr) {
int maxRange = inputArr.length;
for (int i=1; i < inputArr.length; i++) {
if (inputArr[i] == 0) {
System.out.println(" Element [" + i + "] is missing");
}
int input = inputArr[i];
int mod = input / maxRange;
if ( mod > 1) {
System.out.println (" Element [" + i + "] is repeated + [" + mod + "] times");
}
}
}

}