Friday, May 29, 2009

NavigableMap & NavigableSet interface

The NavigableMap interface extends the SortedMap interface in which the elements are ordered either by natural ordering or by using a Comparator. It contains methods to find out the closest matches for given search targets. All keys inserted into a sorted map must implement the Comparable interface and must be mutually comparable. The elements of the NavigableSet interface can be accessed and traversed in either ascending or descending order.

The NavigableSet interface extends the SortedSet interface in which the elements are ordered either by natural ordering or using a Comparator. It contains methods to find out the closest matches for given search targets. The elements of the NavigableSet interface must be mutually comparable. The elements of the NavigableSet interface can be accessed and traversed in either ascending or descending order.

Matcher class

Matcher is a final class present in the java.util.regex package. It is used to match a regular expression using the pattern defined by the Pattern class.

The Matcher class defines no public constructors. It is created from a pattern by invoking the Pattern's matcher method as follows:

public Matcher matcher(CharSequence input)

This method creates a matcher that will match the given input against the given pattern.

The other important methods of the Matcher class are as follows:

  • int start(): This method returns the index of the first character matched.

  • public int end(): This method returns the index of the last character matched, plus one.

  • boolean find(): This method searches the subsequence of the input sequence that matches the pattern. It returns true if the match is found; otherwise, it returns false.

  • boolean lookingAt(): This method searches through the input sequence to match the pattern. It returns true if the match is found; otherwise, it returns false.

Externalizable interface

The Externalizable interface allows a programmer to have a complete control over the serialization and deserialization processes.

The Externalizable interface has the following two methods:

  • public void writeExternal(ObjectOutput objout): This method is used to save the contents of an object by calling the methods of the DataOutput interface for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, arrays, etc.


  • public void readExternal(ObjectInput objin): This method is used to restore the contents of an object that was saved using the writeExternal() method. It calls the methods of the DataInput interface for primitive types and the readObject() method for objects, strings, arrays, etc.

Comparable & Comparator interface

The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.

The Comparable interface in the generic form is written as follows:

interface Comparable, where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:

int i = object1.compareTo(object2)

  • If object1 <>
  • If object1 > object2: The value of i returned will be positive.

  • If object1 = object2: The value of i returned will be zero.

The Comparator interface is used to sort the elements of collections and arrays. It differs from the Comparable interface in that the Comparable interface sorts the elements only in the natural order. In contrast, the Comparator interface sorts the collections and arrays in a number of different ways.

The Comparator interface has a single compare() method, which returns an integer. It has the following signature:

int Obj1.compare(Obj1, Obj2): This method compares the order of the method arguments and returns the following results:

  • negative if Obj1 <>
  • positive if Obj1 > Obj2

  • zero if Obj1 == Obj2
equals(Object obj): This method is used to compare the equality of two objects. The objects being compared must also implement the Comparator interface.

The Comparator interface can sort only the mutually comparable objects. It cannot be used to sort primitives. Sorting elements using the Comparator interface requires building a class separate from the class whose instances are to be sorted. This is in contrast to the Comparable interface, in which case the class to be sorted itself uses the Comparable interface.

Serializable

Serializable is a marker interface. (A marker interface is one without any method). The classes that do not implement this interface will not have any of their states serialized or deserialized. Serialization is the process of converting an object into byte stream, so that it can be transferred over a network and stored into a persistent medium such as a file.

Serialization is the process of converting the state of an object into a form that can be transported or stored. In this process, an object's state is written to a temporary or persistent storage. Later, the object can be recreated by deserializing or reading the object's state from the storage.

Coupling

Coupling is a term that describes the degree to which one module relies on another module for its proper functioning. Coupling is mainly of the following two types:

  • Loose coupling: Loose or weak coupling implies that a change in one module does not require changes in the implementation of another module.

  • Tight coupling: Tight or strong coupling implies that a module relies on another module so strongly that a small change in one will require an implementation change in the other.
For a good object-oriented design, loose coupling is desirable.

Cohesion

Cohesion is a measure of degree of how strongly a class focuses on its responsibilities. It is of the following two types:

  • High cohesion: This means that a class is designed to carry on a specific and precise task. Using high cohesion, methods are easier to understand, as they perform a single task.
  • Low cohesion: This means that a class is designed to carry on various tasks. Using low cohesion, methods are difficult to understand and maintain.
In object-oriented design, high cohesion is desirable, as it is easy to understand and maintain. Moreover, it is easier to reuse.

Differences between exceptions and assertions

ExceptionsAssertions
An exception tells the user of the program that something in the program went wrong.An assertion documents a program. When it fails, it informs that the program has a bug.
Exceptions are created to deal with problems that might occur in the program. Assertions are written to state the concepts of a program.
Exceptions are used to test input/output as well as whether parameters are legal or not.Assertions are documentations that can be checked by running the program.

checked and unchecked exceptions

Unchecked Exceptions: Exceptions that are defined by the Error and RuntimeException classes and their subclasses are known as unchecked exceptions. It is not necessary that a method must deal with these kinds of exceptions. If the exceptions are irrecoverable, the program should not attempt to deal with them. The method can only deal with the exceptions that are recoverable.

Checked Exceptions: All exceptions except the Error and RuntimeException classes and their subclasses are known as checked exceptions. If a method throws a checked exception, it is necessary that the method must explicitly deal with the exception. The method must catch the exception and take the necessary action.

Closeable and Flushable interfaces

The Closeable and Flushable interfaces define a uniform way for specifying that a stream can be closed or flushed.

Closeable: The objects that implement the Closeable interface can be closed. This interface defines the close() method.

void close() throws IOException

It closes the invoking stream and releases all the resources. It is implemented by all the I/O classes that open a stream.

Flushable: The objects that implement the Flushable interface can force buffered output to be written to a stream to which the objects are attached. This interface defines the flush() method.

void flush() throws IOException

JavaBeans setter and getter methods

JavaBeans are Java classes that have properties. Properties are private instance variables. According to JavaBeans, the methods that set the values of these variables are known as setter methods, and the methods that retrieve the values of these variables are known as getter methods.

The naming convention for setter methods is that they should be prefixed with set and the name of the variable. The name of the variable should begin with upper case.

The naming convention for getter methods is similar to that of setter. It should begin with get and the name of the variable. The name of the variable should begin with upper case.

The setter method must be declared public, with a void return type and an argument that represents the property type.

The getter method must be declared public. It takes no arguments, and should have a return type that matches the argument type of the setter method for that property.

Properties of synchronization

Synchronization is a process through which multiple threads share access to common objects. Java coordinates the actions of multiple threads using synchronized methods and statements. Following are the properties of synchronization:

  1. If a thread contains some locks and goes to sleep, then it does not release the locks.
  2. Only methods can be synchronized, not variables and constants.
  3. If two threads invoke the same method, then only one thread at a time can invoke a method.
  4. A thread can invoke a synchronized method on multiple objects.
  5. A class can have both synchronized and non-synchronized methods.
  6. If a class has synchronized and non-synchronized methods, then multiple threads can still access the non-synchronized methods of the class.

Different states of a thread

The job of the thread scheduler is to move a thread from one state to another state. A thread can be in one of the following states:

  1. New: It is the state when the thread instance has been created, but the start method has not been invoked on the thread.


  2. Runnable: It is the state when the thread is eligible to run. In this state, the thread is not selected by the scheduler for execution. A thread enters the Runnable state when the start() method is invoked. A thread can return to the Runnable state from the blocked, waiting, or sleeping state.


  3. Running: It is the state when the thread scheduler selects the thread to be the currently executing process. A thread can transition out of a running state through the compiler.


  4. Waiting: It is also known as blocked or sleeping state. In this state, the thread is not eligible to run, but it might return to the runnable state if a particular event occurs. A thread can be blocked if it is waiting for a resource. It can be in the waiting state if its code causes it to wait.


  5. Dead: A thread is considered dead when its run() method completes. Once a thread is dead, it can never be brought back to life.

Differences between the BufferedReader and BufferedWriter

BufferedReaderBufferedWriter
It extends from the reader class.It extends from the writer class.
Its key constructor arguments are Reader.Its key constructor arguments are Writer.
It provides the read() and readLine() methods.It provides the close(), flush(), newLine(), and write() methods.
It implements the mark() and reset() methods. It does not implement the mark() and reset() methods.

Differences between the Comparable and Comparator interfaces

Comparable InterfaceComparator Interface
It uses the compareTo() method.

int objectOne.compareTo(objectTwo)
It uses the compare() method.

int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose instance is going to be sorted.A separate class can be created in order to sort the instances.
Only one sort sequence can be created. Many sort sequences can be created.
It is frequently used by the API classes.It it used by third-party classes to sort instances.

Differences between StringBuffer and String

StringBufferString
It provides a mutable character sequence. It provides an immutable character sequence.
It is possible to insert characters and substrings in the middle or at the end of the string.It is not possible to insert characters and substrings in the middle or at the end of the string.
It reserves room for 16 characters without reallocation.It does not reserve room for characters.
It uses the ensureCapacity(), delete(), deleteCharAt(), append(), insert(), and reverse() methods.It is not possible to use these methods on strings because they are immutable.

Differences between method overriding and method overloading

Method OverridingMethod Overloading
Arguments of overloaded methods cannot be changed.Arguments of overloaded methods can be changed.
Method return types cannot be changed except covariant return types. Return types can be changed.
Exceptions must not throw new or broader checked exceptions.Exceptions can be changed.
It happens at runtime.It happens at compile-time.
An object type determines which method is selected.A reference type determines which method is selected.

Wednesday, April 22, 2009

Smart and Simple XML Utility - v1.0

Smart and Simple XML Utility - v1.0

I have developed one small XML utility as well as eclipse plug-in that enables user to perform necessary operations on XML schema

Overview

A Smart and Simple XML utility performs following things,
1. XML validation with XSD schema.
2. Transform XML schema using XSL schema.
3. and Evaluate XPath Expressions.

This is an open source application that is written completely in Java SWT (Standard Widget Toolkit) which is fast, more responsive and lighter .

Standard Widget Toolkit (SWT) is a graphical widget toolkit for use with the Java platform. It was originally developed by IBM and is now maintained by the Eclipse Foundation in tandem with the Eclipse IDE. It is an alternative to the AWT and Swing Java GUI toolkits provided by Sun Microsystems as part of the Java Platform, Standard Edition.

SWT is written in Java. To display GUI elements, the SWT implementation accesses the native GUI libraries of the operating system using JNI (Java Native Interface) in a manner that is similar to those programs written using operating system-specific APIs. Programs that call SWT are portable, but the implementation of the toolkit, despite the fact that it is written in Java, is unique for each platform.

Release Notes :
This application still has a number of gaps in the functionality, but improvements are occurring all the time

Version 1.1.0
Feature:
Added Pretty Formatter to format the contents with correct indentation.

Version 1.0.0
Features:
1. XML validation with XSD.
2. XML Transformation using XSL.
3. XPath Evaluation.
4. Export all the data (XML, XSL/XSD & Result) to a file.

License:

1. Common Public License
2. Eclipse Public License 1.0

Download :

Version 1.1.0

https://xmlutility.dev.java.net/files/documents/10222/134058/XMLUtility_1.1.0.jar

Version 1.0.0

https://xmlutility.dev.java.net/files/documents/10222/132835/XMLUtility_1.0.0.jar

Requirements :

JDK 1.4 or higher installed on your system.

Help wanted!

mailto: xmlutility[at]dev[dot]java[dot]com

MySQL :: Supports XML Operations.

MySQL :: Supports XML Operations.

As of version 5.1.5, MySQL supports some functions for handling XML Data. Working with XML tends to be very data-oriented. In alot of cases, only a trivial mapping is required between the relational data and the xml representation. In these cases, it is certainly quite convenient to have all the tools that implement the mapping close at hand.

MySQL XML capabilities up to 5.0

In prior versions, MySQL XML support was limited to exporting data in XML format using the MySQL command line client. All you need to do is start the mysql client utilitiy with the --xml or -X option.
>mysql -u root -p root -X

This will shows you a query results in an XML format and its very convenient method for quick formatting. A possible disadvantage is that the mapping from relational data to XML is fixed - there is no way you can change the tagnames, control wheter data should be formatted as element content or as an attribute, set the namespace, etcetera.

MySQL XML capabilities as of 5.1.5

XML support in MySQL 5.1 has been extended with:
* ExtractValue(): Query and Retrieve data from XML formatted text strings
* UpdateXML(): Update data in XML formatted text strings

Both functions accept a string that represents fragment of XML, and an XPath expression. The XPath expression acts as a query operator on the xml, identifying the nodes (that is, the elements, attributes, text contents etc.) that the function needs to handle.

In the case of ExtractValue(), the text nodes specified by, or ocurring within the nodes identified by the XPath expression is returned:

mysql> select extractValue('text','tag') as `tag`
-> , extractValue('text','tag/text()') as `text()`
-> ;
+------+--------+
| tag | text() |
+------+--------+
| text | text |
+------+--------+
1 row in set (0.00 sec)

In first call to ExtractValue() the XPath expression, tag selects the text bit, but only the text content is returned. The XPath expression in second call to ExtractValue(), tag/text() explicitly specifies that text content should be selected. The result is the same in both cases.
If multiple nodes are identified, the text contents are concatenated, separated by a single space character:

mysql> select extractValue('text1text2','tag') as `tag`;
+-------------+
| tag |
+-------------+
| text1 text2 |
+-------------+
1 row in set (0.00 sec)

In the case of UpdateXML(), the selected node is replaced by the third supplied argument.

Importing XML using ExtractValue

We can write a single XPath expression for each field in both of the store records, and once we have the values, it's of course a piece of cake to write an insert around that:

set @xml := "text2";
insert into store values (extractValue(@xml,'/parent/child/text()'));

Even we can use these functions in the stored procedure where we have to deal with larger xml schema and do the extraction of data.

Thursday, March 12, 2009

Java Thread

Thread

A thread is a lightweight process which exist within a program and executed to perform a special task. Several threads of execution may be associated with a single process. Thus a process that has only one thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a multi-threaded process. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations,
called activation records or stack frame. The activation record contains pertinent information about a method like local variables.

In Java Programming language, thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime. In single threaded runtime environment, operations are executes sequentially i.e. next operation can execute only when the previous one is complete. It exists in a common memory space and can share both data and code of a program. Threading concept is very important in Java through which we can increase the speed of any application.



Main Thread

When any standalone application is running, it firstly execute the main() method runs in a one thread, called the main thread. If no other threads are created by the main thread, then program terminates when the main() method complete its execution. The main thread creates some other threads called child threads. The main() method execution can finish, but the program will keep running until the all threads have complete its execution.

Life Cycle of A Thread

1. New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.

2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.

3. Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.

4. Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.

5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.


Thread Implementation

I. Extending the java.lang.Thread Class

For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:

1. Extend the java.lang.Thread Class.
2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread.
3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor.
4. Invoke the start( ) method on the instance of the class to make the thread eligible for running.

II. Implementing the java.lang.Runnable Interface

The procedure for creating threads by implementing the Runnable Interface is as follows:

1. A Class implements the Runnable Interface, override the run() method to define the code executed by thread. An object of this class is Runnable Object.
2. Create an object of Thread Class by passing a Runnable object as argument.
3. Invoke the start( ) method on the instance of the Thread class.

There are two reasons for implementing a Runnable interface preferable to extending the Thread Class:

1. If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you implement Runnable interface then you can do this.
2. The class implementing the Runnable interface can avoid the full overhead of Thread class which can be excessive.

Daemon threads

Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon()

When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads.

Synchronization

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:
public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}
}
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Synchronized blocks place locks for shorter periods than synchronized methods.



Mutual exclusion

Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

Wednesday, March 4, 2009

XML and Java Technologies

XML and Java Technologies

* Extensible Markup Language(XML)

XML stands for EXtensible Markup Language. Its a markup language much like HTML. XML was designed to carry data, not to display data. XML tags are not predefined. You must define your own tags. XML is designed to be self-descriptive. XML is a W3C Recommendation

* Java API for XML Processing (JAXP), v 1.3

The Java API for XML Processing, or JAXP for short, enables applications to parse and transform XML documents using an API that is independent of a particular XML processor implementation. JAXP also provides a pluggability feature which enables applications to easily switch between particular XML processor implementations.
To achieve the goal of XML processor independence, an application should limit itself to the JAXP API and avoid implementation-dependent APIs and behavior. This may or may not be easy depending on the application. See this question for more information. JAXP includes industry standard APIs such as DOM and SAX. See these slides (PDF) for more information.
The reason for the existance of JAXP is to facilitate the use of XML on the Java platform. For example, current APIs such as DOM Level 2 do not provide a method to bootstrap a DOM Document object from an XML input document, JAXP does. (When DOM Level 3 provides this functionality, a new version of the JAXP specification will probably support the new Level 3 scheme also.) Other parts of JAXP such as the javax.xml.transform portion do not have any other equivalent XSLT processor-independent APIs.

* Java Architecture for XML Binding (JAXB), v 1.0 and 2.0

Java Architecture for XML Binding (JAXB) provides an API and tool that allow automatic two-way mapping between XML documents and Java objects. With a given Document Type Definition (DTD) and a schema definition, the JAXB compiler can generate a set of Java classes that allow developers to build applications that can read, manipulate and recreate XML documents without writing any logic to process XML elements. The generated codes provide an abstraction layer by exposing a public interface that allows access to the XML data without any specific knowledge about the underlying data structure. In addition to DTD support, future versions of JAXB will add support for other schema languages, such as the W3C XML Schema. These features enable the JAXB to provide many benefits for the developers, which are further explained in the next section.

* JAX-RPC v 1.1

To aid developers in building XML-based requests such as SOAP requests, The JCP is developing the Java APIs for XML based RPC (JAX/RPC). JAX/RPC is used for sending and receiving (including marshalling and unmarshalling) method calls using XML-based protocols such as SOAP, or others such as XMLP (XML Protocol. For more information, see http://www.w3.org/2000/xp/). JAX/RPC isolates you from the specifics of these protocols, enabling rapid application development. There is no longer any need for developers to interact directly with the XML representation of the call.

* JAX-WS v 2.0

JAX-WS (Java API for XML Web Services) is a technology designed to simplify the construction of web services and web service clients in Java. The latest version, JAX-WS 2.0, which is part of the new Java EE 5 platform, provides powerful new tools and techniques to facilitate web service development.

* SAAJ (SOAP with Attachments API for Java)

SOAP with Attachments API for Java (SAAJ) is used mainly for the SOAP messaging that goes on behind the scenes in JAX-RPC and JAXR implementations. Secondarily, it is an API that developers can use when they choose to write SOAP messaging applications directly rather than use JAX-RPC. The SAAJ API allows you to do XML messaging from the Java platform: By simply making method calls using the SAAJ API, you can read and write SOAP-based XML messages, and you can optionally send and receive such messages over the Internet (some implementations may not support sending and receiving). This chapter will help you learn how to use the SAAJ API.
The SAAJ API conforms to the Simple Object Access Protocol (SOAP) 1.1 specification and the SOAP with Attachments specification. The SAAJ 1.2 specification defines the javax.xml.soap package, which contains the API for creating and populating a SOAP message.

* Java API for XML Registries (JAXR)

The Java API for XML Registries (JAXR) API provides a uniform and standard Java API for accessing different kinds of XML Registries. XML registries are an enabling infrastructure for building, deployment, and discovery of Web services.
An abstraction-based JAXR API gives developers the ability to write registry client programs that are portable across different target registries. This is consistent with the Java philosophy of Write Once, Run Anywhere. It also enables value-added capabilities beyond what the underlying registries are capable of. For example, a non-JAXR UDDI client does not have the ability to do taxonomy browsing and taxonomy-aware smart queries, which are available to a JAXR client for UDDI.

* Java API for XML Messaging (JAXM) - Optional

When receiving a web service request from say a business partner, we need a Java API to process XML messages, in a similar way to how we processed SOAP requests using JAX/RPC. The Java API for XML Messaging (JAXM) is a forthcoming specification for interacting with XML messaging standards such as ebXML messaging and SOAP messaging. This API is designed to facilitate the processing of XML message protocols, particularly those where a predetermined “contract” exists (ebXML in particular) to determine the format and constraints of the message. This API will handle all the “envelope” information, such as routing information and the “cargo” manifest, in an intuitive way separate from the actual payload of the message. This allows developers to focus on interacting with the payload and not worry about the other message administrivia.

Tuesday, March 3, 2009

Implementing AJAX using Java

AJAXAJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script. Ajax uses XHTML for content and CSS for presentation, as well as the Document Object Model and JavaScript for dynamic content display. Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background. Intuitive and natural user interaction. No clicking required only Mouse movement is a sufficient event trigger. Ajax is Data-driven as opposed to page-driven.

AJAX is based on the following open standards:

* Browser-based presentation using HTML and Cascading Style Sheets (CSS)
* Data stored in XML format and fetched from the server
* Behind-the-scenes data fetches using XMLHttpRequest objects in the browser
* JavaScript to make everything happen

The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats.

You already have seen couple of examples on how to create a XMLHttpRequest object.

Below is listed some of the methods and properties you have to become familiar with.
XMLHttpRequest Methods

* abort() : Cancels the current request.
* getAllResponseHeaders() : Returns the complete set of HTTP headers as a string.
* getResponseHeader( headerName ) : Returns the value of the specified HTTP header.
* open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password ) : Specifies the method, URL, and other optional attributes of a request.

The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible

The "async" parameter specifies whether the request should be handled asynchronously or not . "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.
* send( content ) : Sends the request.
* setRequestHeader( label, value ) : Adds a label/value pair to the HTTP header to be sent.

XMLHttpRequest Properties

* onreadystatechange : An event handler for an event that fires at every state change.
* readyState :
The readyState property defines the current state of the XMLHttpRequest object.
Here are the possible values for the readyState propery:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is completed

readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState=1 after you have called the open() method, but before you have called send().
readyState=2 after you have called send().
readyState=3 after the browser has established a communication with the server, but before the server has completed the response.
readyState=4 after the request has been completed, and the response data have been completely received from the server.
* responseText : Returns the response as a string.
* responseXML : Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
* status : Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
* statusText : Returns the status as a string (e.g. "Not Found" or "OK").

Steps of AJAX Operation

1. A client event occurs

A JavaScript function is called as the result of an event

2. An XMLHttpRequest object is created

var ajaxRequest; // The variable that makes Ajax possible!
function ajaxFunction(){
try{
xmlHttp = new XMLHttpRequest();
}catch (e){
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
return false;
}
}
}
}

3. The XMLHttpRequest object is configured

In this step we will write a function which will be triggered by the client event and a callback function processRequest() will be registered

function searchUser() {
// Here processRequest() is the callback function.
xmlHttp.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}

4. The XMLHttpRequest object makes an asynchronous request to the Webserver.

ource code is available in the above piece of code. Code written in blue color is responsible to make a request to the web server. This is all being done using XMLHttpRequest object ajaxRequest

5. Webserver returns the result containing XML document.

You can implement your server side script in any language.

If we assume that you are going to write a servlet then here is the piece of code

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
String targetId = request.getParameter("id");

if ((targetId != null) && !accounts.containsKey(targetId.trim()))
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("true");
}
else
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("false");
}
}

6. The XMLHttpRequest object calls the callback() function and processes the result.

The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will recieve the result from the server and will do required processing. As in the following example it sets a variable message on true or false based on retruned value from the Webserver.

function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}


7. The HTML DOM is updated

This is the final step and in this step your HTML page will be updated. It happens in the following way

* JavaScript technology gets a reference to any element in a page using DOM API
* The recommended way to gain a reference to an element is to call.

The Disadvantages of AJAX

1. Building an AJAX-powered application can increase development time and costs.
2. Although AJAX relies on existing and mature technologies like Javascript, HTML and CSS, the available frameworks and components still need to completely mature.
3. Not all concerns regarding security and user privacy have been answered. This fueled a wave of criticism about how safe is the AJAX way of building applications.
4. Using AJAX to asynchronously load bits of content into an existing page conflicts with the way we are used to navigate and create bookmarks in modern browsers.
5. AJAX is not meant to be used in every application. One of the main reasons for this stays in the fact that Google cannot index it.
6. The biggest concern with AJAX is accessibility. This is because not all browsers (especially older ones) have complete support for JavaScript or the XMLHttpRequest object.
7. Due to security constraints, you can only use it to access information from the host that served the initial page. If you need to display information from another server, it is not possible within the AJAX paradigm.

Java JUnit

JUnit is an open source framework that has been designed for the purpose of writing and running tests in the Java programming language. JUnit was originally written by Erich Gamma and Kent Beck. There are many ways to write test cases. A test case is a code fragment that checks that another code unit (method) works as expected. So if we want an accurate and efficient testing process then using a good testing framework is recommended. JUnit has established a good reputation in this scenario.

JUnit is a regression-testing framework that developers can use to write unit tests as they develop systems. Unit testing belongs to test a single unit of code, which can be a single class for Java. This framework creates a relationship between development and testing. You start coding according to the specification and need and use the JUnit test runners to verify how much it deviates from the intended goal. Typically, in a unit testing, we start testing after completing a module but JUnit helps us to code and test both during the development. So it sets more focus on testing the fundamental building blocks of a system i.e. one block at a time rather than module level functional testing. This really helps to develop test suites that can be run any time when you make any changes in your code. This all process will make you sure that the modifications in the code will not break your system without your knowledge.

JUnit provides also a graphical user interface (GUI) which makes it possible to write and test source code quickly and easily. JUnit shows test progress in a bar that is green if testing is going fine and it turns red when a test fails. There is a lot of pleasure in seeing the green bars grow in the GUI output. A list of unsuccessful tests appears at the bottom of the display window. We can run multiple tests concurrently. The simplicity of JUnit makes it possible for the software developer
to easily correct bugs as they are found.

JUnit Installation

1. First, download the latest version of JUnit from http://www.junit.org/ in zip format.
2. Then install JUnit on your platform of choice:
Windows
To install JUnit on Windows, follow these steps:
1. Unzip junit distribution file to a directory referred to as %JUNIT_HOME%.
2. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit-4.x.x.jar

Unix (bash)
To install JUnit on Unix, follow these steps:
1. Unzip junit distribution file to a directory referred to as $JUNIT_HOME.
2. Add JUnit to the classpath:
export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit-4.x.x.jar
3. (Optional) Unzip the $JUNIT_HOME/src.jar file.
4. Test the installation by running the sample tests distributed with JUnit. Note that the sample tests are located in the installation directory directly, not the junit.jar file. Therefore, make sure that the JUnit installation directory is on your CLASSPATH. Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an "OK" message.
If the tests don't pass, verify that junit.jar is in the CLASSPATH.
5. Finally, read the documentation.

Writing Tests

1. Create a class:

import org.junit.*;
import static org.junit.Assert.*;

import java.util.*;

public class SimpleTest {

2. Write a test method (annotated with @Test) that asserts expected results on the object under test:

@Test
public void testEmptyCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}

3. If you are running your JUnit 4 tests with a JUnit 3.x runner, write a suite() method that uses the JUnit4TestAdapter class to create a suite containing all of your test methods:

public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(SimpleTest.class);
}
4. Although writing a main() method to run the test is much less important with the advent of IDE runners, it's still possible:

public static void main(String args[]) {
org.junit.runner.JUnitCore.main("junitfaq.SimpleTest");
}
}

5. Run the test:
* To run the test from the console, type:
java org.junit.runner.JUnitCore SimpleTest

* To run the test with the test runner used in main(), type:
java SimpleTest

The passing test results in the following textual output:

Time: 0
OK (1 tests)

Run JUnit using Ant

1. Define any necessary Ant properties like source folder path, library folder path or class name etc.






2. Set up the CLASSPATH to be used by JUnit:









3. Define the Ant task for running JUnit:









4. Run the test:
ant test

Thursday, February 26, 2009

Java Collections

Collections API

The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

DIFFERENCE : Iterator and ListIterator

Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements

DIFFERENCE : HashMap and HashTable

1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.

DIFFERENCE : Set and list

A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.

DIFFERENCE : Vector and ArrayList

Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.

DIFFERENCE : Array and Arraylist

An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.

DIFFERENCE : Enumeration and Iterator

The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.So Enumeration is used when ever we want to make Collection objects as Read-only.

DIFFERENCE : Enumeration, ArrayList, Hashtable and Collections and Collection

Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.

ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements, including null. It is not thread -safe.

Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.

Collections: It implements Polymorphic algorithms which operate on collections.

Collection: It is the root interface in the collection hierarchy.

HOW : Make hashmap synchronized

Note on Some Important Terms
1) Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

2) Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Java Garbage Collection

Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists.

In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic process and can't be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc(). Once an object is garbage collected, It can no longer become reachable again.

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

Java Abstract Class

1. Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present.

2. Abstract class definition begins with the keyword "abstract" keyword followed by Class definition. An Interface definition begins with the keyword "interface".

3. Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

4. All variables in an Interface are by default - public static final while an abstract class can have instance variables.

5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.

6. An Interface can only have public members whereas an abstract class can contain private as well as protected members.

7. A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast

10.Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

Note: There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an interface.

Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they
share is a set of method signatures, then tend towards an interface.

Similarities:
Neither Abstract classes nor Interface can be instantiated.

Wednesday, February 25, 2009

Installing SSL Certificate on Java Based Web Servers

Use the keytool command to import the certificates as follows:
<%JAVA_HOME%>/bin/keytool -import -trustcacerts -alias -file -keystore

Use the same process for the site certificate using the keytool command, if you are using an alias then please include the alias command in the string. Example:

<%JAVA_HOME%>/bin/keytool -import -trustcacerts -alias yyy -file yahoo.cer -keystore [domain.key/cacerts.jks/...]

Certificate keystore file name may vary from server to server.

The password is then requested.

EXAMPLE BELOW :

Enter keystore password: (This is the one used during CSR creation)
The following information will be displayed about the certificate and you will be asked if you want to trust it (the default is no so type 'y' or 'yes'):
Owner: CN= Root, O=Root, C=US
Issuer: CN=Root, O=Root, C=US
Serial number: 111111111111
Valid from: Fri JAN 01 23:01:00 GMT 1990 until: Thu JAN 01 23:59:00 GMT 2050
Certificate fingerprints:
MD5: D1:E7:F0:B2:A3:C5:7D:61:67:F0:04:CD:43:D3:BA:58
SHA1: B6:GE:DE:9E:4C:4E:9F:6F:D8:86:17:57:9D:D3:91:BC:65:A6:89:64
Trust this certificate? [no]:

Then an information message will display as follows:
Certificate was added to keystore

All the certificates are now loaded and the correct root certificate will be presented. Now we have to restart the web server.

Tuesday, February 24, 2009

Java Database Connection Pool Implementation

The Java Database Connect API (JDBC) is supported by all major database vendors as well as many small databases. To access a database through JDBC you first open a connection to the database, resulting in a Connection object. A Connection object represents a native database connection and provides methods for executing SQL statements. The database connection pool described in this article consists of manager class that provides an interface to multiple connection pool objects.

The database connection pool class, DBConnectionPool, provides methods to

  • get an open connection from the pool,
  • return a connection to the pool,
  • release all resources and close all connections at shutdown.
It also handles connection failures, such as time-outs, communication failures, etc. and can limit the number of connections in the pool to a predefined max value.

The manager class, DBConnectionManager, is a wrapper around the DBConnectionPool class that manages multiple connection pools. It

  • loads and registers all JDBC drivers,
  • creates DBConnectionPool objects based on properties defined in a properties file,
  • maps connection pool names to DBConnectionPool instances,
  • keeps track of connection pool clients to shut down all pools gracefully when the last client is done.
The rest of this article describes each class in detail, starting with the DBConnectionPool class. You will also see an example of how a Servlet is using the connection pool. The complete source code for the DBConnectionManager and the DBConnectionPool is also available here.

The DBConnectionPool class

The DBConnectionPool class represents a pool of connections to one database. The database is identified with a JDBC URL. A JDBC URL consists of three parts: the protocol identifier, the driver identifier and the database identifier (the format is driver specific). The pool also has a name used by the clients and optionally a user name and password and a max connection limit. If you develop a web application where all users can execute some database operations but others are restricted to authorized users, you can define one pool for the general user and another pool for the restricted group using the same JDBC URL but different user names and passwords.

Constructor

The DBConnectionPool constructor takes all values described above as its parameters:

        public DBConnectionPool(String name, String URL, String user,
String password, int maxConn) {
this.name = name;
this.URL = URL;
this.user = user;
this.password = password;
this.maxConn = maxConn;
}
It saves all parameter values in its instance variables.

Get an open connection from the pool

The DBConnectionPool class provides two methods for checking out a connection. They both return an existing Connection if one is available, otherwise they create a new Connection. If no Connection is available and the max number of connections have been reached, the first method returns null but the other waits until an existing Connection is checked in.

public synchronized Connection getConnection() {
Connection con = null;
if (freeConnections.size() > 0) {
// Pick the first Connection in the Vector
// to get round-robin usage
con = (Connection) freeConnections.firstElement();
freeConnections.removeElementAt(0);
try {
if (con.isClosed()) {
log("Removed bad connection from " + name);
// Try again recursively
con = getConnection();
}
}
catch (SQLException e) {
log("Removed bad connection from " + name);
// Try again recursively
con = getConnection();
}
}
else if (maxConn == 0 || checkedOut < con =" newConnection();">All Connection objects in the pool are kept in a Vector, named freeConnections, when they are checked in. If there is at least one Connection in the Vector getConnection() picks the first one. As you will see later, Connections are added to the end of the Vector when they are checked in so picking the first ensures an even utilization to minimize the risk that the database disconnects a connection due to inactivity.

Before returning the Connection to the client, the isClosed() method is used to verify that the connection is okay. If the connection is closed, or an exception is thrown, the method calls itself again to get another connection.

If no Connection is available in the freeConnections Vector the method checks if the max connection limit is specified, and if so, if it's been reached. A maxConn value of 0 means "no limit". If no limit has been specified or the limit has not been reached, the method tries to create a new Connection. If it's successful, it increments the counter for the number of checked out connections and returns the Connection to the client. Otherwise it returns null.

The newConnection() method is used to create a new Connection. This is a private method that creates a Connection based on if a user name and a password have been specified or not.

        private Connection newConnection() {
Connection con = null;
try {
if (user == null) {
con = DriverManager.getConnection(URL);
}
else {
con = DriverManager.getConnection(URL, user, password);
}
log("Created a new connection in pool " + name);
}
catch (SQLException e) {
log(e, "Can't create a new connection for " + URL);
return null;
}
return con;
}
The JDBC DriverManager provides a set of getConnection() methods that takes a JDBC URL plus other parameters, for instance a user name and a password. The DriverManager uses the URL to locate a JDBC driver matching the database and opens a connection.

The second getConnection() method takes a time-out parameter, with a value in milliseconds for how long the client is willing to wait for a connection. It's implemented as a wrapper around the first getConnection() method:

        public synchronized Connection getConnection(long timeout) {
long startTime = new Date().getTime();
Connection con;
while ((con = getConnection()) == null) {
try {
wait(timeout);
}
catch (InterruptedException e) {}
if ((new Date().getTime() - startTime) >= timeout) {
// Timeout has expired
return null;
}
}
return con;
}
The local startTime variable is initialized with the current time. A while loop first try to get a connection. If it fails, wait() is called with the the number of milliseconds we are prepared to wait. wait() returns either when another thread calls notify() or notifyAll(), as you will see later, or when the time has elapsed. To figure out if wait() returned due to a time-out or a notification, the start time is subtracted from current time and if the result is greater than the time-out value the method returns null. Otherwise getConnection() is called again.

Return a connection to the pool

The DBConnectionPool class also provides a method for returning a connection to the pool. The freeConnection() method takes the returned Connection object as its parameter.

        public synchronized void freeConnection(Connection con) {
// Put the connection at the end of the Vector
freeConnections.addElement(con);
checkedOut--;
notifyAll();
}

The Connection is added to the end of the freeConnections Vector and the counter for number of checked out connections is decremented. The notifyAll() is called to notify other clients waiting for a connection.

Shutdown

Most Servlet Engines provide some method for graceful shutdown. The database connection pools need to be notified about this event so that all connections can be closed correctly. The DBConnectionManager class is responsible for coordinating the shutdown but it's the DBConnectionPool class that closes all connections in the pool. The release() method is called by the DBConnectionManager.
        public synchronized void release() {
Enumeration allConnections = freeConnections.elements();
while (allConnections.hasMoreElements()) {
Connection con = (Connection) allConnections.nextElement();
try {
con.close();
log("Closed connection for pool " + name);

}
catch (SQLException e) {
log(e, "Can't close connection for pool " + name);
}
}
freeConnections.removeAllElements();
}
This method loops through the freeConnections Vector and closes all Connections. When all Connections have been closed they are removed from the Vector.

The DBConnectionManager class

The DBConnectionManager class is implemented according to the Singleton pattern described in many design books. A Singleton is a class with just one instance. Other objects can get a reference to the single instance through a static method (class method).

Constructor and getInstance()

The DBConnectionManager constructor is private to prevent other objects to create instances of the class.

    private DBConnectionManager() {
init();
}
Clients of the DBConnectionManager calls the getInstance() method to get a reference to the single instance.
    static synchronized public DBConnectionManager getInstance() {
if (instance == null) {
instance = new DBConnectionManager();
}
clients++;
return instance;
}
The single instance is created the first time this method is called and a reference is then kept in the static variable named instance. A counter for the number of DBConnectionManager clients is incremented before the reference is returned. This counter is later used to coordinate the shutdown of the pools.

Initialization

The constructor calls a private method called init() to initialize the object.

    private void init() {
InputStream is = getClass().getResourceAsStream("/db.properties");
Properties dbProps = new Properties();
try {
dbProps.load(is);
}
catch (Exception e) {
System.err.println("Can't read the properties file. " +
"Make sure db.properties is in the CLASSPATH");
return;
}
String logFile = dbProps.getProperty("logfile",
"DBConnectionManager.log");
try {
log = new PrintWriter(new FileWriter(logFile, true), true);
}
catch (IOException e) {
System.err.println("Can't open the log file: " + logFile);
log = new PrintWriter(System.err);
}
loadDrivers(dbProps);
createPools(dbProps);
}
The getResourceAsStream() method is a standard method for locating an external file and open it for input. How the file is located depends on the class loader but the standard class loader for local classes searches for the file in the CLASSPATH, starting in the directory where the class file is located. The db.properties file is a file in the Properties format containing key-value pairs that define the connection pools. The following common properties can be defined:
drivers A space separated list of JDBC driver class names
logfile The absolute path for a log file

Another set of properties are used for each pool. The property name starts with the name of the connection pool:

.url The JDBC URL for the database
.maxconn The max number of connections in the pool. 0 means no limit.
.user The user name for the pool
.password The corresponding password

The url property is mandatory but all the others are optional. The user name and the matching password must be valid for the database defined by the URL.

Below is an example of a db.properties file for a Windows platform, with a pool for an MySQL database.

drivers=com.mysql.jdbc.Driver
logfile=D:\\user\\src\\java\\DBConnectionManager\\log.txt
mysql.maxconn=100
mysql.url=jdbc:mysql://localhost:3306/test
mysql.user=root
mysql.password=root
Note that the backslashes (\) in a Windows path must be duplicated since a backslash in a properties file is also used as an escape character.

The init() method creates a Properties object and loads the db.properties file. It then reads the logfile property. If a log file hasn't been specified a file named DBConnectionManager.log in the current directory is used instead. As a last resort, System.err is used for log messages.

The loadDrivers() method loads and registers all JDBC drivers specified by the drivers property.

    private void loadDrivers(Properties props) {
String driverClasses = props.getProperty("drivers");
StringTokenizer st = new StringTokenizer(driverClasses);
while (st.hasMoreElements()) {
String driverClassName = st.nextToken().trim();
try {
Driver driver = (Driver)
Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
drivers.addElement(driver);
log("Registered JDBC driver " + driverClassName);
}
catch (Exception e) {
log("Can't register JDBC driver: " +
driverClassName + ", Exception: " + e);
}
}
}
loadDrivers() uses a StringTokenizer to split the drivers property value into a string for each driver class name and and then loops through all class names. Each class is loaded into the JVM and an instance is created. The instance is then registered with the JDBC DriverManager and added to a private Vector. The drivers Vector is used at shutdown to deregister all drivers from the DriverManager.

Next the DBConnectionPool objects are created by the private createPools() method.

    private void createPools(Properties props) {
Enumeration propNames = props.propertyNames();
while (propNames.hasMoreElements()) {
String name = (String) propNames.nextElement();
if (name.endsWith(".url")) {
String poolName = name.substring(0, name.lastIndexOf("."));
String url = props.getProperty(poolName + ".url");
if (url == null) {
log("No URL specified for " + poolName);
continue;
}
String user = props.getProperty(poolName + ".user");
String password = props.getProperty(poolName + ".password");
String maxconn = props.getProperty(poolName + ".maxconn", "0");
int max;
try {
max = Integer.valueOf(maxconn).intValue();
}
catch (NumberFormatException e) {
log("Invalid maxconn value " + maxconn + " for " +
poolName);
max = 0;
}
DBConnectionPool pool =
new DBConnectionPool(poolName, url, user, password, max);
pools.put(poolName, pool);
log("Initialized pool " + poolName);
}
}
}
An Enumeration of all property names is created and scanned for property names ending with .url. When such a property is found, the pool name is extracted, all properties for the corresponding connection pool are read and a DBConnectionPool object is created and saved in an instance variable named pools. pools is a Hashtable, using the pool name as the key and the DBConnectionPool object as the value.

Get and return a connection

The DBConnectionManager provides the getConnection() and freeConnection() methods used by the clients. All of them take a pool name parameter and relay the call to the corresponding DBConnectionPool object.
    public Connection getConnection(String name) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection();
}
return null;
}

public Connection getConnection(String name, long time) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection(time);
}
return null;
}

public void freeConnection(String name, Connection con) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
pool.freeConnection(con);
}
}

Shutdown

Finally, the DBConnectionManager has a method called release(). This method is used for graceful shutdown of the connection pools. Each DBConnectionManager client must call the static getInstance() method to get a reference to the manager. As you could see above, a client counter variable is used in this method to keep track of the number of clients. The release() method is called by each client during shutdown and the client counter is decremented. When the last client calls release(), the DBConnectionManager calls release() on all DBConnectionPool objects to close all connections.
    public synchronized void release() {
// Wait until called by the last client
if (--clients != 0) {
return;
}

Enumeration allPools = pools.elements();
while (allPools.hasMoreElements()) {
DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
pool.release();
}
Enumeration allDrivers = drivers.elements();
while (allDrivers.hasMoreElements()) {
Driver driver = (Driver) allDrivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
log("Deregistered JDBC driver " + driver.getClass().getName());
}
catch (SQLException e) {
log(e, "Can't deregister JDBC driver: " +
driver.getClass().getName());
}
}
}
When all DBConnectionPool objects have been released, all JDBC drivers are deregistered.

Example of a Servlet using the connection pool

The Servlet API defines a Servlet's life cycle like this:
  1. Servlet is created then initialized (the init() method).
  2. Zero or more service calls from clients are handled (the service() method).
  3. Servlet is destroyed then garbage collected and finalized (the destroy() method).
A Servlet using the connection pool described in this article typically performs the following actions in these methods:
  1. in init(), calls DBConnectionManager.getInstance() and saves the reference in an instance variable.
  2. in service(), calls getConnection(), performs all database operations, and returns the Connection to the pool with freeConnection().
  3. in destroy(), calls release() to release all resources and close all connections.
The following is an example of a simple Servlet using the connection pool classes this way.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
private DBConnectionManager connMgr;

public void init(ServletConfig conf) throws ServletException {
super.init(conf);
connMgr = DBConnectionManager.getInstance();
}

public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException {

res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection con = connMgr.getConnection("mysql");
if (con == null) {
out.println("Can't get connection");
return;
}
ResultSet rs = null;
ResultSetMetaData md = null;
Statement stmt = null;
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM EMPLOYEE");
md = rs.getMetaData();
out.println("Employee data");
while (rs.next()) {
out.println("");
for (int i = 1; i < md.getColumnCount(); i++) {
out.print(rs.getString(i) + ", ");
}
}
stmt.close();
rs.close();
}
catch (SQLException e) {
e.printStackTrace(out);
}
connMgr.freeConnection("mysql", con);
}

public void destroy() {
connMgr.release();
super.destroy();
}
}

Open Source Ajax Frameworks

Google Web Toolkit

Google Web Toolkit (GWT) is an open source Java software development framework that makes writing AJAX applications like Google Maps and Gmail easy for developers who don't speak browser quirks as a second language. Writing dynamic web applications today is a tedious and error-prone process; you spend 90% of your time working around subtle incompatibilities between web browsers and platforms, and JavaScript's lack of modularity makes sharing, testing, and reusing AJAX components difficult and fragile. GWT lets you avoid many of these headaches while offering your users the same dynamic, standards-compliant experience. You write your front end in the Java programming language, and the GWT compiler converts your Java classes to browser-compliant JavaScript and HTML

ICEfaces

ICEfaces is an integrated Ajax application framework that enables Java EE application developers to easily create and deploy thin-client rich Internet applications (RIA) in pure Java. ICEfaces leverages the entire standards-based Java EE ecosystem of tools and execution environments. Rich enterprise application features are developed in pure Java, and in a pure thin-client model. There are no Applets or proprietary browser plug-ins required. ICEfaces applications are JavaServer Faces (JSF) applications, so Java EE application development skills apply directly and Java developers are isolated from doing any JavaScript related development.

DWR

DWR is a Java open source library which allows you to write Ajax web sites. It allows code in a browser to use Java functions running on a web server just as if it was in the browser. DWR works by dynamically generating Javascript based on Java classes. The code does some Ajax magic to make it feel like the execution is happening on the browser, but in reality the server is executing the code and DWR is marshalling the data back and forwards.

Echo2

Echo2 is the next-generation of the Echo Web Framework, a platform for developing web-based applications that approach the capabilities of rich clients. The 2.0 version holds true to the core concepts of Echo while providing dramatic performance, capability, and user-experience enhancements made possible by its new Ajax-based rendering engine.

SweetDEV RIA

SweetDEV RIA is a complete set of world-class Ajax tags in Java/J2EE. It helps you to design Rich GUI in a thin client. SweetDEV RIA provides you Out-Of-The-Box Ajax tags. Continue to develop your application with frameworks like Struts or JSF. SweetDEV RIA tags can be plugged into your JSP pages.

ThinWire

ThinWire is an development framework that allows you to easily build applications for the web that have responsive, expressive and interactive user interfaces without the complexity of the alternatives. While virtually any web application can be built with ThinWire, when it comes to enterprise applications, the framework excels with its highly interactive and rich user interface components.

ItsNat, Natural AJAX

ItsNat is an open source (dual licensed GNU Affero General Public License v3/commercial license for closed source projects) Java AJAX Component based Web Framework. It offers a natural approach to the modern Web 2.0 development. ItsNat simulates a Universal W3C Java Browser in the server. The server mimics the behavior of a web browser, containing a W3C DOM Level 2 node tree and receiving W3C DOM Events using AJAX. Every DOM server change is automatically sent to the client and updated the client DOM accordingly. Consequences: pure (X)HTML templates and pure Java W3C DOM for the view logic. No JSP, no custom tags, no XML meta-programming, no expression languages, no black boxed components where the developer has absolute control of the view. ItsNat provides an, optional, event based (AJAX) Component System, inspired in Swing and reusing Swing as far as possible such as data and selection models, where every DOM element or element group can be easily a component.

Singleton Pattern in Java

The Java Singleton pattern belongs to the family of design patterns that governs the instantiation process. A Singleton is an object that cannot be instantiated. This design pattern suggests that at any time there can only be one instance of a Singleton (object) created by the JVM. You implement the pattern by creating a class with a method that creates a new instance of the class if one does not exist. If an instance of the class exists, it simply returns a reference to that object.

How the Singleton pattern works

Here’s a typical example of Singleton:

public class Singleton {
private final static Singleton INSTANCE = new Singleton();

// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}

public static Singleton getInstance() {
return INSTANCE;
}
}

The classic Singleton does not use direct instantiation of a static variable with declaration — it instantiates a static instance variable in the constructor without checking to see if it already exists:

public class ClassicSingleton {
private static ClassicSingleton INSTANCE = null;
private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new ClassicSingleton();
}
return INSTANCE;
}
}

The Singleton class’s default constructor is made private, which prevents the direct instantiation of the object by other classes using the new keyword. A static modifier is applied to the instance method that returns the Singleton object; it makes this a class level method that can be accessed without creating an object.
When you need Singleton

Singletons are truly useful when you need only one instance of a class, and it is undesirable to have more than one instance of a class.

When designing a system, you usually want to control how an object is used and prevent users (including yourself) from making copies of it or creating new instances. For example, you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.

The Singleton pattern is often used in conjunction with the factory method pattern to create a systemwide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Abstract Windowing Toolkit (AWT). In GUI applications, you often need only one instance of a graphical element per application instance, like the Print dialog box or the OK button.
Watch out for potential problems

Although the Singleton design pattern is one of the simplest design patterns, it presents a number of pitfalls.

Construct in multi-threaded applications
You must carefully construct the Singleton pattern in multi-threaded applications. If two threads are to execute the creation method at the same time when a Singleton does not exist, both must check for an instance of the Singleton, but only one thread should create the new object. The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated. This is a thread-safe version of a Singleton:

public class Singleton
{
// Private constructor suppresses generation a (public) default constructor
private Singleton() {}

private static class SingletonHolder
{
private final static Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance()
{
return SingletonHolder.INSTANCE;
}
}

For an alternative solution, you can add the synchronized keyword to the getInstance() method declaration:

public static synchronized Singleton getInstance()

Think ahead about cloning prevention
You can still create a copy of the Singleton object by cloning it using the Object’s clone() method. To forbid this, you need to override the Object’s clone method, which throws a CloneNotSupportedException exception:

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

Consider making the singleton class final
You may want to make the Singleton class final to avoid sub classing of Singletons that may cause other problems.

Remember about garbage collection
Depending on your implementation, your Singleton class and all of its data might be garbage collected. This is why you must ensure that there must be a live reference to the Singleton class when the application is running.