Producer-Consumer Problem in Java | Java Thread interview question for Experinced developer

The producer-consumer problem is one of the most frequently encountered problems when we attempt multi threaded programming. While not as challenging as some of the other problems in multi-threaded programming, an incorrect implementation of this problem can create a mess of your application. Produced items will be left unconsumed, starting items will be skipped, consumption depends on whether the production began earlier or later than consumption attempts etc. To add to this you might notice the anomalies long after it has actually happened and most importantly like almost all multi-threaded programs, this one is hard to debug and reproduce too.
So in this post I thought I would attempt to solve this problem in Java with the help of Java' awesome java.util.concurrent package and its classes.
First of all, let us see the characteristics of the producer-consumer problem:
  • Producer(s) produce items.
  • Consumer(s) consume the items produced by the producer(s).
  • Producer(s) finish production and let the consumers know that they are done.
Note that in this producer-consumer problem the producer is running on a different thread than the ones on consumer. This setup makes sense in two cases:
  • The steps to do the consumption of the item produced in independent and not dependent on other items.
  • The time to process the items is larger that the time to produce them.
The term "larger" in the second point is used a bit loosely. Consider the case where producer reads a line from a file and the "consumption and processing" is just to log the line in a special format back to a file then the use of a producer consumer problem solution can be considered a case of over-engineering a solution. However if for each of those lines the "consumption and processing" step is to make a HTTP GET/POST request to a web-server and then dump the result somewhere then we should opt for a producer-consumer solution. In this case I am assuming that all the data to do a GET/POST is available in the line (item) itself and we are not dependent on previous/next lines.
So let us first take a look at the characteristics of the producer-consumer problem solution that I have posted below:
  • There can be multiple producer.
  • There will be multiple consumers.
  • Once the production of new items is done the producer(s) will let the consumers know so that the consumer will exit after the last item is consumed and processed.
It is interesting to note that to solve this problem at a generic level we can address only the consumer side and not the producer side. This is because the production of items might be done at any time and there is very little that we can do in a generic way to control the production of items. We can, however control the consumer's behaviour while accepting items from producer(s). Having laid out the rules let us take a look at the consumer contract:


  1. package com.maximus.producerconsumer;  
  2.   
  3. public interface Consumer  
  4. {  
  5.  public boolean consume(Item j);  
  6.    
  7.  public void finishConsumption();  
  8. }   

Here the consumer can be shared between multiple producers of similar items; by similar items I mean producer that produces objects of type "Item". The definition if Item is as follows:


  1. package com.maximus.consumer;  
  2.   
  3. public interface Item  
  4. {  
  5.  public void process();  
  6. }  
Now we take a look at an implementation of the Consumer interface:

  1. package com.maximus.consumer;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.List;  
  5. import java.util.concurrent.BlockingQueue;  
  6. import java.util.concurrent.ExecutorService;  
  7. import java.util.concurrent.Executors;  
  8. import java.util.concurrent.LinkedBlockingQueue;  
  9.   
  10. public class ConsumerImpl implements Consumer  
  11. {  
  12.  private BlockingQueue< Item > itemQueue =   
  13.   new LinkedBlockingQueue< Item >();  
  14.    
  15.  private ExecutorService executorService =   
  16.   Executors.newCachedThreadPool();  
  17.    
  18.  private List< ItemProcessor > jobList =   
  19.   new LinkedList< ItemProcessor >();  
  20.    
  21.  private volatile boolean shutdownCalled = false;  
  22.     
  23.  public ConsumerImpl(int poolSize)  
  24.  {  
  25.   for(int i = 0; i < poolSize; i++)  
  26.   {  
  27.    ItemProcessor jobThread =   
  28.     new ItemProcessor(itemQueue);  
  29.      
  30.    jobList.add(jobThread);  
  31.    executorService.submit(jobThread);  
  32.   }  
  33.  }  
  34.    
  35.  public boolean consume(Item j)  
  36.  {  
  37.   if(!shutdownCalled)  
  38.   {  
  39.    try  
  40.    {  
  41.     itemQueue.put(j);  
  42.    }  
  43.    catch(InterruptedException ie)  
  44.    {  
  45.     Thread.currentThread().interrupt();  
  46.     return false;  
  47.    }  
  48.    return true;  
  49.   }  
  50.   else  
  51.   {  
  52.    return false;  
  53.   }  
  54.  }  
  55.    
  56.  public void finishConsumption()  
  57.  {  
  58.   shutdownCalled = true;  
  59.     
  60.   for(ItemProcessor j : jobList)  
  61.   {  
  62.    j.cancelExecution();  
  63.   }  
  64.     
  65.   executorService.shutdown();  
  66.  }  
  67. }  

Now the only point of interest is the ItemProcessor that the consumer internally uses to process the incoming items. ItemProcessor is coded as follows:

  1. package com.maximus.consumer;  
  2.   
  3. import java.util.concurrent.BlockingQueue;  
  4. import java.util.concurrent.TimeUnit;  
  5.   
  6. public class ItemProcessor implements Runnable  
  7. {  
  8.  private BlockingQueue< Item> jobQueue;  
  9.    
  10.  private volatile boolean keepProcessing;  
  11.     
  12.  public ItemProcessor(BlockingQueue< Item > queue)  
  13.  {  
  14.   jobQueue = queue;  
  15.   keepProcessing = true;  
  16.  }  
  17.    
  18.  public void run()  
  19.  {  
  20.   while(keepProcessing || !jobQueue.isEmpty())  
  21.   {  
  22.    try  
  23.    {  
  24.     Item j = jobQueue.poll(10, TimeUnit.SECONDS);  
  25.       
  26.     if(j != null)  
  27.     {  
  28.      j.process();  
  29.     }  
  30.    }  
  31.    catch(InterruptedException ie)  
  32.    {  
  33.     Thread.currentThread().interrupt();  
  34.     return;  
  35.    }  
  36.   }  
  37.  }  
  38.    
  39.  public void cancelExecution()  
  40.  {  
  41.   this.keepProcessing = false;  
  42.  }  
  43. }   
The only challenge above is the condition in the while loop. The while loop is so written to support the continuation of the consumption of items even after the producer(s) have finished production and has notified the consumer that production is finished. The above while loop ensures that consumption of all the items is done before the threads exit.This will be the case when producers run faster that consumers.

The above consumer is thread-safe and can be shared multiple producers such that each producer may concurrently call consumer.consume() without bothering about synchronization and other multi-threading caveats. Producers just need to submit an implementation of the Item interface whose process() method will contain the logic of how the consumption will be done.

As a bonus for reading the post I put forward a test program that demonstrates how to use the above classes:



  1. package com.maximus.consumer;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.InputStreamReader;  
  7.   
  8. public class Test  
  9. {  
  10.  public static void main(String[] args) throws Exception  
  11.         {  
  12.          Consumer consumer = new ConsumerImpl(10);  
  13.            
  14.          BufferedReader br =   
  15.           new BufferedReader(  
  16.           new InputStreamReader(  
  17.           new FileInputStream(  
  18.           new File(args[0]))));  
  19.            
  20.          String line = "";  
  21.            
  22.          while((line = br.readLine()) != null)  
  23.          {  
  24.           System.out.println(  
  25.            "Producer producing: " + line);  
  26.           consumer.consume(new PrintJob(line));  
  27.          }  
  28.            
  29.          consumer.finishConsumption();  
  30.         }  
  31. }  
  32.   
  33. class PrintJob implements Item  
  34. {  
  35.  private String line;  
  36.    
  37.  public PrintJob(String s)  
  38.  {  
  39.   line = s;  
  40.  }  
  41.    
  42.  public void process()  
  43.  {  
  44.   System.out.println(  
  45.    Thread.currentThread().getName() +   
  46.    " consuming :" + line);  
  47.  }  
  48. }  
The above consumer can be tweaked in a host of different ways to make it more flexible. We can define what the consumer will do when production is done. It may be tweaked to allow batch processing but I leave that to the user. Feel free to use it and twist it in whatever way you want.

Most common error : java.lang.UnsupportedClassVersionError: when is it thrown by a JVM & how to resolve it | Experinced level java interview question

UnsupportedClassVersionError is (evidently a descendant of the Error class in Java) which subclasses java.lang.ClassFormatError which in turn subclasses java.lang.LinkageError (which is a direct subclass of java.lang.Error). This error is thrown in the cases when the JVM (Java Virtual Machine) attempts to read a class file and finds that the major and minor version numbers in the particular class file are not supported. This happens in the cases when a higher version of Java Compiler is used to generate the class file than the JVM version which is used to execute that class file. Please do notice that this is not true vice-versa which means you can comfortably use a higher version of JVM to run a class file compiled using an earlier version of Java Compiler. Let’s understand why? We'll see below a valid Java program and subsequently an alert and a stack trace of the error which are thrown as a result of the above explained situation which causes UnsupportedClassVersionError. FYI: The output

public class TestFinally {

      public static void main(String[] args) {
             
            try{
                  try{
                        throw new NullPointerException ("e1");
                  }
                  finally{
                        System.out.println("e2");
                  }
            }
            catch(Exception e){
                        e.printStackTrace();
            }
      }
}



The error alert and the stack trace if the right JVM is not used



java.lang.UnsupportedClassVersionError: TestFinally (Unsupported major.minor version 49.0)
      at java.lang.ClassLoader.defineClass0(Native Method)
      at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
      at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
      at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
      at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
      at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
      at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)


The minor and major version numbers are represented by the major_version and minor_version items respectively in a Java Class File structure. A combination of these two unsigned integers (both of length 2 bytes each) determines the particular version of the class file format. If a class file has major version number M and minor version number m, we denote the version of its class file format as M.m.

As per Java VM Spec, “A Java virtual machine implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a Java virtual machine implementation conforming to a certain release level of the Java platform may support.” For example: Implementations of version 1.2 of the Java 2 platform can support class file formats of versions in the range 45.0 through 46.0 inclusive.

Major version number of the class file formats of the popular Java versions are: J2SE 6.0 = 50, J2SE 5.0 = 49, JDK 1.4 = 48, JDK 1.3 = 47, JDK 1.2 = 46, JDK 1.1 = 45. Now you understand what in our example “major.minor version 49.0” signifies? It simply means we have used J2SE 5.0 for compiling the source code as the class file format is 49.0 where major_version is ‘49’ and minor_version is ‘0’.

Errors are never detected at compile time. This is quite easier to understand in this case – how can the compiler have the information at the time of compilation about which version of JVM would be used execute the compiled class file? It can't, right? So is the case with other errors as well. This is the reason why all the Errors are unchecked. The error alert also rightly shows that it's a JVM Launcher error.

How to resolve UnsupportedClassVersionError?


Whenever you encounter this error, do check if you’re using an earlier version of JVM to execute the class file than the corresponding version of compiler you used to compile the source code. The example shown here was compiled using Java 5.0 compiler, but when I tried to run using JVM 1.4, I got the above error. I just needed to switch either to a JVM version 5.0 or above OR needed to switch to a Java Compiler of JDK 1.4 or below (you of course need to make sure the source code is compatible with the corresponding version of the compiler otherwise you’ll start getting other compiler errors).

A higher JVM version doesn’t cause a problem in most of cases unless the class file format is quite old (and hence doesn’t lie in the supported range as specified by Sun for that particular JVM version ... as discussed above). But, it’s always a good practice to have both the Compiler and the JVM of the same version.

How to get name of a Class in Java from within a static method | Fresher level java interview Question

One of our regular visitors (Ranvijay) had asked it a couple of days back. Though, the code is pretty straightforward, I think it might help few others if posted as an article.

One of the many possible ways of finding the name of the class in Java from within a static method is by using a static nested class, which will have a public instance method returning the class name of the enclosing class (in our case the class where we have the particular static method).


public class GetClassNameInStaticMethod {

public static void main(String[] args) {
 // Calling a Static Method
 System.out.println("Current Class Name: " + getCurClassName());
}
public static String getCurClassName(){
 return (new CurClassNameGetter()).getClassName();
}

//Static Nested Class doing the trick
public static class CurClassNameGetter extends SecurityManager{
 public String getClassName(){
  return getClassContext()[1].getName();
 }
}
}

Output

Current Class Name: GetClassNameInStaticMethod

How to recover Shift + Deleted folders/emails in Outlook 2013 | Outlook email recovery

How to recover Shift + Deleted folders/emails in Microsoft Outlook?

Ever wondered if you can really recover something in Windows, which you have Shift + Deleted? Well, you can do that at least in few cases (if not in all) - one of them being recovering folders/emails which you accidentally Shift + Deleted in your Microsoft Outlook (running with MS Exchange Server). I managed to delete one important folder this weekend and only then I could realize the importance of this feature.


As you would certainly be aware that a plain 'Delete' moves the particular email to the 'Deleted Items' folder, from where you can easily restore them unless they get permanently deleted from that folder once one of the two situations occur - either the Deleted Items folder exceeds its quota of storage or the deleted emails become stale more than the allowed number of days (which I guess is 20/30 days) - whichever happens earlier.


But, it's interesting to know that even a Shift + Delete, does not really instantly delete all the items permanently - not at least in case of Microsoft Outlook. It's just that you probably can't see an option to recover them with your default settings. You need to add one registry entry and that's it. They will be visible to you then and you can recover the same way as you restore deleted items from the 'Deleted Items' folder. How many of these emails, folders, or emails within the folders you can recover, again depends upon the two parameters - storage quota and the age of the Shift + Deleted emails. So, you probably need to act fast whenever you manage to lose your folders/emails accidently. Find below the steps which are required for this recovery:-


Registry Entry:
if not already there (it's required to be added only once after the installation of the client application), you would be required to add the below entry in your Windows Registry. Below are the steps:-


  • Run -> regedit
  • expand HKEY_LOCAL_MACHINE
  • expand and go to SOFTWARE
  • expand and go to Microsoft
  • expand and go to Exchange
  • expand and go to Options
  • add the entry 'DumpsterAlwaysOn REG_DWORD 0x00000001 (1)'

Registry entry for recovering Shift+Deleted emails in Outlook
Microsoft Outlook -> Tools -> Recover Deleted Items...: If you want to recover a folder then simply select the corresponding mailbox and select 'Recover Deleted Items...', which will enable you select and recover the Shift + Deleted folders of that mailbox. If you want to recover emails then simply select the corresponding folder and do the same. It will show you all the emails of that folder available for you to be recovered (based on storage quota and age of the emails as discussed above). Please find below the sample screenshots for your reference:

Recover Deleted Items in Tools menu after registry entry
Recovering emails window where you can select which all to recover

IBM Websphere commerce server(WCS) interview question in Sapient date 30.04.2013 | IBM WCS Interview Question in MNC Software Company 2013

I have attended interview of Company Sapient last week for IBM WCS developer they have asked following interview question below

1. Explain Catalog data model in WCS
2. Difference between controller command and task command 
3. Write Hello world in WCS programming model
4. Explain Data bean type.
5. Jsp tag in WCS
6. Sales catalog master catalog
7. Define excepion in IBM WCS.
8. Explain control command mehods.
9. Explian order flow.
10. Can two main() method in java class
11. Difference between HashMap and HashTable.
12  implicit object in JSP.

Setting of Java classpath in Windows , Unix, Linux operating System.| What is Use java classpath

Classpath in Java is path to directory or list of directory which is used by 
ClassLoaders to find and load class in Java program. Classpath can be specified 
using CLASSPATH environment
 variable which is case insensitive, -cp or -classpath command line option or 
Class-Path attribute in manifest.mf file inside JAR file in Java.  In this Java 
tutorial we will learn What is Classpath in Java, how Java resolve classpath and 
How Classpath works in 
Java along side How to set classpath for Java in windows and UNIX environment. 
 I have experience in finance and insurance domain and Java is heavily used in this domain for writing sophisticated Equity, Fixed income trading applications. Most of these investment
 banks has written test as part of there core Java interview questions and
 I always find at least one question related to CLASSPATH in Java on those 
interviews. Java CLASSPATH is one of the most important concepts in Java, 
 but,  I must say mostly overlooked. 
This should be the first thing you should learn while writing Java programs 
because without correct understanding of Classpath in Java you can't understand 
how Java locates your class files. Also don't confuse Classpath with PATH in Java,
 which is another
 environment variable used to find java binaries located in JDK installation 
directory,
 also known as JAVA_HOME. Main difference between PATH and CLASSPATH is that 
former is used to locate Java commands while later is used to locate Java class
 files.

So let’s start with basic and then we will see some example and improvisation 
of Classpath in Java. In fact CLASSPATH is an environment variable which is used 
by Java Virtual Machine
 to locate user defined classes. As I said In this tutorial we will see How to 
setup 
classpath for java in windows and Linux , java -classpath example in different 
scenario and use of java -classpath or java -cp.

Setting Java Classpath in Windows

In order to set Classpath for Java in Windows (any version either Windows XP, 
 Windows 2000 or Windows 7) you need to specify value of environment variable 
CLASSPATH, name of this 
variable is not case sensitive and it doesn’t matter if name of your environment
 variable is Classpath, CLASSPATH or classpath in Java.

Here is Step by Step guide for setting Java Classpath in Windows:

Go to Environment variable window in Windows by pressing "Windows + Pause “-->
Advanced -->Environment variable " or you can go from right click on my computer
 than choosing properties
 and then Advanced and then Environment variable this will open Environment 
variable window in windows.
Now specify your environment variable CLASSPATH and put the value of your 
JAVA_HOME\lib and also include current directory by including (dot or period sign).
 Now to check the value of Java classpath in windows type "echo %CLASSPATH" in
 your DOS command prompt and it will show you the value of directory which 
are included in CLASSPATH.

You can also set classpath in windows by using DOS command like :

set CLASSPATH=%CLASSPATH%;JAVA_HOME\lib;
This way you can set classpath in Windows XP, windows 2000 or Windows 7 and 8,
 as they all come with command prompt.
Setting Java Classpath in UNIX or Linux

To set Classpath for Java In Linux you can simply export
 CLASSPATH="your classpath" from either your .bash_profile or 
.bashrc script which will run whenever you login into your 
Linux or Unix Machine. Now to check value of Java CLASSPATH in Linux type
 "echo ${CLASSPATH}" 
this will print value of Classpath in command prompt. By using export
 command you can set classpath for Java in Unix, Linux, Solaris, 
IBM AIX or any other UNIX operating system. 
I hope this example for setting classpath in Java will enable to set 
classpath by yourself 
let me know if you face any problem while setting up classpath in Java

Overriding Classpath in Java

You can override classpath in Java, defined by environment variable CLASSPATH by providing option "-cp" or "-classpath" while running Java program and this is the best way 
to have different classpath for different Java application running on same Unix or Windows machine,
 standard way to define classpath for Java application is creating start-up script for Java program and set classpath there as shown below :

CLASSPATH=/home/tester/classes
java -cp $CLASSPATH Test

By default Java CLASSPATH points to current directory denoted by "." and it will look for any class only in current directory.

Different example of using Classpath in Java

In case you have multiple directories defined in CLASSPATH variable,
 Java will look for a class starting from first directory and only look 
second directory in case it did not 
find the specified class in first directory. This is extremely useful
 feature of Classpath in
 java to understand and it’s very useful while debugging Java application or  patch release kind of stuff. Let’s see  java -classpath example

I have set my classpath environment variable as CLASSPATH=/home/tester/first:/home/tester/second. Now I have Test class of different version in both first and second directory.
 When I give a command "java Test" What will happen ? Which Test class would be picked? Since 
JVM search directory in the order they have listed in CLASSPATH variable it will first go to the "first" directory and if it finds Test.class over there it will not go to 
/home/tester/second directory. Now if you delete Test.class from /home/tester/first directory it
 will go to /home/tester/second directory and will pick  Test.class from there.

I have used this feature of Java Classpath to test my patch releases, we used to have a folder called "patch" listed as first element in Java CLASSPATH and any point of
 time we want to put any debug statement or want to test any bug we just modify Java source file ,
 compile it and generate class file and put that inside patch folder instead of creating JAR file and releasing whole new Java application. This is very handy if you are
 working in a large project where you don't have development environment setup in Windows and your
 project only runs on Unix server. This approach is much faster than remote debugging Java application in Eclipse

Its also worth noting that when you use the  java -jar command line option to run your Java program as an executable JAR, then the CLASSPATH environment variable will be
 ignored, and also the -cp and -classpath switches will be ignored. In this case you can set your Java
 classpath in the META-INF/MANIFEST.MF file by using the Class-Path attribute. In short Class-path attribute in manifest file overrides classpath specified by -cp, -classpath or CLASSPATH environment variable.

Now a common question if I have my CLASSPATH variable pointing to current directory "." and I have class called "Test" inside package "testing" and with below directory 
structure C:\project\testing\Test.class in my computer.

What will happen if I run command "java Test" from directory "C:\project\testing\"? will it run?
No it will not run it will give you :
Exception in thread "main" java.lang.NoClassDefFoundError: Test
Since name of the class is not Test, instead it’s testing.Test even though your classpath is set to current directory.

Now what will happen if I give command  java testing.Test from C:\project\testing\ it will again not run and give error?

Exception in thread "main" java.lang.NoClassDefFoundError: testing/Test

Why because now it looking for class called Test which is in package testing, starting from current directory "." but don't find it since there is no directory
 called "testing after this path "C:\project\testing\".

To run it successfully you need to go back to directory  C:\project and now run 
C:\project>java testing.Test  and It will run successfully because of Classpath issues i prefer to use Eclipse rather than running Java program from command prompt. 

Errors related to Classpath in Java

If you are working in Java you must have faced some errors and exception related to classpath in java, two most common issues related to java classpath is 
ClassNotFoundException and NoClassDefFoundError. I have seen that many Java developer tries to solve this 
error by trial and error; they just don’t look beyond the hood and try to understand what the reason for these java classpath related errors is. 
They often misunderstood that these two errors are same also. 

Here is the reason of these Java classpath errors: 

ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries to load a Java class at Runtime and don’t find corresponding 
class file on classpath. Two keyword here “dynamically” and “runtime”. Classic example of these errors is 
whey you try to load JDBC driver by using Class.forname(“driver name”) and greeted with java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. So this 
error essentially comes when Java try to load a class using forName() or by loadClass() method of ClassLoader. Key thing to note is that presence of that
 class on Java classpath is not checked on compile time. So even if those classes are not present on Java classpath your program will compile successfully and only fail when you try to run.

On the other hand NoClassDefFoundError is an Error and more critical than ClassNotFoundException which is an exception and recoverable. NoClassDefFoundError 
comes when a particular class was present in Java Classpath during compile time but not available during run-time. Classic example of this error is using log4j.jar 
for logging purpose and forgot to include log4j.jar on classpath in java during run-time. to read more about logging in Java see . Keyword here is,  class was present 
at compile time but not available on run-time.  This is normally occurring due to any method invocation on a particular class which is part of library and not available on classpath in Java.
 This is also asked as common interview questions as  
“What is difference between NoClassDefFoundError and ClassNotFoundException Exception in Java”   or
“When do you see NoClassDefFoundError and ClassNotFoundException Exception in Java”. By the way NoClassDefFoundError can also comes due to various other reason
 like static initializer failure or class not visible to Classloaders in J2EE environment. read 3 ways to resolve NoClassDefFoundError in Java for complete details.


Summary of CLASSPATH in Java

1.      Classpath in Java is an environment variable used by Java 
Virtual machine to locate or find  class files in Java during class loading.

2.      You can override value of Classpath in Java defined by 
environment variable CLASSPATH by providing JVM command line option –cp or –classpath while running your application.

3.      If two classes with same name exist in Java Classpath 
then the class which comes earlier in Classpath will be picked by Java Virtual Machine.

4.      By default CLASSPATH in Java points to current directory
 denoted by "." and it will look for any class only in current directory.

5.      When you use the -jar command line  option to run your program as an executable JAR, then the Java CLASSPATH environment variable will be ignored, 
and also the -cp and -classpath switches will be ignored and In this case you can set your java classpath in
 the META-INF/MANIFEST.MF file by using the Class-Path attribute.

6.      In Unix of Linux Java Classpath contains names of directory with colon “:” separated , On Windows Java Classpath will be  semi colon “;” separated
 while if you defined java classpath in Manifest file those will be space separated.

7.       You can check value of classpath in java inside your application by looking at following system property “java.class.path”  System.getProperty("java.class.path")

Class-Path attribute is used to contain classpath inside manifest file. Also make sure that your manifest file must end with a blank line (carriage return or new line)
 , here is an example of java classpath in manifest file.

Main-Class: com.classpathexample.Demo_Classpath
Class-Path: lib/tibco.jar lib/log4j.jar

8.       It’s also important to note that path specified in manifest file is 
not absolute instead they are relative from application jar’s path. 
For example in above if your application jar file is in C:\test
 directory you must need a lib directory inside test and tibco.jar
 and log4j.jar inside that.

9.       ClassNotFoundException is an Exception and will be thrown when Java
 program dynamically tries to load a particular Class at Runtime and don’t
 find that on Java classpath due to result of Class.forName() or 
loadClass() method invocation.

10. NoClassDefFoundError comes when a particular class was present in Java Classpath during compile time but not available during runtime on Classpath in Java.

I hope you find this Java Classpath tutorial useful , 
please let me know if you have any doubt or any question
 related to "How to set classpath for java" 
and I would be happy to answer :) keep learning. Your
 suggestions and comments are always welcome. 
 If you like to read UNIX command tips you may find  10 
tips of using find command in Linux ,  10 tips to increase
 speed on Unix command and  10 
basic networking Commands in Unix useful. That's all on What
 is Classpath in Java, How Classpath works in Java, How to set 
Classpath in Java on Windows 
and Linux and how to deal with Classpath issues in Java.

How can i generate Excel (.XLS) file in Apache ofbiz by Using Apache POI

For that i have writtten Java Event in Apache ofbiz. The complete code and Step i have mentioned below

1. Enter below code in Controller.xml 

 <request-map uri="paymentRecieptReport.xls">
         <security https="true" auth="true"/>
    <event type="java" path="org.ofbiz.accounting.reports.PaymentRecieptReport" invoke="createPayementRecieptReport" />
         <response name="success" type="view" value="paymentRecieptReport"/>
         <response name="error" type="view" value="paymentRecieptReport"/>
    </request-map>

    <view-map name="paymentRecieptReport" type="screen" page="component://accounting/widget/CommonScreens.xml#paymentRecieptReport"/>


2. Write below java code for generate .XLS file in Java event code

package org.ofbiz.accounting.reports;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javolution.util.FastList;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
public class PaymentRecieptReport {
	

	public static ArrayList<HashMap> getPaymentRecieptList(GenericDelegator delegator, List<GenericValue>  paymentList)
	{
		ArrayList<HashMap>  finalList=new ArrayList<HashMap>();
		
		
		for(int i=0; i<paymentList.size(); i++)
		{
			String paymentId="";
			String paymentMethodId="";
			HashMap map= new HashMap();
			
			GenericValue payment = paymentList.get(i);
			paymentId=payment.getString("paymentId");
			paymentMethodId=payment.getString("paymentMethodId");
			map.put("paymentId", payment.getString("paymentId"));
			map.put("effectiveDate", payment.getString("effectiveDate"));
			map.put("checkNumber", payment.getString("checkNumber"));
			map.put("checkDate", payment.getString("checkDate"));
			map.put("checkAmount", payment.getString("amount"));
			map.put("modeOfPayment", payment.getString("modeOfPayment"));
			map.put("paymentRefNum", payment.getString("paymentRefNum"));
			
			String partyId="";
			if(payment.getString("outGoingPayment").equals("Y"))
			{
				map.put("partyId", payment.getString("partyIdTo"));
				partyId= payment.getString("partyIdTo");
				map.put("paymentType", "OUTGOING");
			
			}
			else
			{
				map.put("partyId", payment.getString("partyIdFrom"));
				partyId=payment.getString("partyIdFrom");
				map.put("paymentType", "INCOMING");
			}
			try
			{
		List<GenericValue>  partyList=delegator.findList("PartyNameView", EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId), null, null, null, false);
		
		if(partyList.size()>0)
		{
			GenericValue party=EntityUtil.getFirst(partyList);
			map.put("partyName", party.getString("groupName"));
			
			if(party.getString("groupName") ==null || party.getString("groupName")=="" )
			{
				try
				{
				List<GenericValue>  personList=delegator.findList("Person", EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId), null, null, null, false);
				if(personList.size()>0)
				{
					GenericValue person=EntityUtil.getFirst(personList);
					map.put("partyName", person.getString("firstName")+" "+person.getString("lastName"));
				}
				}
				catch(Exception ex)
				{
					
				}
			}
		}
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
				
			}
			
			
			try
			{
		List<GenericValue>  tdsList=delegator.findList("TdsHistory", EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId), null, null, null, false);
		if(tdsList.size()>0)
		{
			GenericValue tds=EntityUtil.getFirst(tdsList);
			map.put("tdsSection", tds.getString("sectionOfAct"));
			map.put("tdsGl", tds.getString("overrideGlAccountId"));
			map.put("tdsAmount", tds.getString("tdsAmount"));
			
		}
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
			
			String glId="";	
			String glName="";
			try
			{
			
			List<GenericValue>  glList=delegator.findList("PaymentMethod", EntityCondition.makeCondition("paymentMethodId", EntityOperator.EQUALS, paymentMethodId), null, null, null, false);
			if(glList.size()>0)
			{
			GenericValue gl=EntityUtil.getFirst(glList);
			glId=gl.getString("glAccountId");
			map.put("glAccountId",glId);
			}
			List<GenericValue>  glNameList=delegator.findList("GlAccount", EntityCondition.makeCondition("glAccountId", EntityOperator.EQUALS, glId), null, null, null, false);
			
			if(glNameList.size()>0)
			{
			GenericValue glNameValue=EntityUtil.getFirst(glNameList);
			glName=glNameValue.getString("accountName");
			map.put("glAccountIdName",glName);
			map.put("accountCode", glNameValue.getString("accountCode"));
			map.put("glDesc", glNameValue.getString("description"));
			}
			}
			catch(Exception ex)
			{
			ex.printStackTrace();	
			}
			
			finalList.add(map);
			
		}
		
		
		
		return finalList;
		
	}
	
	public static String createPayementRecieptReport(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
		List<GenericValue> paymentList = new FastList<GenericValue>();
		String fromDate=request.getParameter("fromDate");
		String toDate=request.getParameter("toDate");
		System.out.println("Fromdate   : "+fromDate +"  :"+toDate);
		String orgainsationParty=request.getParameter("organizationPartyId");
		List<String> errors = new ArrayList<String>();
		request.setAttribute("_ERROR_MESSAGE_LIST_", errors);
		System.out.println("coming party id "+orgainsationParty);
		if(orgainsationParty ==null || orgainsationParty=="")
		{
			errors.add("Please select organisation id");
			return "success";
		}
		
		
		if(!request.getParameter("fromDate").isEmpty())
		{
			
			if(request.getParameter("toDate").isEmpty())
			{
				errors.add("Please select ToDate");
				return "success";
			}
		}
		
		if(!request.getParameter("toDate").isEmpty())
		{
			
			if(request.getParameter("fromDate").isEmpty())
			{
				errors.add("Please select FromDate");
				return "success";
			}
		}
		
		
	String companyName="";
		try
		{
	 List<GenericValue>  partyList=delegator.findList("PartyNameView", EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, orgainsationParty), null, null, null, false);
	if(partyList.size()>0)
	{
		GenericValue party=EntityUtil.getFirst(partyList);
		companyName= party.getString("groupName");
		
	}
		}
		catch(Exception ex)
		{
		ex.printStackTrace();	
		}
		
		EntityExpr dateRange = null;
		try
		{
		EntityConditionList<EntityExpr> exprs = EntityCondition.makeCondition(UtilMisc.toList(
	    EntityCondition.makeCondition("partyIdFrom", EntityOperator.EQUALS, orgainsationParty),
	    EntityCondition.makeCondition("partyIdTo", EntityOperator.EQUALS, orgainsationParty)), EntityOperator.OR);
		
		 if(!request.getParameter("fromDate").isEmpty() && !request.getParameter("toDate").isEmpty()){
			 fromDate=fromDate+" 23:59:59";
			 toDate=toDate+" 23:59:59";
			  EntityConditionList<EntityExpr> dateRangeForReport = EntityCondition.makeCondition(UtilMisc.toList(
		                EntityCondition.makeCondition("effectiveDate", EntityOperator.GREATER_THAN_EQUAL_TO,fromDate),
		                EntityCondition.makeCondition("effectiveDate", EntityOperator.LESS_THAN_EQUAL_TO, toDate)), EntityOperator.AND);
			  dateRange = EntityCondition.makeCondition(exprs, EntityOperator.AND, dateRangeForReport);
			  paymentList=delegator.findList("Payment", dateRange, null, null, null, false); 
			  }
		 else
		 {
			 paymentList=delegator.findList("Payment", exprs, null, null, null, false);
		 }
	//	paymentList=delegator.findList("Payment", exprs, null, null, null, false);
		}
		
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		ArrayList finalList=new ArrayList();
		finalList=getPaymentRecieptList(delegator,paymentList );
	    System.out.println("size of payment list is   "+paymentList.size());
	    String periodDate="";
		if(!request.getParameter("fromDate").isEmpty() && !request.getParameter("toDate").isEmpty())
		 {
			periodDate= request.getParameter("fromDate").toString()+" to "+request.getParameter("toDate");
		 }
		else
		{
			periodDate ="         to                  ";
		}
 
 ///////////////////////////////*******************************************
		// code to create a fixed excel start
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("Payment Reciept Report");
		HSSFCellStyle style = wb.createCellStyle();
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		HSSFCellStyle styleHeader = wb.createCellStyle();
		HSSFFont font = wb.createFont();
		String fontName = "Arial";
		font.setFontName(fontName);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setFontHeight((short) 200);
		styleHeader.setFont(font);
		CellRangeAddress region = new CellRangeAddress(1, 1, 0, 6);
		sheet.addMergedRegion(region);
		CellRangeAddress region1 = new CellRangeAddress(2, 2, 0, 6);
		sheet.addMergedRegion(region1);
		CellRangeAddress region2 = new CellRangeAddress(3, 3, 0, 6);
		sheet.addMergedRegion(region2);
		
		HSSFRow companyheader = sheet.createRow(1);
		HSSFCell companyheaderCell = companyheader.createCell(0);
		HSSFCell companyheaderCell_1 = companyheader.createCell(1);
		companyheaderCell_1.setCellStyle(styleHeader);
		HSSFCell companyheaderCell_2 = companyheader.createCell(2);
		companyheaderCell_2.setCellStyle(styleHeader);
		HSSFCell companyheaderCell_3 = companyheader.createCell(3);
		companyheaderCell_3.setCellStyle(styleHeader);
		HSSFCell companyheaderCell_4 = companyheader.createCell(4);
		companyheaderCell_4.setCellStyle(styleHeader);
		HSSFCell companyheaderCell_5 = companyheader.createCell(5);
		companyheaderCell_5.setCellStyle(styleHeader);
		companyheader.setHeight((short) 600);
		HSSFRichTextString companyheaderCode = new HSSFRichTextString(companyName);
		companyheaderCell.setCellValue(companyheaderCode);
		companyheaderCell.setCellStyle(styleHeader);
		
		
		HSSFRow header = sheet.createRow(2);
		HSSFCell headerCell = header.createCell(0);
		HSSFCell headerCell_1 = header.createCell(1);
		headerCell_1.setCellStyle(styleHeader);
		HSSFCell headerCell_2 = header.createCell(2);
		headerCell_2.setCellStyle(styleHeader);
		HSSFCell headerCell_3 = header.createCell(3);
		headerCell_3.setCellStyle(styleHeader);
		HSSFCell headerCell_4 = header.createCell(4);
		headerCell_4.setCellStyle(styleHeader);
		HSSFCell headerCell_5 = header.createCell(5);
		headerCell_5.setCellStyle(styleHeader);
		header.setHeight((short) 300);
		HSSFRichTextString headerCode = new HSSFRichTextString("Payment Register (Cash & Bank)");
		headerCell.setCellValue(headerCode);
		headerCell.setCellStyle(styleHeader);

		HSSFRow ledger = sheet.createRow(3);
		HSSFCell ledgerCell = ledger.createCell(0);
		HSSFCell ledgerCell_1 = ledger.createCell(1);
		ledgerCell_1.setCellStyle(styleHeader);
		HSSFCell ledgerCell_2 = ledger.createCell(2);
		ledgerCell_2.setCellStyle(styleHeader);
		HSSFCell ledgerCell_3 = ledger.createCell(3);
		ledgerCell_3.setCellStyle(styleHeader);
		HSSFCell ledgerCell_4 = ledger.createCell(4);
		ledgerCell_4.setCellStyle(styleHeader);
		HSSFCell ledgerCell_5 = ledger.createCell(5);
		ledgerCell_5.setCellStyle(styleHeader);

		ledger.setHeight((short) 300);
		HSSFRichTextString ledgerCode = new HSSFRichTextString("Period :"+periodDate);
		ledgerCell.setCellValue(ledgerCode);
		ledgerCell.setCellStyle(styleHeader);

	
		HSSFRow period = sheet.createRow(4);
		HSSFCell periodCell = period.createCell(0);

		HSSFCell periodCell_1 = ledger.createCell(1);
		periodCell_1.setCellStyle(styleHeader);
		HSSFCell periodCell_2 = ledger.createCell(2);
		periodCell_2.setCellStyle(styleHeader);
		HSSFCell periodCell_3 = ledger.createCell(3);
		periodCell_3.setCellStyle(styleHeader);
		HSSFCell periodCell_4 = ledger.createCell(4);
		periodCell_4.setCellStyle(styleHeader);
		HSSFCell periodCell_5 = ledger.createCell(5);
		periodCell_5.setCellStyle(styleHeader);

		/*period.setHeight((short) 300);
		HSSFRichTextString periodString = new HSSFRichTextString("To Date :"+toDate);
		periodCell.setCellValue(periodString);
		periodCell.setCellStyle(styleHeader);
*/
		HSSFCellStyle dataStyleHeader = wb.createCellStyle();
		HSSFFont headerFont = wb.createFont();
		String headerFontName = "Arial";
		headerFont.setFontName(headerFontName);
		headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headerFont.setFontHeight((short) 200);
		dataStyleHeader.setFont(headerFont);

	
		HSSFRow TableHeader = sheet.createRow(7);
		HSSFCell custCodeCell = TableHeader.createCell(0);
		HSSFRichTextString custCodeString = new HSSFRichTextString("S.NO");
		custCodeCell.setCellValue(custCodeString);
		custCodeCell.setCellStyle(dataStyleHeader);

	    // Payment outgoing/Incoming
		HSSFCell paymentTypeCell = TableHeader.createCell(1);
		HSSFRichTextString docTypeHeaderpaymentTypeCellString = new HSSFRichTextString("Payment Type");
		paymentTypeCell.setCellValue(docTypeHeaderpaymentTypeCellString);
		paymentTypeCell.setCellStyle(dataStyleHeader);
		
		// HSSFRow docTypeHeader = sheet.createRow(12);
		HSSFCell docTypeHeaderCell = TableHeader.createCell(2);
		HSSFRichTextString docTypeHeaderCellString = new HSSFRichTextString("Bank / Cash GL");
		docTypeHeaderCell.setCellValue(docTypeHeaderCellString);
		docTypeHeaderCell.setCellStyle(dataStyleHeader);

		// HSSFRow docNoHeader = sheet.createRow(12);
		HSSFCell docNoHeaderCell = TableHeader.createCell(3);
		HSSFRichTextString docNoHeaderCellString = new HSSFRichTextString("Bank / Cash Name");
		docNoHeaderCell.setCellValue(docNoHeaderCellString);
		docNoHeaderCell.setCellStyle(dataStyleHeader);

		// HSSFRow referenceNoHeader = sheet.createRow(12);
		HSSFCell referenceNoHeaderCell = TableHeader.createCell(4);
		HSSFRichTextString referenceNoHeaderString = new HSSFRichTextString("Ch No.");
		referenceNoHeaderCell.setCellValue(referenceNoHeaderString);
		referenceNoHeaderCell.setCellStyle(dataStyleHeader);

		// HSSFRow referenceDateHeader = sheet.createRow(12);
		HSSFCell referenceDateHeaderCell = TableHeader.createCell(5);
		HSSFRichTextString referenceDateHeaderString = new HSSFRichTextString("Ch. Date");
		referenceDateHeaderCell.setCellValue(referenceDateHeaderString);
		referenceDateHeaderCell.setCellStyle(dataStyleHeader);

		// HSSFRow departmentHeader = sheet.createRow(12);
		HSSFCell departmentHeaderCell = TableHeader.createCell(6);
		HSSFRichTextString departmentHeaderString = new HSSFRichTextString("Party ID");
		departmentHeaderCell.setCellValue(departmentHeaderString);
		departmentHeaderCell.setCellStyle(dataStyleHeader);

		// HSSFRow descriptionHeader = sheet.createRow(12);
		HSSFCell descriptionHeaderCell = TableHeader.createCell(7);
		HSSFRichTextString descriptionHeaderString = new HSSFRichTextString("Party Name");
		descriptionHeaderCell.setCellValue(descriptionHeaderString);
		descriptionHeaderCell.setCellStyle(dataStyleHeader);

		// HSSFRow drHeader = sheet.createRow(12);
		HSSFCell drCell = TableHeader.createCell(8);
		HSSFRichTextString drString = new HSSFRichTextString("GL Code");
		drCell.setCellValue(drString);
		drCell.setCellStyle(dataStyleHeader);

		// HSSFRow crHeader = sheet.createRow(12);
		HSSFCell crCell = TableHeader.createCell(9);
		HSSFRichTextString crString = new HSSFRichTextString("GL Desc");
		crCell.setCellValue(crString);
		crCell.setCellStyle(dataStyleHeader);
		
		HSSFCell tdsCell = TableHeader.createCell(10);
		HSSFRichTextString tdsString = new HSSFRichTextString("TDS Section");
		tdsCell.setCellValue(tdsString);
		tdsCell.setCellStyle(dataStyleHeader);
		
		HSSFCell tdsCell1 = TableHeader.createCell(11);
		HSSFRichTextString tdsString1 = new HSSFRichTextString("TDS GL");
		tdsCell1.setCellValue(tdsString1);
		tdsCell1.setCellStyle(dataStyleHeader);
		HSSFCell tdsCell2 = TableHeader.createCell(12);
		HSSFRichTextString tdsString2 = new HSSFRichTextString("Doc Date");
		tdsCell2.setCellValue(tdsString2);
		tdsCell2.setCellStyle(dataStyleHeader);
		
		HSSFCell tdsCell3 = TableHeader.createCell(13);
		HSSFRichTextString tdsString3 = new HSSFRichTextString("Doc Number");
		tdsCell3.setCellValue(tdsString3);
		tdsCell3.setCellStyle(dataStyleHeader);
		
		HSSFCell tdsCell4 = TableHeader.createCell(14);
		HSSFRichTextString tdsString4 = new HSSFRichTextString("Reference No.");
		tdsCell4.setCellValue(tdsString4);
		tdsCell4.setCellStyle(dataStyleHeader);
		
		
		HSSFCell tdsCell5 = TableHeader.createCell(15);
		HSSFRichTextString tdsString5 = new HSSFRichTextString("Mode of Payment");
		tdsCell5.setCellValue(tdsString5);
		tdsCell5.setCellStyle(dataStyleHeader);
		
		HSSFCell tdsCell6 = TableHeader.createCell(16);
		HSSFRichTextString tdsString6 = new HSSFRichTextString("TDS Amount");
		tdsCell6.setCellValue(tdsString6);
		tdsCell6.setCellStyle(dataStyleHeader);
		
		HSSFCell tdsCell7 = TableHeader.createCell(17);
		HSSFRichTextString tdsString7 = new HSSFRichTextString("Cheque Amount");
		tdsCell7.setCellValue(tdsString7);
		tdsCell7.setCellStyle(dataStyleHeader);
		
		/*HSSFCell tdsCell8 = TableHeader.createCell(17);
		HSSFRichTextString tdsString8 = new HSSFRichTextString("glDesc");
		tdsCell8.setCellValue(tdsString8);
		tdsCell8.setCellStyle(dataStyleHeader);*/
		
		HSSFCell tdsCell9 = TableHeader.createCell(18);
		HSSFRichTextString tdsString9= new HSSFRichTextString("Credit / Return");
		tdsCell9.setCellValue(tdsString9);
		tdsCell9.setCellStyle(dataStyleHeader);
		HSSFCell tdsCell10 = TableHeader.createCell(19);
		HSSFRichTextString tdsString10 = new HSSFRichTextString("Reconcilation Status");
		tdsCell10.setCellValue(tdsString10);
		tdsCell10.setCellStyle(dataStyleHeader);
		//sheet.createFreezePane(6, 8);
        int sNo=1;
        int RowNo=8;	      
        for(int i=0; i<finalList.size(); i++)
        {
        	HashMap map= (HashMap) finalList.get(i);
        	int cell=0;
        	HSSFRow runningHeader = sheet.createRow(RowNo);
        	
  		    HSSFCell sNoCell = runningHeader.createCell(cell);
  		    HSSFRichTextString sNoString=new HSSFRichTextString(Integer.toString(sNo));
  		    sNoCell.setCellValue(sNoString);
  		    cell++;
  		    
  		    
  		    HSSFCell paymentTypeValueCell = runningHeader.createCell(cell);
		    HSSFRichTextString paymentTypeValueString=new HSSFRichTextString((String) map.get("paymentType"));
		    paymentTypeValueCell.setCellValue(paymentTypeValueString);
		    cell++;
        	
  		    HSSFCell glAccountCell = runningHeader.createCell(cell);
		    HSSFRichTextString glAccountString=new HSSFRichTextString((String) map.get("glAccountId"));
		    glAccountCell.setCellValue(glAccountString);
		    cell++;
		    
		    HSSFCell glAccountNameCell = runningHeader.createCell(cell);
		    HSSFRichTextString glAccountNameString=new HSSFRichTextString((String) map.get("glAccountIdName"));
		    glAccountNameCell.setCellValue(glAccountNameString);
		    cell++;
		    
		    HSSFCell chNoCell = runningHeader.createCell(cell);
		    HSSFRichTextString chNoString=new HSSFRichTextString((String) map.get("checkNumber"));
		    chNoCell.setCellValue(chNoString);
		    cell++;
		    
		    HSSFCell chNoDateCell = runningHeader.createCell(cell);
		    HSSFRichTextString chNoDateString=new HSSFRichTextString((String) map.get("checkDate"));
		    chNoDateCell.setCellValue(chNoDateString);
		    cell++;
		    HSSFCell partyIdCell = runningHeader.createCell(cell);
		    HSSFRichTextString partyIdString=new HSSFRichTextString((String) map.get("partyId"));
		    partyIdCell.setCellValue(partyIdString);
		    cell++;
		    
		    HSSFCell partyNameCell = runningHeader.createCell(cell);
		    HSSFRichTextString partyNameString=new HSSFRichTextString((String) map.get("partyName"));
		    partyNameCell.setCellValue(partyNameString);
		    cell++;
		    
		    HSSFCell glCodeCell = runningHeader.createCell(cell);
		    HSSFRichTextString glCodeString=new HSSFRichTextString("");
		    glCodeCell.setCellValue(glCodeString);
		    cell++;
		    
		    HSSFCell glDescCell = runningHeader.createCell(cell);
		    HSSFRichTextString glDescString=new HSSFRichTextString("");
		    glDescCell.setCellValue(glDescString);
		    cell++;
		    
		    HSSFCell tdsSectionCell = runningHeader.createCell(cell);
		    HSSFRichTextString tdsSectionString=new HSSFRichTextString((String) map.get("tdsSection"));
		    tdsSectionCell.setCellValue(tdsSectionString);
		    cell++;
		    
		    
		    HSSFCell tdsGlCell = runningHeader.createCell(cell);
		    HSSFRichTextString tdsGlString=new HSSFRichTextString((String) map.get("tdsGl"));
		    tdsGlCell.setCellValue(tdsGlString);
		    cell++;
		    
		    HSSFCell docDateCell = runningHeader.createCell(cell);
		    HSSFRichTextString docDateString=new HSSFRichTextString((String) map.get("effectiveDate"));
		    docDateCell.setCellValue(docDateString);
		    cell++;
		    
		    HSSFCell docNumberCell = runningHeader.createCell(cell);
		    HSSFRichTextString docNumberString=new HSSFRichTextString((String) map.get("paymentId"));
		    docNumberCell.setCellValue(docNumberString);
		    cell++;
		    
		    HSSFCell refnoCell = runningHeader.createCell(cell);
		    HSSFRichTextString refnoString=new HSSFRichTextString((String) map.get("paymentRefNum"));
		    refnoCell.setCellValue(refnoString);
		    cell++;
		    
		    HSSFCell modePaymentCell = runningHeader.createCell(cell);
		    HSSFRichTextString modePaymentString=new HSSFRichTextString((String) map.get("modeOfPayment"));
		    modePaymentCell.setCellValue(modePaymentString);
		    cell++;
		    
		    HSSFCell tdsAmountCell = runningHeader.createCell(cell);
		    HSSFRichTextString tdsAmountString=new HSSFRichTextString((String) map.get("tdsAmount"));
		    tdsAmountCell.setCellValue(tdsAmountString);
		    cell++;
		    
		    HSSFCell checkAmountCell = runningHeader.createCell(cell);
		    HSSFRichTextString checkAmountString=new HSSFRichTextString((String) map.get("checkAmount"));
		    checkAmountCell.setCellValue(Double.valueOf((String) map.get("checkAmount")));
		    cell++;
		    
		    HSSFCell descCell = runningHeader.createCell(cell);
		    HSSFRichTextString descString=new HSSFRichTextString((String) map.get("desc"));
		    descCell.setCellValue(descString);
		    cell++;
		    
		    HSSFCell creditReturnCell = runningHeader.createCell(cell);
		    HSSFRichTextString creditReturnString=new HSSFRichTextString("");
		    creditReturnCell.setCellValue(creditReturnString);
		    cell++;
		    
		    HSSFCell reconsilationCell = runningHeader.createCell(cell);
		    HSSFRichTextString reconsilationString=new HSSFRichTextString("");
		    reconsilationCell.setCellValue(reconsilationString);
		    cell++;
      	
        	
  		  RowNo++;
  		  sNo++; 
        }
        
		

				String serverPath_1 = System.getProperty("ofbiz.home");
				String serverFilePath = serverPath_1
						+ "/applications/documents/register.xls";

				FileOutputStream fileOut = new FileOutputStream(serverFilePath);
				wb.write(fileOut);
				fileOut.close();
				// Code to save a file in document directory end

				// Code To download a file
				// Map<String, Object> parameters = UtilHttp.getParameterMap(request);
				String FileName = (String) request.getParameter("FileName");
				FileName = "register.xls";

				OutputStream os;
				try {
					os = response.getOutputStream();
					String mimeType = "application/octet-stream";
					response.setContentType(mimeType);
					String serverPath = System.getProperty("ofbiz.home");
					serverPath = serverPath + "/applications/documents/" + FileName;
					File file = new File(serverPath);
					InputStream i = new FileInputStream(file);
					int readBytes = 0;

					while ((readBytes = i.read()) != -1) {
						os.write(readBytes);
					}
					request.setAttribute("_EVENT_MESSAGE_",
							"File Transfered Successfully");

					i.close();

					os.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
				}
				// creating a fixed excel end

		
		return "success";
	}

}