6/19/2007

Conversation State on the Client using Applets

The Problem
Web applications often require a large amount of data to be stored to maintain the session state of the clients, spanning multiple requests. There are multiple options to store session state, including hidden form fields, cookies, the web layer (the HTTPSession), the EJB layer (rarely, if you are a fan of stateful session beans), and finally the database. (The last thing you want to do is use your database as a "scratch pad" for each client!) Experience says that storing state information at the database or EJB layer has limitations and performance concerns.

For a browser-based web application, whose architecture is realized through a servlet on the server side, it is typical that we store the client's session state at the server end. This means that we dump the aggregation of the data of all clients into HTTP sessions. As a result, our architectures have inherently given way to overloaded servers that spend more of their energy and potential in maintaining clients' HTTP session state rather than actually serving requests. Yes, we do have the option of scaling the servers to meet the concurrency needs beyond these constraints through clustering or other methods. However, the fact remains that the much of the effort spent by servers in maintaining HTTP state information for each client (in terms of space complexity) is very high compared to the actual servicing of the client requests.

Let's plug in values to see the order of magnitude. Suppose that for a typical web application, an application server stores 300K of data per client HTTP session and is expected to serve 1000 concurrent users. Straight away, 300MB of memory is eaten up by the server's function of maintaining clients' HTTP session states, leaving the rest for actual request processing.

The real problem, the reason that the server is made to store all the HTTP session states of the clients, is that the HTTP protocol is stateless. That means that between two requests, a client communicating through HTTP to a server will lose track of the data stored in the current session or conversation. So, we decided to dump states of all clients on the server. That is exactly the point. Now, let us see an alternative to work around this problem.

A New Approach
Here, I propose an applet-based approach to persist HTTP state information on the client end that can replace some of the techniques discussed above. The idea is to distribute an applet to each client on the first HTTP request. This applet would be persisted as long as the conversation with the server, or according to the business logic. Each client's state information will be tracked using the applet at its own end. Between multiple pages of navigation, the applet would serve as a "session tracker." The applet will be disposed when the conversation is over with the server according to the business logic (for example, the checkout option on an e-shopping site) or when the user closes the browser.

To visualize how it would work for an e-shopping application, we will look at a simple e-book shop that sells different types of books. The application consists of multiple web pages containing books classified just as they are on Amazon.com. As the user navigates the pages in the website, he can keep adding books that he intends to buy to his "shopping cart."

In the traditional method of storing client session state in the server's HTTP session, the browser would post HTTP requests to the server and the server would maintain the shopping cart. Instead, what we are going to do is to update the session state stored in the applet residing the client side. One plus is that we don't communicate over the network here to update session state. Another advantage is that the server is going to bother about a client only when it actually requires server-side processing and validation, not when the user does trivial actions like deleting or modifying his shopping cart.

On login, the server would send back an applet to the user, which acts as the shopping cart for the user throughout the current session. One way to do this is to embed an applet tag in the returned HTML/JSP page, so that the applet is loaded and initialized in the client's browser. This effectively bootstraps the applet as the shopping cart for the user.

Each time the user modifies his shopping cart by adding or removing books or changing the quantity of books purchased, a JavaScript would be invoked, which in turn delegates the call to the applet. But how? The concept here is that when we embedded the applet inside the returned web page, we made it a part of the Document instance in the browser, as per the DOM specification. For a more details on how JavaScript can communicate with an applet, see the Resources section.

Remember, to use the applet as a session tracker, the session state data need to be persisted across pages until the user decides to check out. But we have a problem: when the user clicks to move on to another page, the browser simply moves the existing Document instance to History and creates a new Document. Consequently, our applet--part of the Document--along with the session state data is lost. To overcome this problem, we use a simple yet interesting characteristic of applets:


Limitations
Of course, this approach has all the limitations that any applet-based client has. Applet-flavored user interfaces require a basic Java runtime at the client side. Especially when the application is accessed over the internet, this means that some users need to download and install Java plugins for their browsers. It is easier, however to do that across all user desktops if the application runs within a managed intranet.

Another effect of this approach is that the client machine needs adequate memory to store session data. Since we are deploying our applet as the delegate at the client side to store session state, any memory leaks could crash the user's browser or JVM. To avoid this, memory requirements need to be analyzed and taken care during development.

However, if you are wondering if security is a limitation, think again: our session tracker would be loaded on the AppletClassloader which has strict but customizable security features.

Source : www.java.net

6/16/2007

JAVA KERNEL

The basic idea was that the current Java Runtime Environment is simply too big, and most programs require only a small subset of the functionality.

From Ethan Nicholas's Blog
Building a minimal JRE

The first thing I have to do is establish that this project is feasible. Remember that even though it has been approved, it could alway be un-approved (disapproved?) at any point in the future if things aren't looking good. So I figured I would start out by creating a simple, stripped-down JRE installer that contained only the functionality necessary to run System.out.println("Hello world!"), to get an estimate of the size reduction we could expect.

Stripping out the unecessary classes is easy -- you just run Java with the -verbose option to get a list of all of the classes it loads while running the Hello World program. Those classes are all that we need to include in rt.jar.The real problem is the rest of the functionality. My devel build of the Java 6 JRE contains 683 files totalling 119MB. Many of them are not necessary to run Hello World, but which ones? Determining which files were truly necessary and which weren't could be a tough job, so I made my computer determine it for me.

I wrote a simple program which would iterate through all of the files in the JRE. It would remove a file and then attempt to run the Hello World program using this stripped-down JRE. If the test succeeded, the file was evidently unnecessary. If the test failed, the file was deemed necessary and restored. After going through all of the files in this fashion, I was left with an extremely minimal JRE that could run Hello World and... well, that's about it. But it at least provided a starting point. Building a working installer from this JRE was itself a challenge, because several of the files that weren't necessary to run Hello World were still necessary to successful install the JRE, but I persevered and now have a fully functioning, minimal JRE.

Results
I built two JREs using this methodology: one with a program that prints "Hello World" to System.out, and one with a program that displays an empty

java.awt.Frame. Here are the results:
Java 6 Runtime Environment: 15.5MB
"Hello World" JRE: 2.6MB
java.awt.Frame JRE: 3.5MB

JAVAFx




The Java revolution, which started more than a decade ago, gains even more momentum with today's announcement of JavaFX, a new Java innovation targeted at the billions of consumer devices and computers powered by Java technology. JavaFX is a new family of Java technology-based products that will help content providers create and deploy rich Internet applications (RIA). Available today are the first two JavaFX releases: JavaFX Script and JavaFX Mobile.

A new scripting language, JavaFX Script gives Java developers the power to quickly create content-rich applications for the widest variety of clients, including mobile devices, set-top boxes, desktops, even Blu-ray discs. Content creators now have a simple way to develop content for any Java Powered consumer device.

JavaFX Mobile is a complete software system for mobile devices. It is available via OEM licenses to carriers, handset manufacturers, and other companies that
want to simplify and accelerate the development of a powerful standardized software system that can be leveraged across a wide range of consumer devices. In
addition:

JavaFX allows content creators to create rich media content without relying on developers, including drag and drop of desktop and mobile content to the desktop, something that is not possible in any other RIA. JavaFX Script offers a close integration with other Java components (applications and infrastructure) running on server and client platforms, enabling a rich end-to-end experience for developers and users.

JavaFX Script takes advantage of the Java security model so consumers can securely access assets (e.g., pictures, music files, word documents) on their desktop

JFugue - Music Notepad!

The aim of this open source project is to provide a simple standalone application for composing music and generating MIDI files. The underlying functionality provided by this application comes from its reliance on the JFugue API. The JFugue API provides a simple yet powerful set of classes for playing and saving MIDI files. The user interface that is built on top of this API is based on the NetBeans Platform.

All that the user interface does is enable the user to generate JFugue music strings, without needing to understand what they are, how they work, or what
they're for. For example, when a quarter note is dragged to the "E" line in the clef register of the music sheet, a string consisting of "E5q" is generated
in the Editor (right side of the screen, below the Palette). The JFugue API knows what to do with this string and, when File > Play is selected, the JFugue API plays the note. When File > Save is selected, the complete content of the Editor, which contains all the JFugue music strings in the order in which they were added, is played and then saved as a MIDI file. When a new instrument is selected, a related string is added to the editor, and all subsequent notes are played by the last selected instrument.

A screenshot of the user interface: (more screenshots are available by clicking on the item "Documents & files", in the navigator on the left side)


https://nbjfuguesupport.dev.java.net/source/browse/nbjfuguesupport/

6/15/2007

The Pitfalls of Inheritance

In Object Oriented Programming, inheritance is a commonly used mechanism to model the relationship between two types. However, modelling such relationship without realizing the impact on the overall application may result in unexpected problems. In this article, I will try to present some internal details of inheritance mechanism based on the Java language and highlight some of the problems that a developers should be aware of when using inheritance of types.

Inheritance Defined…
One of the first questions that we should answer is what do we mean by inheritance. The inheritance is a modelling technique of expressing the relationship between a generalized type and a specialized type. This in essence is a way of expressing IS A relationship. For example, we can say Car IS A Vehicle. In such situations, we will say Car inherits from Vehicle. In the world of Java language, this inheritance relationship is expressed with the following semantics.



class Car extends Vehicle {


In this model, Car is a subclass of the Vehicle super class. Now the next question is what we inherit. By default, the subclass inherits all the interfaces and the implementations from the super class. Note that, the use of the word "interface" in this context does not refer to the interface type specific to the Java language. In OO, the "interface" is a function/method that a particular class exposes to the external world. Coming specific to Java, the inheritance relationship guarantees the following:


*The sub class inherits all the public methods and the implementation in the super class.
*The sub class inherits all the protected methods and their implementation in the super class.
*The sub class also inherits all the public and protected member variables from the super class.
*However, constructors are not part of this inheritance model. We shall also see later the invocation relationship of constructors that exists between a sub class and its immediate super
class.

These consequences of inheritance also imply the following things that are vital to how we can use a super class and any sub class of it. In general, when you model and implement an inheritance relationship, you guarantee the following:


*The sub class is capable of accepting all the messages that the super class accepts.
*The sub class can replace the super class anywhere the super class is called for without
affecting the final outcome.



Modifying the Super Class Behavior…
With inheritance mechanism, although the sub class by default inherits all the interfaces and implementations of the super class, it is possible to override any of the implementations in the sub class. It is also perfectly possible to extend the interfaces by adding new methods to the sub class. Both of these are mechanisms to modify or extend the functionality of the super class. For example, consider the following inheritance scenario in Listing 1. public class Vehicle
{
public void stop()
{
//stop the engine

}

public void accelarate()
{

}
}


public class Car extends Vehicle
{

public Car()
{

}

public void stop()
{
//stop the engine
//lock the steering wheel
}

public void switchOnWiper()
{

}

}
Listing 1: The Vehicle-Car interface inheritance


In this example, we have modelled Car IS A Vehicle. The Car class overrides the stop() method implementation of its super class Vehicle. However, it decides to reuse the accelarate() implementation from its super class.
As a result of this inheritance relationship, we will be able to write a VehicleTester class in the following form.
public class VehicleTester
{

public void testVehicle(Vehicle vechicle)
{
//test the accelarate behaviour
vechicle.accelarate();
//test the stop behaviour
vechicle.stop();
}

}
Listing 2. The example benefits of using inheritance relationship


In this example, you can immediately see the benefits of inheritance relationship. We could write a single method accepting a super class type and we are able to pass any sub class to the same method. This greatly reduces the strongly typed nature of code and increases the flexibility of the application module.

Restricting inheritance…
Sometimes in your design you would like to stop some classes and methods being inherited. The final keyword in Java achieves this functionality. When you declare a class to be final, no other sub class of it can be created. Similarly, when you declare a method to be final, no sub class can override that method.


Overriding member variables…
So far we have talked about how can you override the methods declared in the super class. It is also possible to hide the member variables declared in the super class, by declaring a member variable in the sub class with the same name as in super class. The type of the field does not matter, only the name needs to match. Notice that when you hide a member variable in the sub class, you can still access the super class variable by using the super keyword. This means that the member variables cannot be overridden but can only be hidden. It is important to notice this subtle distinction between overriding and hiding.
The logic behind that Java allows the hiding of member variables, is that you can then create a sub class of any super class without detailed knowledge of its internal implementation. This is more in the line of encapsulation.


How it works…


We have just seen how powerful inheritance mechanism is and how relatively it is to implement in real world. We will later in this article examine some of the pitfalls with this inheritance mechanism but for the time being, let us see how the inheritance works in Java.


Object Initialization and Inheritance


When an object is initialized, all the instance variables defined within the class of that object and also all the instance variables defined in its super class get initialized. Consider the following example in Listing 3.


public class Vehicle
{
private String registration;

public void accelarate()
{

}
public void stop()
{
//stop the engine

}
}


public class Car extends Vehicle
{
private String model;

public Car()
{

}

public void stop()
{
//stop the engine
//lock the steering wheel
}

public void switchOnWiper()
{

}


}
Listing 3 A Simple inheritance model


Following this example, we would do the following to create an instance of the Car object: //create a new instance of the Car object
Car car = new Car();
In this, the instance variable of the Car class named model and also the instance variable registration of the super class Vehicle both will get initialized to their default values. By default, the Java Virtual Machine will allocate enough space for all the instance variables of the Object’s own class and all the instance variable in all its super classes. Do not forget that in Java you can have multi-level inheritance, that is a Car IS A Automobile IS A Vehicle. In such cases, the same initialization mechanism will be followed. The initialization chain finally leads to the java.lang.Object class as all the classes in Java implicitly inherits from the Object class.
The important thing is however the order of initialization. According to Java Language Specification, the initialization starts with super class fields and end with the fields declared in the Object’s own class. Thus, in our previous example, the order of initialization will be:
1) All variables in the Object class. (No fields declared)
2) All variables in the Vehicle class. (field registration).
3) All variables in the Car class (field model).
The logic behind this order of initialization is to ensure that you can use a super class variable within a sub class initialization properly.

The Initialization Mechanism…
In Java, the initialization of objects can be done in two ways:
* The static initialization blocks
* The constructor
The static initialization block is invoked only when the Class Loader in Java loads the class. The constructor is not invoked unless you explicitly invoke them in order to initialize an instance of an Object.
In Java the first thing that a constructor does is to invoke another constructor in the super class. In order to fully understand this, I would try to iterate the mechanism in the following points to note.
* In Java if no constructor is explicitly defined for a class, the compiler provides a default no-argument constructor. However, if you explicitly specify a public constructor, compiler will not place any default constructor.
* When the constructor of the sub class is invoked, at first the compiler will invoke the default constructor in the super class recursively up in the tree.
* The super class’s constructor can also be invoked explicitly by using the super() key word.
From within a constructor, you are free to call a super class constructor with any number of arguments. It does not have to be the default constructor only.
* It is important however to note that the order of constructor invocation starts from the Object’s class and proceeds recursively up in the tree. However, if you remember that the order of instance variable initialization proceeds from the base class down to the Object’s class. (Figure 1).
* The previous point coincides with the fact that eventually before a constructor of the Object’s class has finished its job, a constructor of the super class is always called, which will initialize the super class fields.






Figure 1: The Constructor invocation and Object initialisation order
Now that we understand how the inheritance in Java really happens behind the scene, it is time to think more about the implications. At first sight, inheritance is an attractive mechanism. But on second thoughts, we will reveal some of the problems that might arise with the user of inheritance.

The Problem Begins…
The above examples were easy to understand in terms of modelling and coding. What is difficult is how all this magic happens behind the scenes. In fact, we have seen a lot more of what goes on behind the scene than we would think normal. Now, we will probe into the depth of the black magic and who knows we might get scared and leave the stage of inheritance magic all together.

Problem 1
Let us return to our example, and now we come up with something like the following in Listing 4.
public class Vehicle
{
private String registration;

private Vechile(){ }

public void accelarate()
{

}
public void stop()
{
//stop the engine

}
}


public class Car extends Vehicle
{
private String model;

public Car()
{

}

public void stop()
{
//stop the engine
//lock the steering wheel
}

public void switchOnWiper()
{

}


}
Listing 4. New version of the Vehicle-Car relationship implementation


Nothing has changed except we have added two member variables to both the classes and added constructors for the classes. However, the problem begins now that the code does not compile any more!


Lesson 1
The super class in an inheritance relationship cannot have a private constructor. The argument here is that the private constructor stops us from directly instantiating any object of that class. If we really don’t want anyone to create a new object of any class, it cannot possibly be used to represent any Object in an IS-A relationship.
The exceptions to this rule are however the abstract classes and classes that prefer to provide a factory method to obtain instances of that class. The abstract classes are never intended to be initialized as they are abstracts and the compiler will never allow you to do so.
On the other hand, some developers are fanatic about providing factory method as opposed to constructors as means to instantiate objects. It is like providing a static method such as getInstance() as we are used to in implementing "Singleton pattern". The argument here is that you can always change the mechanism of creating instances of that class without affecting the clients of that class.

Problem 2
Now we correct the previous problem and just remove the private constructor; after all it was just a do nothing constructor. But we decide to add another method stop() in the Car class, which returns a boolean if the Car has stopped. Here is code in Listing 5. public class Vehicle
{
private String registration;

public void accelarate()
{

}
public void stop()
{
//stop the engine

}
}


public class Car extends Vehicle
{
private String model;

public Car()
{

}

//The new method//
public boolean stop()
{
//stop the engine
//lock the steering wheel
}

public void switchOnWiper()
{

}


}
Listing 5: Another version of the Vehicle-Car relationship


This class will also not compile. The problem is that the super class already has a method with the same name(stop) but different return type (void).


Lesson 2
The sub class cannot declare a method with the same name of an already existing method in the super class with a different return type. The sub class can however declare a method with the same signature as in super class. We call this "Overriding".
This is called a "fragile base class" problem. The base class is fragile because before you can extend it, you may require the full knowledge of all its sub classes. Otherwise, you might end up in a situation where you add a method with the same signature as in one of the base classes and
the application no longer compiles!


The finale…
You might think that the problems so far described are not really problems as being a Java developer; you would probably know all of it, but it is important to notice that all these, point to a bigger picture and a deeper problem. The problem is that you cannot always trust the inheritance relationship.

* It is too restrictive in the way you have to make the super class available to the sub classes. For example, the presence of a public constructor is a must.
* Both the super class and sub classes need the knowledge of each other before adding any other methods to them. This is fragile in terms of flexibility of design.
* The inheritance in one way violates the principle of encapsulation as sub classes can potentially have access to all data and methods of the super class. However, you can restrict visibility by properly using the access modifiers available in Java.
* The fact that a sub class by default inherits all the implementation and interfaces of the super class makes the constituting API more prone to misuse.

Conclusion
In this article, we have seen the inside of inheritance mechanism in Java and how it works. We have understood some of the problems related to inheritance. A section of the problem arises from the misuse of the inheritance relationship and some are inherent in the inheritance concept itself.
However, as designers and developers we would like to find an alternative. But is there one? There can be arguments both ways. However, to keep the scope of this article simpler, I will just only point to another technique called Composition where one object contains reference to another object. I will present a detailed analysis of Composition and Inheritance in the next article. Until then make sure you understand all that we talked about Inheritance.

4/25/2007

Java HotSpot VM Options

Java HotSpot VM Options


Standard options recognized by the Java HotSpot VM are described on the Java Application Launcher reference pages for Windows, Solaris and Linux. This document deals exclusively with non-standard options recognized by the Java HotSpot VM:

Options that begin with -X are non-standard (not guaranteed to be supported on all VM implementations), and are subject to change without notice in subsequent releases of the JDK.
Options that are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice.


Some Useful -XX Options


Default values are listed for Java SE 6 for Solaris Sparc with -server. Some options may vary per architecture/OS/JVM version. Platforms with a differing default value are listed in the description.

Boolean options are turned on with -XX:+

4/06/2007

Google Gulp!

Quench your thirst for knowledge.






At Google our mission is to organize the world's information and make it useful and accessible to our users. But any piece of information's usefulness derives, to a depressing degree, from the cognitive ability of the user who's using it.
That's why we're pleased to announce Google Gulp (BETA)™ with Auto-Drink™ (LIMITED RELEASE), a line of "smart drinks" designed to maximize your surfing efficiency by making you more intelligent, and less thirsty.

Think fruity. Think refreshing.
Think a DNA scanner embedded in the lip of your bottle reading all 3 gigabytes of your base pair genetic data in a fraction of a second, fine-tuning your individual hormonal cocktail in real time using our patented Auto-Drink™ technology, and slamming a truckload of electrolytic neurotransmitter smart-drug stimulants past the blood-brain barrier to achieve maximum optimization of your soon-to-be-grateful cerebral cortex. Plus, it's low in carbs! And with flavors ranging from Beta Carroty
to Glutamate Grape, you'll never run out of ways to quench your thirst for knowledge.

Google Gulp FaQ!

Unique Package Name...?

By convention, the first part of the package name is the Internet domain name of the class creator, reversed. And thatz why we see many packages starting with com and org...!

Since the Internet domain names are unigue you should follow this agreement. Do not use the package name that already match some domain
name that you are not owner of. Find free name and register it. You can find cheap registration now on Internet, ~$10/year!

Threadophobia

I'am sure that in my program I create 100 new threads and when I use isAlive method it shows often less than 100 threads... I have not killed even one of them!

Good, short and clear explanation I found in Java tutorial on SUN's site:

"The API for the Thread class includes a method called isAlive. The isAlive method returns true if the thread has been started and not stopped. If the isAlive method returns false, you know that the thread either is a New Thread or is Dead. If the isAlive method returns true, you know that the thread is either Runnable or Not Runnable. You cannot differentiate between a New Thread or a Dead thread. Nor can you differentiate between a Runnable thread and a Not Runnable thread."

ShiFter

I have written lines of code with mathematical operators...but i always wonder about shiFters (Shift Operators...Bingo!)...
Why do we need it...? watz the use...? Read on...
1. Make faster integer division/multiplication operations:

4839534 * 4
can be done like this:
4839534 << 2

or

543894 / 2
can be done like this:
543894 >> 1

Shift operations much more faster than multiplication for most of processors.

2. Reassembling byte streams to int values
3. For accelerating operations with graphics since Red, Green and Blue colors coded by separate bytes.
4. Packing small numbers into one single long...

4/02/2007

Which4J

Which4J is a simple utility app that helps you determine where classes are being loaded from. This can be especially helpful in debugging classpath and classloader problems. It serves the same general purpose as the Unix which command except it searches your classpath (or a particular classloader) instead of your shell command path.

Which4J can be run in command-line mode to search your system classpath for all occurrences of the specified classname. More importantly, it can also be used programmatically to search a particular ClassLoader for the first occurrence of the specified classname or Class instance. This can be extremely valuable when trying to debug problems in web containers and application servers that have sophisticated ClassLoader hierarchies.

The following snippet of code shows how simple it is to figure out where a particular classloader is loading a particular class from:







System.out.println(org.theshoemakers.which4j.Which4J.which( java.lang.String.class ) );


And here is the output:


jar:file:/D:/jdk1.4.1_03/jre/lib/rt.jar!/java/lang/String.class

Download which4J

4/01/2007

404 - Error Page...

Are these self explanatory to someone whoz new to computers?
if no read on...





We understand what 404 means: Page Not Found. But the average internet user has no idea what 404 means or what to do about it. To them, it's yet another unintelligible error message from the computer. Most 404 pages are unvarnished geek-speak.

One of the best error pages I've ever seen is/was from Dunstan's 1976 Design blog . I think it hits most of your points for a good error page, although it doesn't automatically search and it doesn't automatically send an error report (although it comes awfully close with a simple "submit quick error report" that requires no forms to fill out).

3/31/2007

Tiger Provided option for getting various Thread States

Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two. Starting with the release of Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time.

NEW A Fresh thread that has not yet started to execute.
RUNNABLE A thread that is executing in the Java virtual machine.
BLOCKED A thread that is blocked waiting for a monitor lock.
WAITING A thread that is wating to be notified by another thread.
TIMED_WAITING A thread that is wating to be notified by another thread for a specific amount of time
TERMINATED A thread whos run method has ended.


The folowing code prints out all thread states.

public class ThreadStates{
public static void main(String[] args){
Thread t = new Thread();
Thread.State e = t.getState();
Thread.State[] ts = e.values();
for(int i = 0; i < ts.length; i++){
System.out.println(ts[i]);
}
}
}

3/29/2007

JPC Project




JPC is a pure Java emulation of an x86 PC with fully virtual peripherals. It runs anywhere you have a JVM, whether x86, RISC, mobile phone, set-top box, possibly even your refrigerator! All this, with the bulletproof security and stability of Java technology.

JPC creates a virtual machine upon which you can install your favourite operating system in a safe, flexible and powerful way. It aims to give you complete control over your favorite PC software's execution environment, whatever your real hardware or operating system, and JPC's multilayered security makes it the safest solution for running the most dangerous software in quarantine - ideal for archiving viruses, hosting honeypots, and protecting your machine from malicious or unstable software.

JPC has been developed since August 2005 in Oxford University's Subdepartment of Particle Physics. It can be run on a number of devices, from PC's to mobile phones, and you can see some of the results of JPC in action (more soon!). Some might see JPC as part of a nefarious plot by mad scientists who want to harness every last CPU in the world for their research - but we prefer to see JPC as Java-hardened protection against their buggy programs.

3/28/2007

Faster Deep Copies of Java Objects ( Shallow Copy and Deep Copy )

Faster Deep Copies of Java Objects

The java.lang.Object root superclass defines a clone() method that will, assuming the subclass implements the java.lang.Cloneable interface, return a copy of the object. While Java classes are free to override this method to do more complex kinds of cloning, the default behavior of clone() is to return a shallow copy of the object. This means that the values of all of the origical object’s fields are copied to the fields of the new object.

A property of shallow copies is that fields that refer to other objects will point to the same objects in both the original and the clone. For fields that contain primitive or immutable values (int, String, float, etc…), there is little chance of this causing problems. For mutable objects, however, cloning can lead to unexpected results. Figure 1 shows an example.



import java.util.Vector;


public class Example1 {


public static void main(String[] args) {

// Make a Vector

Vector original = new Vector();


// Make a StringBuffer and add it to the Vector

StringBuffer text = new StringBuffer(”The quick brown fox”);

original.addElement(text);


// Clone the vector and print out the contents

Vector clone = (Vector) original.clone();

System.out.println(”A. After cloning”);

printVectorContents(original, “original”);

printVectorContents(clone, “clone”);

System.out.println(

“——————————————————–”);

System.out.println();


// Add another object (an Integer) to the clone and

// print out the contents

clone.addElement(new Integer(5));

System.out.println(”B. After adding an Integer to the clone”);

printVectorContents(original, “original”);

printVectorContents(clone, “clone”);

System.out.println(

“——————————————————–”);

System.out.println();


// Change the StringBuffer contents

text.append(” jumps over the lazy dog.”);

System.out.println(”C. After modifying one of original’s elements”);

printVectorContents(original, “original”);

printVectorContents(clone, “clone”);

System.out.println(

“——————————————————–”);

System.out.println();

}


public static void printVectorContents(Vector v, String name) {

System.out.println(” Contents of \”" + name + “\”:”);


// For each element in the vector, print out the index, the

// class of the element, and the element itself

for (int i = 0; i < v.size(); i++) {

Object element = v.elementAt(i);

System.out.println(” ” + i + ” (” +

element.getClass().getName() + “): ” +

element);

}

System.out.println();

}


}



Figure 1. Modifying Vector contents after cloning

In this example we create a Vector and add a StringBuffer to it. Note that StringBuffer (unlike, for example, String is mutable — it’s contents can be changed after creation. Figure 2 shows the output of the example in Figure 1.



> java Example1


A. After cloning

Contents of “original”:

0 (java.lang.StringBuffer): The quick brown fox


Contents of “clone”:

0 (java.lang.StringBuffer): The quick brown fox


——————————————————–


B. After adding an Integer to the clone

Contents of “original”:

0 (java.lang.StringBuffer): The quick brown fox


Contents of “clone”:

0 (java.lang.StringBuffer): The quick brown fox

1 (java.lang.Integer): 5


——————————————————–


C. After modifying one of original’s elements

Contents of “original”:

0 (java.lang.StringBuffer): The quick brown fox jumps over the lazy dog.


Contents of “clone”:

0 (java.lang.StringBuffer): The quick brown fox jumps over the lazy dog.

1 (java.lang.Integer): 5


——————————————————–



Figure 2. Output from the example code in Figure 1

In the first block of output (”A”), we see that the clone operation was successful: The original vector and the clone have the same size (1), content types, and values. The second block of output (”B”) shows that the original vector and its clone are distinct objects. If we add another element to the clone, it only appears in the clone, and not in the original. The third block of output (”C”) is, however, a little trickier. Modifying the StringBuffer that was added to the original vector has changed the value of the first element of both the original vector and its clone. The explanation for this lies in the fact that clone made a shallow copy of the vector, so both vectors now point to the exact same StringBuffer instance.

This is, of course, sometimes exactly the behavior that you need. In other cases, however, it can lead to frustrating and inexplicable errors, as the state of an object seems to change “behind your back”.

The solution to this problem is to make a deep copy of the object. A deep copy makes a distinct copy of each of the object’s fields, recursing through the entire graph of other objects referenced by the object being copied. The Java API provides no deep-copy equivalent to Object.clone(). One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of an instance of one of your classes. This may be the best solution if you need a complex mixture of deep and shallow copies for different fields, but has a few significant drawbacks:


  1. You must be able to modify the class (i.e., have the source code) or implement a subclass. If you have a third-party class for which you do not have the source and which is marked final, you are out of luck.
  2. You must be able to access all of the fields of the class’s superclasses. If significant parts of the object’s state are contained in private fields of a superclass, you will not be able to access them.
  3. You must have a way to make copies of instances of all of the other kinds of objects that the object references. This is particularly problematic if the exact classes of referenced objects cannot be known until runtime.
  4. Custom deep copy methods are tedious to implement, easy to get wrong, and difficult to maintain. The method must be revisited any time a change is made to the class or to any of its superclasses.

A common solution to the deep copy problem is to use Java Object Serialization (JOS). The idea is simple: Write the object to an array using JOS’s ObjectOutputStream and then use ObjectInputStream to reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct referenced objects. JOS takes care of all of the details: superclass fields, following object graphs, and handling repeated references to the same object within the graph. Figure 3 shows a first draft of a utility class that uses JOS for making deep copies.



import java.io.IOException;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.ObjectOutputStream;

import java.io.ObjectInputStream;


/**

* Utility for making deep copies (vs. clone()’s shallow copies) of

* objects. Objects are first serialized and then deserialized. Error

* checking is fairly minimal in this implementation. If an object is

* encountered that cannot be serialized (or that references an object

* that cannot be serialized) an error is printed to System.err and

* null is returned. Depending on your specific application, it might

* make more sense to have copy(…) re-throw the exception.

*

* A later version of this class includes some minor optimizations.

*/

public class UnoptimizedDeepCopy {


/**

* Returns a copy of the object, or null if the object cannot

* be serialized.

*/

public static Object copy(Object orig) {

Object obj = null;

try {

// Write the object out to a byte array

ByteArrayOutputStream bos = new ByteArrayOutputStream();

ObjectOutputStream out = new ObjectOutputStream(bos);

out.writeObject(orig);

out.flush();

out.close();


// Make an input stream from the byte array and read

// a copy of the object back in.

ObjectInputStream in = new ObjectInputStream(

new ByteArrayInputStream(bos.toByteArray()));

obj = in.readObject();

}

catch(IOException e) {

e.printStackTrace();

}

catch(ClassNotFoundException cnfe) {

cnfe.printStackTrace();

}

return obj;

}


}



Figure 3. Using Java Object Serialization to make a deep copy

Unfortunately, this approach has some problems, too:


  1. It will only work when the object being copied, as well as all of the other objects references directly or indirectly by the object, are serializable. (In other words, they must implement java.io.Serializable.) Fortunately it is often sufficient to simply declare that a given class implements java.io.Serializable and let Java’s default serialization mechanisms do their thing.
  2. Java Object Serialization is slow, and using it to make a deep copy requires both serializing and deserializing. There are ways to speed it up (e.g., by pre-computing serial version ids and defining custom readObject() and writeObject() methods), but this will usually be the primary bottleneck.
  3. The byte array stream implementations included in the java.io package are designed to be general enough to perform reasonable well for data of different sizes and to be safe to use in a multi-threaded environment. These characteristics, however, slow down ByteArrayOutputStream and (to a lesser extent) ByteArrayInputStream.

The first two of these problems cannot be addressed in a general way. We can, however, use alternative implementations of ByteArrayOutputStream and ByteArrayInputStream that makes three simple optimizations:


  1. ByteArrayOutputStream, by default, begins with a 32 byte array for the output. As content is written to the stream, the required size of the content is computed and (if necessary), the array is expanded to the greater of the required size or twice the current size. JOS produces output that is somewhat bloated (for example, fully qualifies path names are included in uncompressed string form), so the 32 byte default starting size means that lots of small arrays are created, copied into, and thrown away as data is written. This has an easy fix: construct the array with a larger inital size.
  2. All of the methods of ByteArrayOutputStream that modify the contents of the byte array are synchronized. In general this is a good idea, but in this case we can be certain that only a single thread will ever be accessing the stream. Removing the synchronization will speed things up a little. ByteArrayInputStream’s methods are also synchronized.
  3. The toByteArray() method creates and returns a copy of the stream’s byte array. Again, this is usually a good idea: If you retrieve the byte array and then continue writing to the stream, the retrieved byte array should not change. For this case, however, creating another byte array and copying into it merely wastes cycles and makes extra work for the garbage collector.

An optimized implementation of ByteArrayOutputStream is shown in Figure 4.


import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.ByteArrayInputStream;


/**

* ByteArrayOutputStream implementation that doesn’t synchronize methods

* and doesn’t copy the data on toByteArray().

*/

public class FastByteArrayOutputStream extends OutputStream {

/**

* Buffer and size

*/

protected byte[] buf = null;

protected int size = 0;


/**

* Constructs a stream with buffer capacity size 5K

*/

public FastByteArrayOutputStream() {

this(5 * 1024);

}


/**

* Constructs a stream with the given initial size

*/

public FastByteArrayOutputStream(int initSize) {

this.size = 0;

this.buf = new byte[initSize];

}


/**

* Ensures that we have a large enough buffer for the given size.

*/

private void verifyBufferSize(int sz) {

if (sz > buf.length) {

byte[] old = buf;

buf = new byte[Math.max(sz, 2 * buf.length )];

System.arraycopy(old, 0, buf, 0, old.length);

old = null;

}

}


public int getSize() {

return size;

}


/**

* Returns the byte array containing the written data. Note that this

* array will almost always be larger than the amount of data actually

* written.

*/

public byte[] getByteArray() {

return buf;

}


public final void write(byte b[]) {

verifyBufferSize(size + b.length);

System.arraycopy(b, 0, buf, size, b.length);

size += b.length;

}


public final void write(byte b[], int off, int len) {

verifyBufferSize(size + len);

System.arraycopy(b, off, buf, size, len);

size += len;

}


public final void write(int b) {

verifyBufferSize(size + 1);

buf[size++] = (byte) b;

}


public void reset() {

size = 0;

}


/**

* Returns a ByteArrayInputStream for reading back the written data

*/

public InputStream getInputStream() {

return new FastByteArrayInputStream(buf, size);

}


}



Figure 4. Optimized version of ByteArrayOutputStream

The getInputStream() method returns an instance of an optimized version of ByteArrayInputStream that has unsychronized methods. The implementation of FastByteArrayInputStream is shown in Figure 5.



import java.io.InputStream;

import java.io.IOException;


/

* ByteArrayInputStream implementation that does not synchronize methods.

*/

public class FastByteArrayInputStream extends InputStream {

/

* Our byte buffer

*/

protected byte[] buf = null;


/

* Number of bytes that we can read from the buffer

*/

protected int count = 0;


/

* Number of bytes that have been read from the buffer

*/

protected int pos = 0;


public FastByteArrayInputStream(byte[] buf, int count) {

this.buf = buf;

this.count = count;

}


public final int available() {

return count - pos;

}


public final int read() {

return (pos < count) ? (buf[pos++] & 0xff) : -1;

}


public final int read(byte[] b, int off, int len) {

if (pos >= count)

return -1;


if ((pos + len) > count)

len = (count - pos);


System.arraycopy(buf, pos, b, off, len);

pos += len;

return len;

}


public final long skip(long n) {

if ((pos + n) > count)

n = count - pos;

if (n < 0)

return 0;

pos += n;

return n;

}


}



Figure 5. Optimized version of ByteArrayInputStream.

Figure 6 shows a version of a deep copy utility that uses these classes:



import java.io.IOException;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.ObjectOutputStream;

import java.io.ObjectInputStream;


/**

* Utility for making deep copies (vs. clone()’s shallow copies) of

* objects. Objects are first serialized and then deserialized. Error

* checking is fairly minimal in this implementation. If an object is

* encountered that cannot be serialized (or that references an object

* that cannot be serialized) an error is printed to System.err and

* null is returned. Depending on your specific application, it might

* make more sense to have copy(…) re-throw the exception.

*/

public class DeepCopy {


/**

* Returns a copy of the object, or null if the object cannot

* be serialized.

*/

public static Object copy(Object orig) {

Object obj = null;

try {

// Write the object out to a byte array

FastByteArrayOutputStream fbos =

new FastByteArrayOutputStream();

ObjectOutputStream out = new ObjectOutputStream(fbos);


out.writeObject(orig);

out.flush();

out.close();


// Retrieve an input stream from the byte array and read

// a copy of the object back in.

ObjectInputStream in =

new ObjectInputStream(fbos.getInputStream());

obj = in.readObject();

}

catch(IOException e) {

e.printStackTrace();

}

catch(ClassNotFoundException cnfe) {

cnfe.printStackTrace();

}

return obj;

}


}



Figure 6. Deep-copy implementation using optimized byte array streams

The extent of the speed boost will depend on a number of factors in your specific application (more on this later), but the simple class shown in Figure 7 tests the optimized and unoptimized versions of the deep copy utility by repeatedly copying a large object.



import java.util.Hashtable;

import java.util.Vector;

import java.util.Date;


public class SpeedTest {


public static void main(String[] args) {

// Make a reasonable large test object. Note that this doesn’t

// do anything useful — it is simply intended to be large, have

// several levels of references, and be somewhat random. We start

// with a hashtable and add vectors to it, where each element in

// the vector is a Date object (initialized to the current time),

// a semi-random string, and a (circular) reference back to the

// object itself. In this case the resulting object produces

// a serialized representation that is approximate 700K.

Hashtable obj = new Hashtable();

for (int i = 0; i < 100; i++) {

Vector v = new Vector();

for (int j = 0; j < 100; j++) {

v.addElement(new Object[] {

new Date(),

"A random number: " + Math.random(),

obj

});

}

obj.put(new Integer(i), v);

}


int iterations = 10;


// Make copies of the object using the unoptimized version

// of the deep copy utility.

long unoptimizedTime = 0L;

for (int i = 0; i < iterations; i++) {

long start = System.currentTimeMillis();

Object copy = UnoptimizedDeepCopy.copy(obj);

unoptimizedTime += (System.currentTimeMillis() - start);


// Avoid having GC run while we are timing...

copy = null;

System.gc();

}


// Repeat with the optimized version

long optimizedTime = 0L;

for (int i = 0; i < iterations; i++) {

long start = System.currentTimeMillis();

Object copy = DeepCopy.copy(obj);

optimizedTime += (System.currentTimeMillis() - start);


// Avoid having GC run while we are timing...

copy = null;

System.gc();

}


System.out.println("Unoptimized time: " + unoptimizedTime);

System.out.println(" Optimized time: " + optimizedTime);

}


}



Figure 7. Testing the two deep copy implementations.

A few notes about this test:


  • The object that we are copying is large. While somewhat random, it will generally have a serialized size of around 700 Kbytes.
  • The most significant speed boost comes from avoid extra copying of data in FastByteArrayOutputStream. This has several implications:

    1. Using the unsynchronized FastByteArrayInputStream speeds things up a little, but the standard java.io.ByteArrayInputStream is nearly as fast.
    2. Performance is mildly sensitive to the initial buffer size in FastByteArrayOutputStream, but is much more sensitive to the rate at which the buffer grows. If the objects you are copying tend to be of similar size, copying will be much faster if you initialize the buffer size and tweak the rate of growth.

  • Measuring speed using elapsed time between two calls to System.currentTimeMillis() is problematic, but for single-threaded applications and testing relatively slow operations it is sufficient. A number of commercial tools (such as JProfiler) will give more accurate per-method timing data.
  • Testing code in a loop is also problematic, since the first few iterations will be slower until HotSpot decides to compile the code. Testing larger numbers of iterations aleviates this problems.
  • Garbage collection further complicates matters, particularly in cases where lots of memory is allocated. In this example, we manually invoke the garbage collector after each copy to try to keep it from running while a copy is in progress.

These caveats aside, the performance difference is sigificant. For example, the code as shown in Figure 7 (on a 500Mhz G3 Macintosh iBook running OSX 10.3 and Java 1.4.1) reveals that the unoptimized version requires about 1.8 seconds per copy, while the optimized version only requires about 1.3 seconds. Whether or not this difference is signficant will, of course, depend on the frequency with which your application does deep copies and the size of the objects being copied.

3/27/2007

Comparing Arrays, Lists, and Maps

Generally when we tend to use either Arryalist/ Vector based on the basic requirement if that has to be synchronized or not. Other than that we minimally consider the responsiveness of the algorithmic implementation for each at the requirements.

For example: if we know there will be 10 objects that we need to store and iterated every time. Given the fancy of API we normally tend to use ArrayList / Vector irrespective of thinking of Array which is more powerful and very good implementation for known size.

There are several other parameters we might need to understand as developers which implementation that we need to choose based on the requirements. Some of them could be

1. Insert elements at the end of a list
2. Insert elements in the beginning of a list
3. Insert elements at random positions in a list
4. Access elements from the first to the last
5. Access elements from the last to the first
6. Access elements in random order
7. Update elements in random order


Here is an excellent article that explains the collection on a case to case basis

XML as database

Here is how you can connect to the database:
try { 
//Load the DB2 JDBC Type 2 Driver with DriverManager
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
}catch (ClassNotFoundException e) {
e.printStackTrace();
}

Getting connection:
connection = DriverManager.getConnection(url, user, pass);
the prepare statement:PreparedStatement stmt = connection.prepareStatement(sql);
Result Set:
option 1:ResultSet resultSet = stmt.executeQuery();
option 2:InputStream inputStream = resultSet.getBinaryStream(1);
option 3:DB2Xml db2xml = (DB2Xml) resultSet.getObject(1);

Selecting a XML value:String sql = "SELECT PID, DESCRIPTION from XMLPRODUCT where PID = ?";
PreparedStatement stmt = connection.prepareStatement(sql);stmt.setString(1, "100-105-09");
ResultSet resultSet = stmt.executeQuery();
String xml = resultSet.getString("DESCRIPTION"); // orInputStream inputStream = resultSet.getBinaryStream("DESCRIPTION"); // orReader reader = resultSet.getCharacterStream("DESCRIPTION"); // orDB2Xml db2xml = (DB2Xml) resultSet.getObject("DESCRIPTION");


you can use other methods available in java too..!

getString( )
getBinaryStream( )
getCharacterStrem( )
getObject( )


Inserting in XML file:

String sql = "INSERT INTO xmlproduct VALUES(?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, "100-105-09");
File binFile = new File("productBinIn.xml");
InputStream inBin = new FileInputStream(xmlFile);
stmt.setBinaryStream(2, inBin, (int) binFile.getLength());stmt.execute();


XML database driver

DWR - Easy AJAX for JAVA

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 consists of two main parts:

  • A Java Servlet running on the server that processes requests and sends responses back to the browser.
    JavaScript running in the browser that sends requests and can dynamically update the webpage.

  • 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.

  • This method of remoting functions from Java to JavaScript gives DWR users a feel much like conventional RPC mechanisms like RMI or SOAP, with the benefit that it runs over the web without requiring web-browser plug-ins.

    Java is fundamentally synchronous where Ajax is asynchronous. So when you call a remote method, you provide DWR with a callback function to be called when the data has been returned from the network.

    The diagram shows how DWR can alter the contents of a selection list as a result of some Javascript event like onclick.



    DWR dynamically generates an AjaxService class in Javascript to match some server-side code. This is called by the eventHandler. DWR then handles all the remoting details, including converting all the parameters and return values between Javascript and Java. It then executes the supplied callback function (populateList) in the example below which uses a DWR utility function to alter the web page.

    3/22/2007

    Generics FAQ

    Know more about Generics....You have a good article that explains generics on a case to case basis

    Generics FAQ

    3/15/2007

    Tomcat Vs OC4J

    Couple of differences between Tomcat and Oracle Application Server (OC4J)...There could be more...

    org.w3c.dom.Document:getElementsByTagName()
    Tomcat (Xerces): doc.getElementsByTagName("SOAP-ENV:Envelope") is valid. It treats the namespace as if it were just part of the tag name.
    OC4J (oraclexmlparserv2): doc.getElementsByTagName("SOAP-ENV:Envelope") is not valid
    Solution: Use doc.getElementsByTagNameNS(). To use this method, you must make sure to call setNamespaceAware(true) on your DocumentBuilderFactory.

    javax.xml.parsers.DocumentBuilderFactory:isNamespaceAware()
    Tomcat (Xerces): Defaults to false
    OC4J (oraclexmlparserv2): Defaults to true (which contradicts the documentation http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#setNamespaceAware(boolean))

    Class:forName()
    Tomcat: Always Throws ClassNotFoundException if the class isn't found
    OC4J: Throws NoClassDefFoundError in some situations if the class isn't found

    3/14/2007

    Are generics fully functional...?

    Consider the snippet,

    Vector <String>strObject = new Vector <String>();
    strObject.add("STR1");
    strObject.add("STR2");


    Now adding an int or any other type of object into this collection would throw a compile time error, which sounds good...!
    //strObject.add(12) -- Compilation error

    On the other hand,
    Vector newVector = strObject;
    newVector.add(12);

    This doesn't throw any compilation errors rather, you see a warning to recompile with -Xlint, which many a times we ignore....!

    serialVersionUID

    static final long serialVersionUID = -4544769666886838818L;

    What does this mean to Gosling's tool..?

    It's used when deSerializing an object, to determine whether that object is compatible with that object's class file in the JVM doing the deserialization. If the serialVersionUID of the class file doesn't match the serialVersionUID of the deserialized object, you'll get an InvalidClassException. If the class file doesn't explicitly declare a serialVersionUID, then the serialization runtime has to compute it, which is a relatively expensive process.

    So what makes the Object that was serialized and its class incompatible?
       1. Deleting fields from the class
       2. Changing the type of a field
       3. Changing a class from Serializable to Externalizable or vice versa


    Keep the Pandoras box closed by adding a serialVersionUID to the class file.

    Firefox killer Application - All Peer

    Fed up with email messages bouncing because your attachments are too big? There's a simple solution -- get a very good new Firefox add-in,   AllPeers .

    It's a simple peer-to-peer file-sharing app. Set it up, select files you want to share, and who you want to share them with, and the person gets a notification. He can then grab them. It's that simple.

    For the moment, AllPeers runs only under Firefox, but expect it to work with Internet Explorer some time in the future. If you've ever had a problem with sending a file via email, it's worth a look..!

    3/09/2007

    Singleton Pattern

    The Objective of the pattern is,at any given time there can be only one instance of a class.

    A singleton pattern can be used to create a Connection Pool. We can have connection object as singleton to avoid wastage of
    resources.

    Steps to create a singleton pattern,

    1. We need to have default constructor of the class as private, which prevents instantiation of the object by other classes.

    2. Define a static method that returns singleton object, If object doesn't exists new object is returned otherwise existing
      object would be returned.

    3. To avoid the object being cloned, override the clone method of the Object class.

    4. If a application is going to be Multithreaded one then there can be chances wherein two therads at the sametime can access the static method which may create more than one instance of the singleton class. To avoid the above scenario we need to have this static method as synchronized.



    class Singleton {
    private static Singleton singletonObject;
    private Singleton{
    }

    public static synchronized Singleton getInstance(){
    if (singletonObject == null){
    singletonObject = new Singleton();
    }
    return singletonObject;
    }

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

    public class SingletonObjectDemo{
    public static void main(String args[]){
    //Singleton obj = new Singleton(); Would cause Compilation error.
    //create the Singleton Object..
    Singleton obj = Singleton.getInstance();

    }
    }

    NoClassDefFoundError Vs ClassNotFoundException

    What..When...?
    I always wonder, why Java is not intelligent enough to fix problems in the code when it knows something goes wrong; rather than throwing just exceptions? May be Gosling wants it that way, saving donuts for him!

    Now read on...

    A.java

    1  public class A{
    2
    3  public static void main(String []s) throws classNotFoundException{
    4    B obj = new B();
    5     // class.forName("B).newInstance()
    6   }
    7
    8  }

    B.java

    1 public class B{
    2 }


    javac A.java
    java A

    This would throw a NoClassDefFoundError. Comment out line 4 and uncomment line 5. Now it would throw ClassNotFoundException.

    ClassNotFoundexception is thrown when an application tries to load in a class through its string name using:


  • The forName method in class Class.



  • The findSystemClass method in class ClassLoader .



  • The loadClass method in class ClassLoader.

  • Otherwise NoClassDefFoundError is thrown.

    The interesting fact is that, this behaves differently when your application runs in OC4j Oracle application server. i.e. your application would throw a NoClassDefFoundError to ClassNotFoundException.

    If you dont want to miss your donut, add two catch blocks in your code...I already missed one..:(

    try{
     
     
     
        }catch(ClassNotFoundexception e1){
        }catch(NoClassDefFoundError e2){
       }

    Added on 9/14/2012:
    Further I also see of there are issues with class initialization, there could be NoClassDefFoundError.

    Once there is an initialization failure, JVM marks the class as bad, and subsequent attempts to use or access the class result in NoClassDefFoundError 

    Web 2.0 in 5 minutes

    Now you just need 5 minutes to know what Web 2.0 is all about.

    3/05/2007

    Google Maps @ Work..!

    In the first part of this article, we will discuss how to integrate a feature-rich map into your application in record time, by using the Google Maps API. The Google Maps API is an easy-to-use JavaScript API that enables you to embed interactive maps directly in your application's web pages. And as we will see, it is easy to extend it to integrate real-time server requests using Ajax.

    Getting started with the Google Maps API is easy. There is nothing to download; you just need to sign up to obtain a key to use the API. There is no charge for publicly accessible sites (for more details, see the Sign up for the Google Maps API page). You need to provide the URL of your website, and, when your application is deployed on a website, your key will only work from this URL. One annoying thing about this constraint is that you need to set up a special key to use for your development or test machines: for the sample code, I had to create a special key for http://localhost:8080/maps, for example.

    Once you have a valid key, you can see the Google Maps API in action. Let's start off with something simple: displaying a map on our web page.

    Although the API is not particularly complicated, working with Google Maps requires a minimal knowledge of JavaScript. You also need to know the latitude and longitude of the area you want to display. If you're not sure, you can find this sort of information on the internet, or even by looking in an atlas!

    The full code listing of our first Google Map is shown here:


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Our first Google Map</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=MYKEY"
    type="text/javascript"></script>
    <script type="text/javascript">

    //<![CDATA[

      function load() {
        if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(-41.5, -185), 5);
       }
      }
    //]]>
    </script>
    </head>
    <body onload="load()" onunload="GUnload()">
    <div id="map" style="width: 420px; height: 420px"></div>
    </body>
    </html>

    The first thing to notice here is the code that fetches the actual JavaScript code from the Google Maps server. You need to supply your key here for the code the work.


    <script src="http://maps.google.com/maps?file=api&v=2&key=MYKEY"
    type="text/javascript">
    </script>


    Next comes the code that actually downloads the map from the server.


    <script type="text/javascript">
    //<![CDATA[
      function load() {
      if (GBrowserIsCompatible()) {
       var map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(-41.5, -187.5), 5);
       }
      }
    //]]>
    </script>


    Finally, in the body, we display the map. The size and shape of the map are taken from the corresponding HTML element. The map is initialized when the page is loaded (via the onload event). In addition, when the user leaves the page, the GUnload() method is called (via the onunload event). This cleans up the map data structure in order to avoid memory leak problems that occur in Internet Explorer.


    <body onload="load()" onunload="GUnload()">
    <div id="map" style="width: 420px; height: 420px"></div>
    </body>


    Panning and Zooming
    Now that we can successfully display a map, let's try to add some zoom functionality. The Google Maps API lets you add a number of different controls to your map, including panning and zooming tools, a map scale, and a set of buttons letting you change between Map and Satellite views. In our example, we'll add a small pan/zoom control and an "Overview map" control, which places a small, collapsible overview map. You add controls using the addControl() method, as shown here:


    function load() {
      if (GBrowserIsCompatible()) {
       var map = new GMap2(document.getElementById("map"));
       map.setCenter(new GLatLng(-41.5, -187.5), 5);
        map.addControl(new GSmallMapControl());
        map.addControl(new GOverviewMapControl());
      }
    }

    2/28/2007

    Static gets serialized..?

    Now dont jump into conclusions before you read this.

    import java.io.*;
    public class Ser implements Serializable {
    static int var = 9;

    void set() {
    var = 100;
    }
    }

    public class DumpSer {
    public static void main(String[] args) throws Exception {
    Ser kk = new Ser();
    kk.set();
    File outFile = new File("out.dmp");
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outFile));
    out.writeObject(kk);
    out.close();
    }
    }

    public class LoadSer {
    public static void main(String[] args) throws Exception {
    File inFile = new File("out.dmp");
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(inFile));
    Ser jj = (Ser)in.readObject();
    in.close();
    System.out.println("Val -> "+jj.var);
    }
    }

    After compilation, first execute:
    > java DumpSer
    Then execute:
    > java LoadSer
    What do you see?

    Reason: Once a class is loaded it remains loaded and all its static fields remain set with any values assign to them. The Thumb rule is Statics's are not serialized but initialized.

    Kitchen Sink Language

    "Throw stuff into the kitchen sink without thinking too hard about whether or not its a good idea. Let folks kick the tires. Those experiences then inform the choice of which features go into the standard. " - James Gosling, 2007

    Enjoy and share the fun of being a part of the Java Compiler Community.

    Kitchen Sink Language

    Dodo Tales: Finally fischy ','

    Why did not the complier complain of having a "," as the final element in an array initialization?

    List initList = Arrays.asList(new Integer[] {
    new Integer(1),
    new Integer(2),
    new Integer(1),
    new Integer(2),
    });

    Why is this a part of Java Language Specification ..?

    2/23/2007

    Congrats Mr.James Gosling...

    The man credited with inventing the Java programming language commonly used on the World Wide Web has been appointed to the Order of Canada.

    James Gosling, a vice-president of Sun Microsystems Inc. of Santa Clara, Calif., has been named an officer of the Order of Canada, the office of the Governor General announced on Monday.

    Read on CBC News...

    2/22/2007

    And finally....WoodStock !

    A new community of Java participants are developing the next generation of User Interface Components for the web, based on Java Server Faces and AJAX. This open source collaboration enables a community of developers to create powerful and intuitive web applications that are accessible and localizable, and which are based on a uniform set of guidelines and components, to help ensure ease of development and ease of use. This is Project WoodStock

    The community adds, "The vision of the Project Woodstock is devoted to providing the best possible web application experience for our customers and communities. That experience will certainly be greatly enriched by the interaction of ideas, information, and techniques that emerge from the cooperation of individuals in the web community, and the rapid introduction of new technologies by members of that community".

    This is really an interesting and cool stuff. There are lots of new features that we can do with eaze. Follow the link to know more...

    Preview
    Download
    Documentation

    2/19/2007

    An intelligent compiler...?

    Janino is a compiler that reads a JavaTM expression, block, class body, source file or a set of source files, and generates JavaTM bytecode that is loaded and executed directly. Janino is not intended to be a development tool, but an embedded compiler for run-time compilation purposes, e.g. expression evaluators or "server pages" engines like JSP.

    JANINO can also be used for static code analysis.

    Click here to download Janino

    2/18/2007

    Dodo Tales: if(true) Lies...?

    I always wonder, if java worries more about syntax and semantics, Why

    if (true);

    is considered to be a valid syntax in Java? Why don't the Compiler complain this? what does this line signify?

    2/17/2007

    Free Java Lectures

    The Free Java Lectures page bills itself as "two semesters of College-Level Java--for free" offers a comprehensive introduction to Java over the course of 28 sessions, from basic language concepts up through commonly-used libraries like servlets, JSP's, and Struts. Each lecture is a presentation file in .pps format, which can be opened with OpenOffice.org.

    Looks good to me...

    Lets add few more to wat we know...

    2/16/2007

    Messages in System Tray

    Many folks are aware that Java SE 6 comes with the new SystemTray and TrayIcon classes that allows an icon to be added to the system tray - or status area or whatever it is called on your platform. One very cool feature that most articles/pieces don't mention is it is possible to display a message similar to the "Low battery" warning produced by laptops or the "Updates are ready to be installed" alert Windows Update displays so often.

    So you wanna try it..?

    Click here to get the code

    Javascript made simple..!

    If your application uses javascript, just give a try with the new framework written completely in javascript. Prototype is a JavaScript Framework that aims to ease development of dynamic web applications.

    Here goes a sample snippet:

    Instead of,
    for (var index = 0; index < myArray.length; ++index) {
    var item = myArray[index];
    // Your code working on item here...
    }

    You can use iterators, such as each :
    myArray.each(function(item) {
    // Your code working on item here...
    });

    There are many overloaded methods and functions too!

    Now what are you waiting for...?
    Download Prototype from www.prototypejs.org

    Tired of seeing that 500 Bad gateway error while deploying a Springboot application in AWS...?

    By default, Spring Boot applications will listen on port 8080. Elastic Beanstalk assumes that the application will listen on port 5000. Th...