Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Wednesday, May 13, 2009

Java PureFaces : New JSF Framework

Java PureFaces is a layer on top of JSF that simplifies implementation. The article here is the aggregate of the blog posts that I have written on our blog. The framework is not yet made public, and we are looking to see if there is interest in us releasing it as an open-source project. We are not a JSF framework company; we develop web applications. This framework is a result of our experience with the tools with which we were already working.


We are very interested in getting input from the community on it, so please let us know what you think.


Introduction


Developing the Web Tier is a big part of designing and developing a web application. Many frameworks exist that attempt to improve this part of the development. These frameworks simplify the process, providing ready tools and improving code reuse.


Most frameworks are developed around a web designer/Java developer job split, providing a simple API to the web designers, and an XML/HTML file and a Java API for the developers. Examples are Struts and JSF. Other frameworks are aimed only at Java developers and provide a Swing-like API, allowing the developers to develop a web application with only the Java language. The developer code can be very object oriented and does not need to be concerned about interacting with HTTP/ JSP/Tags etc. An example of this type of framework is GWT.


Building off of both of these, we have created a new framework for Java developers that we call Java PureFaces. This framework is built on the very popular JSF framework, but allows the web tier to be designed completely in Java -- no massive library of JSP/JSF pages or configuration files necessary.


Java PureFaces


A little over a year ago, we started looking for a way to create HTML pages without writing HTML code. It did not make sense that a developer that knows a powerful object-oriented language like Java needs to create and maintain static HTML/JSP/XML pages just because of the HTTP protocol. However, JSF is too raw to work with directly (JSF tags, value bindings, etc.).


Java PureFaces provides a pure Java framework for building the web tier. Java developers can use good object oriented solutions, increase code reuse, speed up development, and simplify code maintenance without worrying about many of the web/http concepts like HTTP, JSP, XML, Tags, HTTP sessions, etc. The API is very simple and easy to learn and use.


Like JSF, Java PureFaces binds object attributes into the GUI, and binds commands and link buttons to object methods. Also, JSF components are used to render the HTML. Unlike JSF, Pure JavaFaces attributes and commands can be bound to any POJO object, not only to a backing bean. An advantage of binding to any POJO object through Java is that the bindings themselves can be tested with JUnit.


Because the framework uses JSF, it is very extensible. In order to create a new component, we can extend the UIComponent JSF class. Also, only a single JSP page and backing bean are necessary as the container for the web application (this simplicity does mean that, like some other frameworks, you cannot refresh the page or use the browser back button).


Compare it to a standard JSF application


To quickly illustrate the simplicity of Java PureFaces, we implemented the JSF guessing number game.


Built in the Java PureFaces framework, it makes sense to create two classes: One to represent the logic and one to represent the view. These classes are:



  • GuessNumber -- will know how to create a random number to guess and will check it the user number matches the guessing number.

  • GuessNumberView -- is responsible to create the GUI and response to the button clicks.


Here is the code from the GuessNumberView object:


public class GuessNumberView extends EntryPage implements Serializable {

private static final long serialVersionUID = -7093024622882061259L;

private static final int minNumber = 0;
private static final int maxNumber = 10;
transient private PurePanelGroup component; //not Serializable in the session
private GuessNumber guessNumber;

public GuessNumberView() {
guessNumber = new GuessNumber(minNumber,maxNumber);
}
/**
* pressing on the submit button will create the the response component
*/
public void guessAction() {
createResponseComponent();
}
/**
* pressing on the back button will create the the guess component
*/
public void backAction() {
createGuessComponent();
}
/**
* pressing on the start button will create the the guess component and reset the number
*/
public void startAction() {
createGuessComponent();
guessNumber.start();
}
private void createGuessComponent() {
component = new PurePanelGroup();
component.setFormId("guessForm");
component.add(new PureOutput("Hi. I'm thinking of a number from " + minNumber + " to "
+ maxNumber + " Can you guess it?").setStyleClass("headerText"));
component.add(new PureInput(guessNumber, "userNumber").addValidator(new LongRangeValidator(maxNumber,
minNumber)).setIsRequired(true));
component.add(new PureErrorMessages(true, false, "list").setStyleClass("errorMessage"));
component.add(new PureButton("Submit", this, "guessAction").setStyleClass("button"));
}

private void createResponseComponent() {
component = new PurePanelGroup();
component.setFormId("guessForm");
if (guessNumber.getIsGuessCurrect()) {
component.add(new PureOutput("Yay! You got it!").setStyleClass("headerText"));
component.add(new PureButton("Start", this, "startAction").setStyleClass("button"));
} else {
component.add(new PureOutput("Sorry, " + guessNumber.getUserNumber() + "
is incorrect.").setStyleClass("headerText"));
component.add(new PureButton("Back", this, "backAction").setStyleClass("button"));
}
}
public UIComponent getRootUIComponent() {
if (component == null) {// only for the first time
createGuessComponent();
}
return component.createUIComponent();
}

public String getBackingBeanName() {
return "root";
}
}

Notice that the code to create the simple GUI, as well as the code that handles the button clicks, is cleanly packaged together. Compare this to the JSF Version.


(You can download this demo here: (RAR), (ZIP), (TGZ). There are also full demo applications on the Solutions page of our website. Both of these were created using Java PureFaces)


Clean and Simple Output


So what does the HTML from Java PureFaces look like? Before discussing exactly how the framework works, I want to show how clean it is to work with; I want to show exactly what mark-up is created. I will use a couple of examples from the previous Guess-A-Number demo to show some examples. I'll start by using a single JSP page for the project:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Java PureFaces guessing number demo</title>
<link rel="stylesheet" href='<c:url value="/theme/demoStyle.css" />' type="text/css">
</head>
<body>
<f:view>
<h:panelGroup binding="#{root.render}"></h:panelGroup>
</f:view>
</body>
</html>

This is all that is needed in the simplest application JSP page. The #{root.render} binding is all that is needed to bind the page to the application. Here is the code of the createGuessComponent from the demo:


private void createGuessComponent() {
component = new PurePanelGroup();
component.setFormId("guessForm");
component.add(new PureOutput("Hi. I'm thinking of a number from " + minNumber + " to " +
maxNumber + " Can you guess it?").setStyleClass("headerText"));
component.add(new PureInput(guessNumber, "userNumber").addValidator(new LongRangeValidator(maxNumber,
minNumber)).setIsRequired(true));
component.add(new PureErrorMessages(true, false, "list").setStyleClass("errorMessage"));
component.add(new PureButton("Submit", this, "guessAction").setStyleClass("button"));
}

which creates this simple view:



and this clean HTML (very CSS-friendly):


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Java PureFaces guessing number demo</title>
<link rel="stylesheet" href='/pureFaces-guessNumber/theme/demoStyle.css' type="text/css">
</head>


<body>
<form id="guessForm" name="guessForm" method="post" action="/pureFaces-guessNumber/demo.jsf"
enctype="application/x-www-form-urlencoded">
<span id="guessForm:pureFaces_root1" class="headerText">Hi. I'm thinking of a number from
0 to 10 Can you guess it?</span>


<table cellpadding="0" cellspacing="0" class="__pureFacesErrorGrid">
<tbody>
<tr>
<td><input id="guessForm:pureFaces_root2" name="guessForm:pureFaces_root2"
type="text" value="0" /></td>
<td></td>
</tr>
</tbody>
</table>

<input id="guessForm:pureFaces_root3" name="guessForm:pureFaces_root3" type="submit" value="Submit"
onclick="if(typeof window.clearFormHiddenParams_guessForm!='undefined')
{clearFormHiddenParams_guessForm('guessForm');}if(typeof window.getScrolling!='undefined')
{oamSetHiddenInput('guessForm','autoScroll',getScrolling());}" class="button" />
<input type="hidden" name="guessForm_SUBMIT" value="1" />

</body>
</html>

There is a table in there that is configured to allow for an error message next to the input box through JSF messaging. If the input field is not required, this can be removed for even simpler HTML.


This example shows that when comparing this mark-up to the Java code that created it, you can see it is almost line for line (there is no error message, so it is not rendered). You can use table-based layouts (using PurePanelGrid instead of PurePanelGroup), or work with more current semantic layouts. Either way, it is very easy to create a view. It is also very easy to manipulate the attributes of the HTML elements, like the style classes in the HTML shown here (class=). The framework model can support any element attribute, such as DOM "Level 0 Events (onclick, onkeypress, etc.) and inline styles (style=), to name a few of the more frequently used attributes, by just chaining them onto the component you are adding.


The Way It Works


Now that we have taken a look at the simplicity of the code and the HTML output, I'll describe how we detached the need for a backing bean so that any object or method can be bound to the page.


For a quick review: Typically, JSP pages are coupled with a backing bean, which contains any Java code used in the page. The backing bean must be defined in the faces-config.xml file, and is the page's interface to the rest of the system.


My point here is that:



  • It is tedious to define and maintain the mapping of beans in the faces-config file, and

  • The JSP page is restricted to accessing methods only in the backing bean.


The designer is forced to maintain a JSP file, an XML, and a java class -
for each page in the system (not to mention the navigation mappings, etc).
Java PureFaces removes this complexity and inflexibility. A backing bean is
required, but only one that is used to tie the whole system to a single JSP
page... and this bean is never really used after this. At least, not for binding
to the page. The objects bound to the page are part of the application. The
magic behind Java PureFaces is simple, yet extremely powerful. There is rarely
a need to touch the faces-config file or the JSP page, yet you can bind to
any method or field in the system. Here is how it works.


There are two main things that make Java Pure Faces work. The key to it is that in JSF, listeners are called before the binding.



  • Command Buttons / Links: When you create a command component through the API, Java PureFaces binds that component to the single backing bean using a dummy method that simply returns "success." The work for these components is performed using ActionListeners. First the binding is tested (for testing in JUnit), and then an ActionListener is created from the parameters entered through the API.

  • Inputs: All input types are set up with a default Value Change Listener directed at the desired field entered through the API. Once again, the bindings are tested first using reflection and will throw exceptions for JUnit testing.


That's all there is to it. The listeners are set up to manipulate the target of the component. It is not how JSF was meant to be used, but isn't that where some of the best uses come from? This work is all done behind the scenes, and completely removes the restrictions of the standard JSP/XML/backing bean combination. Absolutely any property can be manipulated, and any method can be triggered. This design enables the system to be completely object-oriented.


As an example to further clarify how useful Java Pure Faces can be, consider a developer who is using Hibernate and would like to bind an entity directly into a view. Using JSF, all backing beans registered in the faces-config file are instantiated at runtime by JSF. Hibernate also instantiates the entities for you. So in this case, the developer cannot do it; an entity cannot be a backing bean. There need to be extra steps to move data from the page to the entity. In Java PureFaces, this is not an issue. The JSP page binds to any POJO in the system through either a Value Change Listener or Action Listener. Hibernate instantiates the entity and anything in that entity can be bound directly into a view.


Object-Oriented API


For the final topic in this article, I want to talk about how Java PureFaces promotes object-oriented programming.


The PureComponent Interface


All Java PureFaces components implement a single interface, PureComponent, that enable them to be used in the framework. This means that, unlike some other frameworks, you do not have to extend a framework-specific object in order to have the functionality of the framwork. In a language that does not allow double-inheritence, being forced to extend another object creates inflexibility. Instead, it allows any object in the application to contain its own display code. It also allows for the creation of custom components that can be easily used throughout the system.


Component Objects


Component creation is very easy with Java PureFaces. All containers, such as PurePanelGrid and PurePanelGroup, take objects that implement PureComponent, and all components are PureComponents. To create a new custom component, you simply implement the interface and then build whatever component you need.


In this example, a simple component - that approximates an HTML label element - is created. By implementing the PureComponent interface, the object is required to implement the createUIComponent method. Inside this method, the component is created from other building blocks. The rest of the object can contain any getters and setters necessary, along with any helper methods, or really just anything at all.


This particular example makes use of another Java PureFaces convenience object called PureEditableValue. This component is a very simple object that holds a reference to a property, and contains the necessary getter and setter needed to access that property. Through the use of generics, that property can be of any type.


public class LabelAndInputComponent<E> implements PureComponent {

private String label;
private PureEditableValue<E> editableValue;
public LabelAndInputComponent(String label, E value) {
this.label = label;
this.editableValue = new PureEditableValue<E>(value);
}
public PureComponent createUIComponent() {
PurePanelGrid panelGroup = new PurePanelGrid(2);
panelGroup.setStyleClass("panelStyleClass");
panelGroup.add(new PureOutput(label).setStyleClass("lableStyleClass"));
panelGroup.add(new PureInput(editableValue).setStyleClass("inputStyleClass"));
return panelGroup;
}
public E getValue(){
return editableValue.getValue();
}
}

This component can now be used anywhere, as shown in the example below. The component is a completely object-oriented solution that can be tested through JUnit. It can extend anything it wants, and of course can implement as many interfaces as necessary. There is absolutely no restriction on making any object a Java PureFaces component.


//.. Some other view object 
private LabelAndInputComponent<String> label = new LabelAndInputComponent<String>("A Label",
"default text"); // example
public PureComponent createUIComponent() {
// Create a DIV element that contains a label component
PurePanelGroup panelGroup = new PurePanelGroup();
panelGroup.setDivStyleClass("divStyleClass");
panelGroup.add(label);
return panelGroup;
}

Easier Maintenance


The final topic to cover is the ease of maintenance for a Java PureFaces implementation. For this, I will use the LabelAndInputComponent implementation that we just discussed.


Testing Java PureFaces is very easy, and very powerful. Of course, it is already easy to test the non-Java PureFaces parts of the object in JUnit the same way we would any other time. The additional advantage here is that we can test the bindings of the Java PureFaces components as well.


The way it works is that the framework tests every binding (using the Reflection API) prior to adding it to the ActionListener or ValueChangeListener. This functionality is done immediately when building the component, and an exception is thrown if something does not check out correctly. Testing the bindings is as simple as:


public void testLabelAndInputComponentImplementation() {
ThatTestObject obj = new ThatTestObject();
obj.createUIComponent();
}

This simple test creates the component and tests that all bindings are valid and able to be resolved.


And finally there is general maintenance. Everything is inside Java. The views are maintained by editing existing objects and components with the ease of whatever development environment you use. There are no JSP files to maintain, there is no XML to update. Productivity is increased by be able to work on all of the code without having to switch gears and use a separate environment. Changes are immediately available when you rebuild the project.

Friday, April 17, 2009

Object Persistence

One of the most critical tasks that applications have to perform is
to save and restore data. Whether it be a word processing application
that saves documents to disk, a utility that remembers its configuration
for next time, or a game that sets aside world domination for the night,
the ability to store data and later retrieve it is a vital one. Without
it, software would be little more effective that the typewriter - users
would have to re-type the data to make further modifications once the
application exits.





Writing the code for saving data, however, can become boring repetitive
work. First, the programmer must create a specification document for the
proposed file structure. Next, the programmer must implement save and
restore functions that convert object data to & from
primitive data types, and test it with sample data. 


If the application later requires new data to be stored, the file
specification must be modified, as well as the save and restore methods. Take it from someone who's been there -
creating save & restore functions is not a fun task.

The solution to this is object serialization.
Object serialization takes an object's state, and converts it to a
stream of data for you. With object serialization, it's an easy task to
take any object, and make it persistent, without writing custom code to
save object member variables. The object can be restored at a later
time, and even a later location. With persistence, we can move an object
from one computer to another, and have it maintain its state. This very
cool feature, in Java, also happens to be very easy to use.

Serializing
objects


Java makes it easy to serialize objects. Any object
whose class implements the java.io.Serializable interface can be made
persistent with only a few lines of code. No extra methods need to be
added to implement the interface, however - the purpose of the interface
is to identify at run-time which classes can be safely serialized, and
which cannot. You, as a programmer, need only add the implements keyword
to your class declaration, to identify your classes as serializable.

public class UserData implements
java.io.Serializable


Now, once a class is serializable, we can write the object to any
OutputStream, such as to disk or a socket connection. To achieve this,
we must first create an instance of java.io.ObjectOutputStream, and pass
the constructor an existing OutputStream instance.

// Write to disk with FileOutputStream
FileOutputStream f_out = new
FileOutputStream("myobject.data");

// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new
ObjectOutputStream (f_out);

// Write object out to disk
obj_out.writeObject ( myObject );


Note that any Java object that implements the serializable interface
can be written to an output stream this way - including those that are
part of the Java API. Furthermore, any objects that are referenced by a serialized
object will also be stored. This means that arrays, vectors, lists, and
collections of objects can be saved in the same fashion - without the
need to manually save each one. This can lead to significant time and
code savings.

Restoring objects from a serialized state


Reading objects back is almost as easy. The one catch is that at
runtime, you can never be completely sure what type of data to expect. A
data stream containing serialized objects may contain a mixture of
different object classes, so you need to explicitly cast an object to a
particular class. If you've never cast an object before, the procedure
is relatively straightforward. First check the object's class, using the
instanceof operator. Then cast to the correct class.

// Read from disk using FileInputStream
FileInputStream f_in = new
FileInputStream("myobject.data");

// Read object using ObjectInputStream
ObjectInputStream obj_in =
new ObjectInputStream (f_in);

// Read an object
Object obj = obj_in.readObject();

if (obj instanceof Vector)
{
// Cast object to a Vector
Vector vec = (Vector) obj;

// Do something with vector....
}

Further issues with serialization


As you can see, it's relatively easy to serialize an object. Whenever
new fields are added to an object, they will be saved automatically,
without requiring modification to your save and restore code. However,
there are some cases where this behavior is not desirable. For example,
a password member variable might not be safe to transmit to third
parties over a network connection, and might need to be left blank. In
this case, the transient keyword can be used. The
transient field indicates that a particular member variable should not
be saved. Though not used often, it's an important keyword to remember.


public class UserSession implements 
java.io.Serializable
{
String username;
transient String password;
}

Summary


Java's support for object serialization makes the implementation of persistent
objects extremely easy. In contrast, the amount of code required to save
and restore every field of an object is complex and repetitive work. While it is certainly possible to write your own
serialization mechanism, the simplicity of that provided by Java would
be hard to beat.

Serialization benefits programmers by


  • Reducing time taken to write code for save and restoration of
    object or application state

  • Eliminating complexity of save and restore operations, and
    avoiding the need for creating a new file format

  • Making it easier for objects to travel over a network connection.


With relatively little effort, you can apply serialization to a
variety of tasks. Not only do applications benefit from serialization,
but also applets. Rather than specifying a long list of parameters, or
performing time consuming initialization and parsing, an applet can
simple reload a configuration object whose member variables contain all
the information needed to execute. It's not just useful for Java applications - even
applets can make benefit, by loading their configuration details or
parameters. With a little imagination, serialization may just have a
place in your next project.

Singleton Object

For those who haven't heard of design patterns before, or who are familiar with the term but not its meaning, a design pattern is a template for software development. The purpose of the template is to define a particular behavior or technique that can be used as a building block for the construction of software - to solve universal problems that commonly face developers. Think of design code as a way of passing on some nifty piece of advice, just like your mother used to give. "Never wear your socks for more than one day" might be an old family adage, passed down from generation to generation. It's common sense solutions that are passed on to others. Consider a design pattern as a useful piece of advice for designing software.

Design patterns out of the way, let's look at the singleton. By now, you're probably wondering what a singleton is - isn't jargon terrible? A singleton is an object that cannot be instantiated. At first, that might seem counterintuitive - after all, we need an instance of an object before we can use it. Well yes a singleton can be created, but it can't be instantiated by developers - meaning that the singleton class has control over how it is created. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy.

So why would this be useful? Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. I'm sure you can think of a other situations where a singleton would be useful - perhaps you've even used one before without giving it a name. It's a common enough design criteria (not used everyday, but you'll come across it from time to time). The singleton pattern can be applied in any language, but since we're all Java programmers here (if you're not, shame!) let's look at how to implement the pattern using Java.

Preventing direct instantiation

We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.

Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.

We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}


So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.

Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....

Preventing thread problems with your singleton

We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
public static void main(String args[])
throws Exception
{
// Get a singleton
SingletonObject obj =
SingletonObject.getSingletonObject();

// Buahahaha. Let's clone the object
SingletonObject clone =
(SingletonObject) obj.clone();
}
}

Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}

private static SingletonObject ref;
}

Summary

A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.

Monday, July 21, 2008

Sealed Class

A Sealed is a modifer in .NET.The sealed modifier is equivalent to marking a class with the final keyword in Java.We can use this for the following reasons.

1. when youn want to provide security for the class.you declare sealed class.If you declare sealed class the class can not inerited to other class.
2. The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.


using System;
sealed class SealedClass{
public int x;
public int y;
}

class MainClass{
static void Main(){
SealedClass sc = new SealedClass();
sc.x = 110;
sc.y = 150;
Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y);
}
}


Output :
x = 110, y = 150

Sunday, July 20, 2008

Abstract Class

1. Abstract classes are classes that contain one or more abstract
methods.
2. An abstract method is a method that is declared, but contains
no implementation.
3. Abstract classes may not be instantiated, and require subclasses to
provide implementations for the abstract methods.


Let's look at an example of an abstract class, and an abstract method.

Suppose we were modeling the behavior of animals, by creating a class hierachy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an abstract method for making a sound (such as a dog barking, a cow mooing, or a pig oinking).

public abstract Animal
{
public void eat(Food food)
{
// do something with food....
}

public void sleep(int hours)
{
try
{
// 1000 milliseconds * 60 seconds * 60 minutes * hours
Thread.sleep ( 1000 * 60 * 60 * hours);
}
catch (InterruptedException ie) { /* ignore */ }
}

public abstract void makeNoise();
}


Note that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class.

public Dog extends Animal
{
public void makeNoise() { System.out.println ("Bark! Bark!"); }
}

public Cow extends Animal
{
public void makeNoise() { System.out.println ("Moo! Moo!"); }
}

Now you may be wondering why not declare an abstract class as an interface, and have the Dog and Cow implement the interface. Sure you could - but you'd also need to implement the eat and sleep methods. By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.

Monday, July 7, 2008

Navigating with Servlets

The first thing to understand is how a servlet begins and ends. Similar to an applet, the life cycle of the servlet begins with an automatic call to its init method. The init method is called once by the server for initialization and not again for each user request. Because the server creates a single class instance that handles every request of the servlet, performance is greatly improved, eliminating the need to create overhead that would otherwise be necessary if each request required the server to create a new object.

Next, the service method is called, performing the work of the servlet, and passing ServletRequest and ServletResponse objects as needed. These objects collect or pass information such as the values of the named attributes, theIP address of the agent, or the port number on which the request was received.

Lastly, like an applet, it is time to remove a previously loaded servlet instance, the servlet's destroy method is called. This gives the servlet a chance to close database connections, save information to a log file, or perform other cleanup tasks before it is shut down. If you have special cleanup tasks you'd like your servlet to perform before being removed from memory, the destroy is the place to write those instructions.

All three methods, init, service, and destroy, can be overridden.

If you need a servlet to load with customized initialization behavior, you can override the init method using either of the following two formats:

No argument format:

public void init()throws ServletException{

Takes ServletConfig object:

public void init(ServletConfig config)
throws ServletException {
super.init(config);
//Initialization code . .


The latter is used when the servlet needs to be initialized with server information such as:

1. Password files
2. A hit count number
3. Serialized cookie information
4. Data from previous requests

When using the ServletConfig format, create a call to the super.init so that the super class registers the information where the servlet can find it later.

Which format you use depends on what information needs to be known at initialization time. If no information is needed when the servlet is first invoked, then the no argument format may be used.

The Heart of the Servlet

The javax.servlet package and the javax.servlet.http package provide the classes and interfaces to define servlets. HTML servlet classes extend the javax.servlet.http.HttpServlet abstract class, which provides a framework for handling HTTP protocol. Because HttpServlet is abstract your servlet must extend it and override at least one of the following methods:

1. doGetget information such as a document, the results of a database query, or strings passed from the browser.
2. doPost posts information such as data to be stored in a database, user login and password information, or other strings passed from the browser.
3. doPutplaces documents directly on the server.
doDelete deletes information or documents from the server.
4. getServletInfo returns descriptive information about the servlet, possibly its purpose, author, or version number.

These methods are the heart of the servlet, where instructions and the purpose of the servlet are carried out. You will likely only need to use, or override, a few of the methods. RedirectServlet overrides doGet and doPost, but does not need any of the other methods.

public class Example extends HttpServlet {
public void doGet ( HttpServletRequest req,
HttpServletResponse res)

When a client calls a servlet by typing the URL in the browser, submitting a form, or clicking a button on a menu, the servlet's service method checks the HTTP request type, such as POST or GET. This in turn calls doGet, doPOST, doPUT, or doDelete as needed.

You can override the service method without implementing doGet and doPost, but it's generally better to call both doGet and doPost. See the JDC RedirectServlet.

The doPost and doGet Methods

The doPost or doGet methods instruct the server about what it must do, whether printing information back to the client's browser, writing to a database, or simply redirecting the client to a requested URL. Within these methods you will use Java programming syntax to give specific instructions for the servlet to interact between the client and the server.

Servlets to Process Forms

A form is a powerful web site tool, enabling clients to take polls, enter personal information for online shopping, or subscribe to an e-newsletter. In other words, forms turn static web pages into dynamic pages. But a form cannot give instructions to a server. Without an application between the form and the server, the form is useless.

Servlets process form information in three steps:

1. Retrieve or request the data
2. Store or passing the data
3. Respond to the request

RedirectServlet Servlet

As with most servlets, the JDC RedirectServlet imports the following packages:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

Servlets extend the abstract HttpServlet class, whichextends the GenericServlet base class.

public class RedirectServlet extends HttpServlet {
So the servlet collects the parameter NAME and corresponding value as a String pair, the String object must be declared:

private String paramName;

To initialized the servlet with the NAME and value String pair, the init method is overridden, and the ServletConfig object is passed as a parameter. Because errors can occur, such as a bad URL, the throws ServletException is included.

public void init(ServletConfig config)
throws ServletException {

When overriding the init method, call super.init(config). After the call to super.init(config), the servlet can invoke its own getInitParameter method as shown.The getInitParameter method returns a string containing the value of the named initialization parameter, or null if the requested parameter does not exist. Init parameters have a single string value.

super.init(config);
paramName =
config.getInitParameter("paramName");
}

A servlet must override doGet or doPost, depending on whether data is sent by POST or GET in the HTML form. The drawback to overriding only one of these methods is that if production changes the HTML form to call POST instead of GET, the servlet won't work. Generally, it is better to override both methods, as shown below.

RedirectServlet overrides the doGet method and takes two arguments:

HttpServletRequest, with the variable req

HttpServletRequest has useful methods such as getParameter that takes the value of a NAME attribute as a string or null if the parameter does not exist.

HttpServletResponse with the variable res has methods that let you specify outgoing information, such as getWriter, which returns a print writer for writing formatted text responses to the browser, or in this case sendRedirect, which sends a temporary redirect response to the client using the specified redirect location URL.

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect(
request.getParameter(paramName));

The doGet method calls the getParameter method through the request object, passing in the paramName object and its value as a string pair, in this case url and the actual URL. A special sendRedirect method then passes the string to the browser and redirects the user to the desired destination.

The RedirectServlet also forces doPost to call doGet, making it possible to use GET or POST in the HTML form without breaking the servlet.


}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
doGet(request, response);
}
}

As long as the value is not null, the code moves onto the res object and its sendRedirect method, which redirects the client to the URL that was passed to the method.This makes for smooth navigation when a client's browsers cannot support JavaScript, or the user has JavaScript toggled off.

Web site design issues frequently pose challenges because of browser incompatibility, user preferences, and non-browser problems, such as sending information to a database or email address. Servlets serve functionality in these situations, acting as a messenger between HTML pages and the server, or as back-up for other technologies.

RedirectServlet is a short yet reliable servlet that works as back-up to JavaScript, and it doesn't need to deal with browser compatibility, or other client related issues because it works on the server side.

Wednesday, March 12, 2008

Setting Environment Variables

An instruction stored in the MS-DOS environment that controls, for example, how to display the DOS prompt, where to store any temporary files, and the path of directories that DOS searches to find commands. The PATH, COMSPEC, PROMPT, and SET commands in the AUTOEXEC.BAT file all define environment variables.

Environment variables are strings that contain information such as drive, path, or file name. They control the behavior of various programs. For example, the TEMP environment variable specifies the location in which programs place temporary files.

In Windows 95/98/ME, append these lines to the end of your c:\autoexec.bat using notepad, and then reboot your computer:
1. set Temp=%USERPROFILE%\Local Settings\Temp

set TMP=%USERPROFILE%\Local~1\Temp
(Syntax : set variableName=variableValue)

In Windows NT/2000/XP, follow the following steps:
1. Open Control Panel
2. Click the System icon and the window pops up
3. Go to the Advanced pane

4. Click the Environment Variables button

5. There are two seperated windows showing two sets of environment variables. Select the "new" button for the upper window to create a new environment variable.Select the "Edit" button for the upper window to edit an existing environment variable. Probably you need to create the "Temp" and "TEMP" variable, and edit the "PATH" variable.


6. For Example the value of "TEMP" will be %USERPROFILE%\Local Settings\Temp
7. The value of "TMP" will be %USERPROFILE%\Local~1 \Temp.
8. You should add these values to the beginning of your "PATH" variable. If you want to specify any path of the software ,you can set using the path vairable.

For Ex :

set path=C:\Program Files\Java\jdk1.5.0_07;C:\bea\jdk142_05;

The above path specify the path od Java Software.

common predefined environment variables :