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.