Tuesday, December 21, 2010

Simple AJAX Example

AJAX = Asynchronous JavaScript and XML.

AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page. ie Within the same web page we can communicate with other web page without getting out of current page.

Lets see a simple AJAX Example using .html files, directly you can run this example no need of any server.

Here we have a MainPage.html, as the name suggest this is our Main Page which will communicate with another simple page called SimplePage.html. MainPage.html will fetch data from SimplePage.html and display it without refreshing the whole page. lets see the codes.

<!-- MainPage.html -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<script TYPE="text/javascript" LANGUAGE="JavaScript">

function GetXmlHttpObject()
var xmlHttp=null;
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
catch (e)
// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
catch (e)
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;

function stateChanged()
// if request finished and response is ready
if (xmlHttp.readyState==4)
//get the response data as a string
var response = xmlHttp.responseText;

alert("Response :: "+response);


function AJAXTest()
document.getElementById("myDiv").innerHTML="Fetching data...";

alert("AJAXTest function called");

if (xmlHttp==null)
alert ("Your browser does not support AJAX!");

//Stores a function (or the name of a function) to be called automatically each time the readyState property changes


This is a Main page. <br/><br/>
<a href="#" onclick="AJAXTest()">Click Here</a> to call SimplePage.html<br/><br/>

<div id="myDiv"> </div>


Add a simple text line in another page, which will be displayed on main page.

<!-- SimplePage.html -->

<h1>This is a Simple Page</h1>


Friday, November 26, 2010

Java Collections


The Collections Framework in Java, which took shape with the release of JDK 1.2 and was expanded in 1.4 and again in Java 5, gives you lists, sets, maps, and queues to satisfy most of your coding needs. They've been tried, tested, and tweaked. Pick the best one for your job and you'll get—at the least—reasonable performance. And when you need something a little more custom, the Collections Framework in the java.util package is loaded with interfaces and utilities.

So What Do You Do with a Collection?

There are a few basic operations you'll normally use with collections
  •  Add objects to the collection.
  •  Remove objects from the collection.
  • Find out if an object (or group of objects) is in the collection.
  • Retrieve an object from the collection (without removing it).
  • Iterate through the collection, looking at each element (object) one after another.
 Key Interfaces and Classes of the Collections Framework 

The collections API begins with a group of interfaces, but also gives you a truckload of concrete classes.


Not all collections in the Collections Framework actually implement the Collection interface. In other words, not all collections pass the IS-A test for Collection. Specifically, none of the Map-related classes and interfaces extend from Collection. So while SortedMap, Hashtable, HashMap, TreeMap, and LinkedHashMap are all thought of as collections, none are actually extended from Collection-with-a-capital-C (see below Figure). To make things a little more confusing, there are really three overloaded uses of the word "collection":
  • collection (lowercase c), which represents any of the data structures in which objects are stored and iterated over.
  • Collection (capital C), which is actually the java.util.Collection interface from which Set, List, and Queue extend. (That's right, extend, not implement.
    There are no direct implementations of Collection.)
  • Collections (capital C and ends with s) is the java.util.Collections class that holds a pile of static utility methods for use with collections.
The interface and class hierarchy for collections

Collections come in four basic flavors:

  • Lists Lists of things (classes that implement List).
  • Sets Unique things (classes that implement Set).
  • Maps Things with a unique ID (classes that implement Map).
  • Queues Things arranged by the order in which they are to be processed.
The structure of a List, a Set, and a Map
Ordered When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order.

Sorted A sorted collection means that the order in the collection is determined according to some rule or rules, known as the sort order.

List Interface
A List cares about the index. The one thing that List has that non-lists don't have is a set of methods related to the index. Those key methods include things like get(int index), indexOf(Object o), add(int index, Object obj), and so on. All three List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end. The three List implementations are described in the following sections.

1 . ArrayList Think of this as a growable array. It gives you fast iteration and fast random access. To state the obvious: it is an ordered collection (by index), but not sorted. You might want to know that as of version 1.4, ArrayList now implements the new RandomAccess interface—a marker interface (meaning it has no methods) that says, "this list supports fast (generally constant time) random access." Choose this over a LinkedList when you need fast iteration but aren't as likely to be doing a lot of insertion and deletion.

2 . Vector Vector is a holdover from the earliest days of Java; Vector and Hashtable were the two original collections, the rest were added with Java 2 versions 1.2 and 1.4. A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety. You'll normally want to use ArrayList instead of Vector because the synchronized methods add a performance hit you might not need. And if you do need thread safety, there are utility methods in class Collections that can help. Vector is the only class other than ArrayList to implement RandomAccess.

3. LinkedList A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now supports the common queue methods: peek(), poll(), and offer().

Set Interface
A Set cares about uniqueness—it doesn't allow duplicates. Your good friend the equals() method determines whether two objects are identical (in which case only one can be in the set). The three Set implementations are described in the following sections.

1. HashSet A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get. Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.

2. LinkedHashSet A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

3. TreeSet The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure (but you knew that), and guarantees that the elements will be in ascending order, according to natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.

Map Interface
A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are, of course, objects. You're probably quite familiar with Maps since many languages support data structures that use a key/value or name/value pair. The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

1. HashMap The HashMap gives you an unsorted, unordered Map. When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead. Where the keys land in the Map is based on the key's hashcode, so, like HashSet, the more efficient your hashCode() implementation, the better access performance you'll get.HashMap allows one null key and multiple null values in a collection.

2. Hashtable Like Vector, Hashtable has existed from prehistoric Java times. For fun, don't forget to note the naming inconsistency: HashMap vs. Hashtable. Where's the capitalization of t? Oh well, you won't be expected to spell it. Anyway, just as Vector is a synchronized counterpart to the sleeker, more modern ArrayList, Hashtable is the synchronized counterpart to HashMap. Remember that you don't synchronize a class, so when we say that Vector and Hashtable are synchronized, we just mean that the key methods of the class are synchronized. Another difference, though, is that while HashMap lets you have null values as well as one null key, a Hashtable doesn't let you have anything that's null.

3. LinkedHashMap Like its Set counterpart, LinkedHashSet, the LinkedHash-Map collection maintains insertion order (or, optionally, access order). Although it will be somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.

4. TreeMap You can probably guess by now that a TreeMap is a sorted Map. And you already know that by default, this means "sorted by the natural order of the elements." Like TreeSet, TreeMap lets you define a custom sort order (via a Comparable or Comparator) when you construct a TreeMap, that specifies how the elements should be compared to one another when they're being ordered.

Queue Interface
A Queue is designed to hold a list of "to-dos," or things to be processed in some way. Although other orders are possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection methods and they also add methods to add and subtract elements and review queue elements.

1. PriorityQueue This class is new with Java 5. Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. The purpose of a PriorityQueue is to create a "priority-in, priority out" queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.

Tuesday, November 9, 2010

Legal Java Identifiers

Technically, legal identifiers must be composed of only Unicode characters,numbers, currency symbols, and connecting characters (like underscores).

  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.
  • You can't use a Java keyword as an identifier. Below table lists all of the Java keywords including one new one for 5.0, enum.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.
Examples of legal and illegal identifiers follow, first some legal identifiers:

  int _a;
  int $c;
  int ______2_w;
  int _$;
  int this_is_a_very_detailed_name_for_an_identifier;

The following are illegal:

  int :b;
  int -d;
  int e#;
  int .f;
  int 7g;

Complete List of Java Keywords (assert added in 1.4, enum added in 1.5)


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) {
    //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) {



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.


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) {
            while ((s = stdError.readLine()) != null) {
        } catch (IOException e) {
    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);
            //set the new value of count
            //save the file
            try {
                prop.store(new FileOutputStream("data.properties"),"This is a simple example");
            } catch (IOException e) {
                System.out.println("IOException :: "+e);



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



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">
<comment>This is a simple example</comment>
<entry key="count">10</entry>

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) {
            // reading any errors of the command
            System.out.println("Error stream (if any) :: \n");
            while ((s = errorStream.readLine()) != null) {
        } catch (Exception e) {

    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("cmd /c dir");




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 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 :

Download quartz-1.8.3.tar


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.scheduleJob(job, trigger);



Lets look at  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.


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);

            //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
                            DataInputStream dis = new DataInputStream(socket.getInputStream());
                    catch (Exception ie)
                    { }
            //Start new Thread for sending message
            new Thread(new Runnable()
                public void run()
                {    try
                            String userInput = scan.nextLine();
                            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                            dos.writeUTF("Server says : "+userInput);
                    catch (Exception ie)
                    { }

        }//while loop



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
                        String userInput = scan.nextLine();
                        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                        dos.writeUTF("Client says : "+userInput);
                catch (Exception ie)
                { }
        //Start new Thread for receiving message
        new Thread(new Runnable()
            public void run()
            { try
                        DataInputStream dis = new DataInputStream(socket.getInputStream());
                catch (Exception ie)
                { }


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)
                return false;

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

        if (document.layers)
        else if (document.all&&!document.getElementById)

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



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
[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



<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