Tuesday, August 31, 2010

Java : How to throw custom Exception

In java many times we required to throw our own custom Exception. We can throw our custom Exception by creation our own Exception class which will extend from class java.lang.Exception.

Before going to example lets look at few points about Exception Handling from book "Sun Certified Java Programmer SCJP 5" by Kathy sierra.

Handling Exceptions
  • Exceptions come in two flavors: checked and unchecked.
  • Checked exceptions include all subtypes of Exception, excluding classes
    that extend RuntimeException.
  • Checked exceptions are subject to the handle or declare rule; any method
    that might throw a checked exception (including methods that invoke methods
    that can throw a checked exception) must either declare the exception
    using throws, or handle the exception with an appropriate try/catch.
  • Subtypes of Error or RuntimeException are unchecked, so the compiler
    doesn't enforce the handle or declare rule. You're free to handle them, or to
    declare them, but the compiler doesn't care one way or the other.
  • If you use an optional finally block, it will always be invoked, regardless of
    whether an exception in the corresponding try is thrown or not, and regardless
    of whether a thrown exception is caught or not.
  • The only exception to the finally-will-always-be-called rule is that a finally
    will not be invoked if the JVM shuts down. That could happen if code
    from the try or catch blocks calls System.exit().
  • Just because finally is invoked does not mean it will complete. Code in the
    finally block could itself raise an exception or issue a System.exit().
  • Uncaught exceptions propagate back through the call stack, starting from
    the method where the exception is thrown and ending with either the first
    method that has a corresponding catch for that exception type or a JVM
    shutdown (which happens if the exception gets to main(), and main() is
    "ducking" the exception by declaring it).
  • You can create your own exceptions, normally by extending Exception or
    one of its subtypes. Your exception will then be considered a checked exception,
    and the compiler will enforce the handle or declare rule for that exception.
  • All catch blocks must be ordered from most specific to most general.
    If you have a catch clause for both IOException and Exception, you must
    put the catch for IOException first in your code. Otherwise, the IOException
    would be caught by catch(Exception e), because a catch argument
    can catch the specified exception or any of its subtypes! The compiler will
    stop you from defining catch clauses that can never be reached.
  • Some exceptions are created by programmers, some by the JVM.

Lets see a simple example which will throw a custom Exception.

In this example we have a method acceptsEvenNumber(int number) which accepts only even number, it it encounters odd number it throws our custom Exception ie "MyException".
Here our class MyException extends java.lang.Exception also observe the constructor MyException(String message) which calls its super constructor.

To know more look API.

/* MyException.java */

public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }
  
    //This method throws custom Exception
    public static void acceptsEvenNumber(int number) throws MyException {
      
        if(number %2 == 0) {
          
            System.out.println("It is Even number");
        }
        else {
          
            throw new MyException("Odd number not allowed");
        }
      
    }

    public static void main(String[] args) {
      
        try {
           

            //acceptsEvenNumber(23); //odd number
            acceptsEvenNumber(22); //even number
          
        } catch (MyException e) {
          
            e.printStackTrace();
        }
    }

}



Output

When Even Number

#>java MyException
It is Even number

When Odd Number

#>java MyException
MyException: Odd number not allowed
        at MyException.acceptsEvenNumber(MyException.java:16)
        at MyException.main(MyException.java:25)

Friday, August 27, 2010

Java : Simple program to get system properties

If you want to know your system properties or you want to create properties file listing all properties of your system. Lets see a simple java program which lists all system properties of your computer.

/* MySystemProperties.java */

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class MySystemProperties {
  
    public static void main(String[] args) {
      
        System.out.println("# My System Properties");
      
        Properties properties = System.getProperties();
      
        Set<String> propertiesSet = properties.stringPropertyNames();
      
        Iterator<String> iterator =  propertiesSet.iterator();
      
        String name;
      
        while (iterator.hasNext()) {
          
            name = iterator.next();
            System.out.println(name+" = "+properties.getProperty(name));
        }
      
    }

}


Output (output may differ depending on your computers properties)

# My System Properties
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jre6\bin
java.vm.version = 17.0-b17
java.vm.vendor = Sun Microsystems Inc.
java.vendor.url = http://java.sun.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
sun.java.launcher = SUN_STANDARD
sun.os.patch.level = Service Pack 3
java.vm.specification.name = Java Virtual Machine Specification
user.dir = C:\MY\Code\Test
java.runtime.version = 1.6.0_21-b07
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Program Files\Java\jre6\lib\endorsed
os.arch = x86
java.io.tmpdir = c:\temp\
line.separator =

java.vm.specification.vendor = Sun Microsystems Inc.
user.variant =
os.name = Windows XP
sun.jnu.encoding = Cp1252
java.library.path = C:\WINXP\system32;.;C:\WINXP\Sun\Java\bin;C:\WINXP\system32;C:\WINXP;C:\WINXP\system32;C:\WINXP\;C:\WINXP\System32\Wbem;C:\WINXP\system32\nls;C:\WINXP\system32\nls\ENGLISH;C:\Program Files\UltraEdit\;C:\Program Files\CA\SC\CAWIN\;C:\Program Files\IBM\Personal Communications\;C:\Program Files\IBM\Trace Facility\;C:\WINXP\system32;C:\WINXP;C:\WINXP\System32\Wbem;C:\WINXP\system32\nls;C:\WINXP\system32\nls\ENGLISH;c:\Program Files\Novell\ZENworks\;C:\PROGRA~1\CA\SC\CAM\bin;C:\Program Files\CA\DSM\bin;C:\Program Files\SSH\SecureCRT\;C:\Program Files\SSH\SecureFX\;C:\Program Files\Rational\common;C:\Program Files\SQLLIB\FUNCTION;C:\Program Files\SQLLIB\help\;C:\Program Files\SQLLIB\samples\repl\;C:\Program Files\IBM\IMNNQ\;C:\Program Files\SQLLIB\bin\;C:\PROGRA~1\IBM\SQLLIB\BIN;C:\PROGRA~1\IBM\SQLLIB\FUNCTION;C:\Program Files\Java\jre6\bin;C:\Program Files\Java\jdk1.6.0_21\bin;C:\Program Files\Java\jdk1.6.0_21\bin;C:\Program Files\Java\jre6\bin;Z:.;Y:.;X:.
java.specification.name = Java Platform API Specification
java.class.version = 50.0
sun.management.compiler = HotSpot Client Compiler
os.version = 5.1
user.home = C:\Documents and Settings\madan
user.timezone =
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.6
user.name = madan
java.class.path = .
java.vm.specification.version = 1.0
sun.arch.data.model = 32
java.home = C:\Program Files\Java\jre6
java.specification.vendor = Sun Microsystems Inc.
user.language = en
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode, sharing
java.version = 1.6.0_21
java.ext.dirs = C:\Program Files\Java\jre6\lib\ext;C:\WINXP\Sun\Java\lib\ext
sun.boot.class.path = C:\Program Files\Java\jre6\lib\resources.jar;C:\Program Files\Java\jre6\lib\rt.jar;C:\Program Files\Java\jre6\lib\sunrsasign.jar;C:\Program Files\Java\jre6\lib\jsse.jar;C:\Program Files\Java\jre6\lib\jce.jar;C:\Program Files\Java\jre6\lib\charsets.jar;C:\Program Files\Java\jre6\classes
java.vendor = Sun Microsystems Inc.
file.separator = \
java.vendor.url.bug = http://java.sun.com/cgi-bin/bugreport.cgi
sun.cpu.endian = little
sun.io.unicode.encoding = UnicodeLittle
sun.desktop = windows
sun.cpu.isalist = pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86

Thursday, August 26, 2010

Java Decompiler : Simple Java Program to decompile .class files

I was wondering is there a java program to decompile a .class file of another java program or itself. I searched on internet but I didn't found any, latter I decided to write my own. but how..... lets see.

When we compile a java file, JVM creates .class file. But imagine you have a .class and you need to create its source .java file, in such case you can use java decompiler which creates .java file of a .class file.


However many times decompiled .java file is not 100% accurate but still more or less you will get idea about what the java file consist of.

There are many java decompiler available on internet.We will use JAD Java Decompiler to decompile our .class files because it can be easily integrated with our Java program.

To know more about JAD Decompiler click here, Also you can download latest version of JAD Decompiler. In our example we are using JAD 1.5.8 version ie jad158g.win.zip. Visit  http://www.varaneckas.com/jad to know more.

Installation

Unzip jad.zip file into any appropriate directory on your hard drive.
This will create two files:

    * an executable file named 'jad.exe' (Windows 9x/NT/2000) or 'jad' (UNIX)
    * README file 'Readme.txt', which contains the short user's manual

Note : You need to add jad.exe in your CLASS PATH
Simple way just put jad.exe in your java path For Eg : C:\Program Files\Java\jdk1.6.0_21\bin\jad.exe

To test your installation just type 'jad' in your command prompt, it should produce below output.




Now Lets see the decompile process and its command.

For example, lets say we have Test.class to which we need to decompile.

C:\Jad>jad Test.class
Parsing Test.class... Generating Test.jad

This will create Test.jad file which contains java code, don't worry .jad is default extension.

C:\Jad>jad -s .java Test.class
Parsing Test.class... Generating Test.java

using -s you can provide extension of the file. This will create Test.java.

Also you can provide destination folder where you want to decomiple the .class file.

C:\Jad>jad -s .java -d C:\Dest Test.class
Parsing Test.class... Generating C:\Dest\Test.java

This will create Test.java in our desire destination folder. To know more see the 'Readme.txt' file.

 Now we can write our java program which will use above mentioned system commands and can be used as Java decompiler program.

/* JadExample.java */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JadExample {

    public void runSystemCommand(String command) {
       
        try {
            Process p = Runtime.getRuntime().exec(command);
           
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
           
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
           
            String s = "";
           
            System.out.println("command :: "+command);
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
           
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }           
           
        } catch (IOException e) {
           
            e.printStackTrace();
        }       
    }
   
    public void decompile(String srcClassFile,String destFolder) {
       
        runSystemCommand("jad -s .java -d "+destFolder+" "+srcClassFile);
       
    }
   
    public static void main(String[] args) {
       
        JadExample obj = new JadExample();
       
        //obj.decompile("Test.class", "."); //Current directory
        obj.decompile("Test.class", "C:\\Test");
    }

}





Run the above program and see the output. If you like it do write comments or mail me madan712@gmail.com

Monday, August 23, 2010

Java : Simple Properties Example

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

Properties class extends Hashtable so methods like get, hashCode, isEmpty, keys, keySet, put, putAll, rehash, remove, size can be applied to Properties class.

Lets see a simple Java Properties counter example, here we will read count values ie load value from a  data.properties file and just increment the value and again store in data.properties file. Each time we run this example it increment the count value.

 /* PropertiesExample.java */

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {

        public static void main(String[] args) {
      
            Properties prop = new Properties();
           
            //load Properties prop from a file
            try {
                prop.load(new FileInputStream("data.properties"));
               
            } catch (IOException e) {
                System.out.println("IOException :: "+e);
            }
           
            //get values of count
            String count = prop.getProperty("count");
           
            System.out.println("count = "+count);
           
            //just incrementing value of count
            int newCount = Integer.parseInt(count);
            newCount++;
           
            //set the new value of count
            prop.setProperty("count",""+newCount);
           
            //save the file
            try {
                prop.store(new FileOutputStream("data.properties"),"This is a simple example");
               
            } catch (IOException e) {
                System.out.println("IOException :: "+e);
            }
           
    }

}


data.properties

#This is a simple example
#Mon Aug 23 13:05:22 IST 2010
count=12

Output










  














However you can also store / load the data in XML (.xml) file rather than .properties file using storeToXML(OutputStream os, String comment)and loadFromXML(InputStream in) method.

Also you can iterate through all parameters in Properties using propertyNames()and stringPropertyNames().

Lets look at API for more details

For eg. Data.xml
 
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>This is a simple example</comment>
<entry key="count">10</entry>
</properties>



properties file example

# this is a comment
! this is also a comment
a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line
   \ continuation line
d.e.f = another string 


Friday, August 20, 2010

Java : Simple program to Run System Commands

Many times we require to execute system command using java program. Java do support to this using Process class, we can execute command on Runtime object using exec("command") method.

Eg : Process p = Runtime.getRuntime().exec(command);

Lets see a simple java program to run system command. directly you can this program and see the output


/* RunSystemCommand.java */

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunSystemCommand {

    public void runCommand(String command) {
       
        try {
            Process p = Runtime.getRuntime().exec(command);
           
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
           
            BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
           
            String s = "";

            System.out.println("Output stream :: \n");
            // reading output stream of the command
            while ((s = inputStream.readLine()) != null) {
                System.out.println(s);
            }
           
            // reading any errors of the command
            System.out.println("Error stream (if any) :: \n");
            while ((s = errorStream.readLine()) != null) {
                System.out.println(s);
            }
           
        } catch (Exception e) {
           
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
       
        RunSystemCommand obj = new RunSystemCommand();
       
        //Example system commands
        //obj.runCommand("cmd /c copy c:\\java\\Test.java d:\\data");
        //obj.runCommand("javac");   
       
        obj.runCommand("cmd /c dir");

    }

}


Output


Friday, August 13, 2010

Add google map to your Website/Blog in 2 steps

Many time you need to embed google map in your website or blogs, you can do simple way in just two steps.

1. Go to google map, choose your desire location. Click on Link and get the HTML code.





























2. Add the given code in your page.


Here is the output, as show below


View Larger Map

Monday, August 9, 2010

Java : Simple Quartz Job Scheduler

Quartz

Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may executed virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.

To know more click here

What Can Quartz Do For You?

If your application has tasks that need to occur at given moments in time, or if your system has recurring maintenance jobs then Quartz may be your ideal solution.

Sample uses of job scheduling with Quartz:

* Driving Process Workflow: As a new order is initially placed, schedule a Job to fire in exactly 2 hours, that will check the status of that order, and trigger a warning notification if an order confirmation message has not yet been received for the order, as well as changing the order's status to 'awaiting intervention'.
* System Maintenance: Schedule a job to dump the contents of a database into an XML file every business day (all weekdays except holidays) at 11:30 PM.
* Providing reminder services within an application.

Refrence : http://www.quartz-scheduler.org/


In our example we used Quartz 1.8.3

Download quartz-1.8.3.tar

Simple Example

In our example we will create a simple job class ie(MyJob.java) which will print a date time on console after every 1 minute.

Below is our Quartz class (QuartzExample.java), to run this example you need to set below files in class path :
quartz-1.8.3.jar
log4j-1.2.14.jar
slf4j-api-1.5.10.jar
slf4j-log4j12-1.5.10.jar

Download quartz-1.8.3.tar


//QuartzExample.java

import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzExample {

    public static void main(String[] args) throws SchedulerException {
      
        SchedulerFactory schedFact = new StdSchedulerFactory();
      
        Scheduler scheduler = schedFact.getScheduler();
      
        JobDetail job = new JobDetail("job1",scheduler.DEFAULT_GROUP, quartz.MyJob.class);
      
        Trigger trigger = new SimpleTrigger("trigger1",scheduler.DEFAULT_GROUP,new Date(),null,SimpleTrigger.REPEAT_INDEFINITELY,60L*1000L);
      
        scheduler.start();
      
        scheduler.scheduleJob(job, trigger);
      
        //scheduler.shutdown();

    }

}


Lets look at  MyJob.java

//MyJob.java

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {
   
    //Required public no argument constructor
    public MyJob() {
       
    }

    public void execute(JobExecutionContext arg0) throws JobExecutionException {
       
        System.out.println("Now : "+new Date());

    }

}

Console Output


log4j:WARN No appenders could be found for logger (org.quartz.simpl.SimpleThreadPool).
log4j:WARN Please initialize the log4j system properly.
Now : Mon Aug 09 19:44:09 IST 2010
Now : Mon Aug 09 19:45:09 IST 2010
Now : Mon Aug 09 19:46:09 IST 2010
Now : Mon Aug 09 19:47:09 IST 2010
Now : Mon Aug 09 19:48:09 IST 2010
Now : Mon Aug 09 19:49:09 IST 2010
Now : Mon Aug 09 19:50:09 IST 2010


For quick and fast development use IDE like Eclipse.

Java : Simple Client-Server chat application

We all might have use some or other chat application in some or other form, the basic principle of a chatting is very simple. There is a Server which acts as a controller and  Clients which can be communicate either with server or among client themselves. Lets look at a simple example in java.

In our example we have a Server.java which as the name suggest acts as a server and we have a Client.java which will act as a client. In both we used a threading concept, for receiving and sending a message to and fro.

We used Socket programming concept of ServerSocket and Socket

Kindly go through the code and see output.

//Server.java

import java.net.*;
import java.io.*;
import java.util.*;

public class Server
{
    public static void main(String args[]) throws IOException
    {
        //Register service on port 1436
        ServerSocket serverSocket = new ServerSocket(1463);
       
        //For taking input
        final Scanner scan = new Scanner(System.in);

        while(true)
        {
            //Wait and accept a connection of multiple client
            final Socket socket=serverSocket.accept();
           
            //Start new Thread for receiving message
            new Thread(new Runnable()
            {
                public void run()
                {    try
                    {
                        while(true)
                        {
                            DataInputStream dis = new DataInputStream(socket.getInputStream());
                            System.out.println(dis.readUTF());
                        }
                    }
                    catch (Exception ie)
                    { }
                }
            }).start();
           
            //Start new Thread for sending message
            new Thread(new Runnable()
            {
                public void run()
                {    try
                    {
                        while(true)
                        {
                            String userInput = scan.nextLine();
                            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                            dos.writeUTF("Server says : "+userInput);
                        }
                    }
                    catch (Exception ie)
                    { }
                }
            }).start();

        }//while loop

    }//main
}

//Client.java

import java.net.*;
import java.io.*;
import java.util.*;

public class Client
{
    public static void main(String args[]) throws IOException
    {
        //Open your connection to a server, at port 1436
        final Socket socket = new Socket("localhost",1463);       
       
        //For taking input
        final Scanner scan = new Scanner(System.in);       
       
        //Start new Thread for sending message
        new Thread(new Runnable()
        {
            public void run()
            { try
                {
                    while(true)
                    {
                        String userInput = scan.nextLine();
                        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                        dos.writeUTF("Client says : "+userInput);
                    }
                }
                catch (Exception ie)
                { }
            }
        }).start();
       
        //Start new Thread for receiving message
        new Thread(new Runnable()
        {
            public void run()
            { try
                {
                    while(true)
                    {
                        DataInputStream dis = new DataInputStream(socket.getInputStream());
                        System.out.println(dis.readUTF());
                    }
                }
                catch (Exception ie)
                { }
            }
        }).start();
    }//main
}


Output




Please write your comments.

Wednesday, August 4, 2010

Javascript : Disable right click

While browsing through my bank account site when i used right click i observed that right click was disabled of that page, off course due to security reasons. May be they do not want to show there internal code implementation. so i was searching on web to get code which can be used to disable right click of the browser.


I got a Javascript code, which can be used to do this. Just copy-page below code in a head section of your page.


<script language="JavaScript">
   
        var message="Right click Disabled!";

        function checkIEBrowser()
        {
            if (event.button==2)
            {
                alert(message);
                return false;
            }
        }

        function checkOtherBrowser(e)
        {
            if (document.layers||document.getElementById&&!document.all)
            {
                if (e.which==2||e.which==3)
                {
                    alert(message);
                    return false;
                }
            }
        }

        if (document.layers)
        {
            document.captureEvents(Event.MOUSEDOWN);
            document.onmousedown=checkOtherBrowser;
        }
        else if (document.all&&!document.getElementById)
        {
            document.onmousedown=checkIEBrowser;
        }

        document.oncontextmenu=new Function("alert(message);return false");

    </script>


Output























Https protocol


Due to security reason we do this thing, i used this code along with Https protocol.
to know about Https protocol click here

Https protocol : SSL Configuration

Secure Socket Layer

SSL, or Secure Socket Layer, is a technology which allows web browsers and web servers to communicate over a secured connection. This means that the data being sent is encrypted by one side, transmitted, then decrypted by the other side before processing. This is a two-way process, meaning that both the server AND the browser encrypt all traffic before sending out data.

Another important aspect of the SSL protocol is Authentication. This means that during your initial attempt to communicate with a web server over a secure connection, that server will present your web browser with a set of credentials, in the form of a "Certificate", as proof the site is who and what it claims to be. In certain cases, the server may also request a Certificate from your web browser, asking for proof that you are who you claim to be. This is known as "Client Authentication," although in practice this is used more for business-to-business (B2B) transactions than with individual users. Most SSL-enabled web servers do not request Client Authentication.

Apache Reference

To know more click here

I used following, to implement Https protocol :

  • JDK 1.6
  • Tomcat 6


1 . Create a certificate keystore:

HTTPS requires an SSL Certificate. When you generate an SSL Certificate, you are creating a keystore file (dot keystore file).

{JAVA_HOME}\bin> keytool -genkey -alias tomcat -keyalg RSA

Eg :

C:\Program Files\Java\jdk1.6.0_21\bin>keytool -genkey -alias tomcat -keyalg RSA
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: madan chaudhary
What is the name of your organizational unit?
[Unknown]: Technology
What is the name of your organization?
[Unknown]: Hewitt
What is the name of your City or Locality?
[Unknown]: Mumbai
What is the name of your State or Province?
[Unknown]: Maharashtra
What is the two-letter country code for this unit?
[Unknown]: IN
Is CN=madan chaudhary, OU=Technology, O=Hewitt, L=Mumbai, ST=Maharashtra, C=IN c
orrect?
[no]: y

Enter key password for
(RETURN if same as keystore password):
Re-enter new password:

C:\Program Files\Java\jdk1.6.0_21\bin>

note : Remember your tomcat password, which we will use in our tomcat configuration file ie server.xml

Lets look at a console window

Console Window

 Now check your Home folder ie 

     C:\Documents and Settings\{user home}

     and observe a .keystore file


























2. Configuring Tomcat for using the Keystore file

Now add the following codes in

{CATALINA_HOME}/conf/server.xml

file

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true" keystoreFile="${user.home}/.keystore" keystorePass="your tomcat password"
clientAuth="false" sslProtocol="TLS" />



You change ${user.home} according to your requirement.

Also don't forget to set JAVA_HOME and CATALINA_HOME in environment variable.



Now we are done with our settings now start the tomcat server, if you look at the console it will look something like this
































Now lets create any testing page (htm/jsp etc).
lets say my page is https://localhost:8443/Test/index.jsp

















Monday, August 2, 2010

Java : Read / Write/ Update XLS file using JExcel

Java Excel API - A Java API to read, write, and modify Excel spreadsheets


Java Excel API is a mature, open source java API enabling developers to read, write, and modifiy Excel spreadsheets dynamically.

Lets look at a Simple Example, which can be used for reading, writing and updating Excel (.xls) file, Even it's cell can be formatted according to user requirement.

To know more about Java Excel API click here

In this example we will first create Excel file (Sample.xls) using writeXLSFile() method and then we will read same Excel file (Sample.xls) using readXLSFile() method

For Java Excel API Click here

You will need to Download jxl.jar file


Assuming you have set jxl.jar in classpath


//SimpleJExcelExample.java


import java.io.File;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class SimpleJExcelExample {

public void writeXLSFile()
{
System.out.println("--- writeXLSFile() ---");

try
{
WritableWorkbook workbook = Workbook.createWorkbook(new File("Sample.xls"));

WritableSheet sheet = workbook.createSheet("Sheet1", 0);

WritableFont headerFont = new WritableFont (WritableFont.TIMES, 10,WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE );
WritableCellFormat headerCells = new WritableCellFormat(headerFont);
headerCells.setBackground(Colour.TAN);

int column = 0;

for (int row=0;row <5;row++) {

Label label = new Label(row,column,"Header "+row,headerCells);
label.setCellFormat(headerCells);
sheet.addCell(label);
}

column ++;

WritableFont normalFont = new WritableFont(WritableFont.TIMES, 10);
WritableCellFormat normalCell = new WritableCellFormat(normalFont);

for (int col=column;col <5;col++)
{
for (int row=0;row <5;row++)
{

Label label = new Label(row,col,"cell "+row+" "+col,normalCell);
label.setCellFormat(normalCell);
sheet.addCell(label);
}
}

workbook.write();
workbook.close();

System.out.println("Sample.xls created sucessfully");
}
catch(Exception ee)
{
System.out.println("Exception :: "+ee);
}
}

public void readXLSFile()
{
System.out.println("--- readXLSFile() ---");

try
{
Workbook workbook = Workbook.getWorkbook(new File("Sample.xls"));

// Get the first sheet
Sheet sheet = workbook.getSheet(0);

for(int column = 0; column < sheet.getColumns(); column++)
{
for(int row = 0; row < sheet.getRows(); row++)
{
Cell cell = sheet.getCell(row,column);
System.out.print(cell.getContents());
}
System.out.println();
}
}
catch(Exception ee)
{
System.out.println("Exception :: "+ee);
}
}

public static void main(String[] args) throws Exception
{
SimpleJExcelExample obj = new SimpleJExcelExample();

obj.writeXLSFile();

obj.readXLSFile();
}
}



Console Output


--- writeXLSFile() ---
Sample.xls created sucessfully
--- readXLSFile() ---
Header 0Header 1Header 2Header 3Header 4
cell 0 1cell 1 1cell 2 1cell 3 1cell 4 1
cell 0 2cell 1 2cell 2 2cell 3 2cell 4 2
cell 0 3cell 1 3cell 2 3cell 3 3cell 4 3
cell 0 4cell 1 4cell 2 4cell 3 4cell 4 4


Sample.xls file