Saturday, June 14, 2008

EJB [Stateful Session Bean]

Introduction:
In last article, discussed about Stateless Session Bean with example. In this I will discuss about Stateful Session Bean which is part of EJB, contains information about Stateful Session Bean, advantages, limitations, when to use this bean, and a complete example as well as steps to develop Stateful Session Bean using Sun Java System Application Server 8.2 with Netbeans 5.0. Software and version used in this are:


  • Jdk1.5.0
  • Sun Java System Application Server 8.2
  • Net Beans 5.0
  • EJB 2.2

Definition:
It is a server-side enterprise component that encapsulates the business logic of an application. Implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute “Stateful”. Called "stateful" because they maintain a conversational state with the client, in other word we can say that, a client want to store information across various request, means we want to maintain all actions performed by client, for e.g. Online Shopping Application.

Following are advantages of Stateful Session Bean:

  • Maintains the state of a client
  • Stores client state in instance variable
  • Can used when information need to be used various methods calls

Limitations of Stateful Session Bean:

  • Stateful bean instance can service the requests of a single client only
  • Not having persistent storage mechanism
  • Reduces application scalability

When to Use Stateful Session Beans?

  • The bean's state represents the interaction between the bean and a specific client.
  • The bean needs to hold information about the client across method invocations.
  • The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
  • Behind the scenes, the bean manages the work flow of several enterprise beans.

Life Cycle of Stateful Session Bean
Following figures shows the life cycle stages of a Stateful session Bean. The client initiates the life cycle by invoking the create method. The EJB container instantiates the bean and then invokes the setSessionContext and ejbCreate methods in the session bean. The bean is now ready to have its business methods invoked.

Life Cycle of a Stateful Session Bean

While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by moving it from memory to secondary storage. (Typically, the EJB container uses a least-recently-used algorithm to select a bean for passivation.)

The EJB container invokes the bean's ejbPassivate method immediately before passivating it. If a client invokes a business method on the bean while it is in the passive stage, the EJB container activates the bean, calls the bean's ejbActivate method, and then moves it to the ready stage.

At the end of the life cycle, the client invokes the remove method, and the EJB container calls the bean's ejbRemove method. The bean's instance is ready for garbage collection.

How to Create Stateful Session Bean:

Following are Steps to Create EJB [Stateful Session Bean] with NetBean 5.0 using Sun Java System Application Server 8

  • File -> New Project-> Enterprise -> EJB Module
  • Type Project Name: MyCourseEJB

  • Click on Finish Button.
  • Right Click on MyCourseEJB -> New-> SessionBean

  • EJB Name: Course -> Package : university
  • Session Type: Stateful -> Create Interface : Remote

  • Click on Finish
  • MyCourseEJB -> Source Package -> university
  • Delete CourseRemoteBusiness.java

  • Replace CourseBean with Following Code

//CourseBean.java

package university;

import java.util.Enumeration;
import java.util.Vector;
import javax.ejb.*;

/**
* This is the bean class for the CourseBean enterprise bean.
* @author rahulk
*/
public class CourseBean implements SessionBean
{
private SessionContext context;

String studentName;
String studentRollNo;
Vector selectedCourse;

public void setSessionContext(SessionContext aContext)
{
context = aContext;
}

public void ejbActivate() { }

public void ejbPassivate() { }

public void ejbRemove()
{
studentName = null;
studentRollNo = null;
}

public void ejbCreate(String sName, String sRollNo) throws CreateException
{

if(sName == null)
{
throw new CreateException ("Null Person not allowed");
}
else
{
studentName = sName;
studentRollNo = sRollNo;
}
selectedCourse = new Vector();
}

public String addCourse(String Cname)
{
if (Cname==null)
{
return "";
}
try
{
if(!selectedCourse.isEmpty())
{
Enumeration enumer = selectedCourse.elements();
String title="";
while(enumer.hasMoreElements())
{
title = (String)enumer.nextElement();
if(title!=null)
{
/* Checks whether a same course is again selected.*/
if(Cname.equals(title))
{
return "You have already selected this course";
}
}
} // end of while loop

/* Adds the course in the cart.*/

selectedCourse.addElement(Cname);
} // end of if
else
{
/* Adds the course in the cart.*/
selectedCourse.addElement(Cname);
}
}
catch(Exception e)
{
return "Error : " + e.toString();
}
return "";
}

public String removeCourse(String Cname)
{

/* Removes a course from the cart.*/
boolean result = selectedCourse.removeElement(Cname);
if (result == false)
{
return Cname + "course is not in cart.";
}
return "Course Removed";
}

public Vector getSelectedCourse()
{
return selectedCourse;
}

}

  • Replace CourseRemote with Following Code

//CourseRemote.java

package university;

import java.rmi.RemoteException;
import javax.ejb.EJBObject;
import java.util.Vector;


/**
* This is the remote interface for Course enterprise bean.
*/
public interface CourseRemote extends EJBObject
{

public String addCourse(String cName)throws RemoteException;
public String removeCourse(String cName) throws RemoteException;
public Vector getSelectedCourse() throws RemoteException;
}

  • Replace CourseRemoteHome with Following Code

//CourseRemoteHome.java

package university;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;


/**
* This is the home interface for Course enterprise bean.
*/
public interface CourseRemoteHome extends EJBHome
{

CourseRemote create(String sName, String sRollNo) throws CreateException, RemoteException;

}

  • Right Click on MyCourseEJB -> DeployProject

Step to Create EJB(Stateful Session Bean) Web Client Application

  • File -> New Project -> Category : web -> Web Application

  • Next- > Project Name: MyCourseWeb -> Server : Sun Java System Application Server

  • Click on Finish Button.

Add the Reference of EJB Module to Client

  • MyCourseWeb -> Right Click on Libraries -> Add Project

  • Select the Name of EJB Module [MyCourseEJB] -> Add Project JAR Files

Replace index.jsp page with following code

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Details</title>
</head>
<body bgcolor="pink">

<h1><center>Student Information</center></h1>
<hr>
<br><h2> <center> Please Enter the Following Details !!!</center> </h2> <br>
<form method="get" name="f1" action="courseCart.jsp">

<table align="center">
<tr>
<td> <b>Name of Student : </b></td>
<td> <input type="text" name="stdname" size="20"> </td> </tr>
<tr>
<td> <b>Student Roll Number: </b> </td>
<td> <input type="text" name="stdrollno" size="20"></td>
</tr>
<tr>
<td align="right"> <b><input type="submit" value="Submit"> </b> </td>
<td align="center"> <b> <input type="reset" value="Reset"> </b></td>
</tr>
</table>

</form>
</body>
</html>

Steps to create a JSP file

  • Right click on Web Pages -> New -> JSP…
  • JSP File Name : courseCart

  • Click on Finish Button

Replace courseCart.jsp page with following code

< %@ page import="javax.ejb.*,javax.naming.*, javax.rmi.PortableRemoteObject,java.rmi.RemoteException,university.*,java.util.*" %>

< %!
private CourseRemote course = null;
CourseRemoteHome home=null;
public void _jspInit()
{
/* Locating the stateful session bean.*/
try
{
Context ic = new InitialContext();
Object objRef = ic.lookup("ejb/CourseBean");
home=(CourseRemoteHome)PortableRemoteObject.narrow(objRef, CourseRemoteHome.class);
}
catch(Exception ex){ } } %>
< html> < head>
< title>University Registration Application< /title> < /head>
< body bgcolor="pink">
< form method="get" name="f1">
< %
String stdname = request.getParameter("stdname");
String stdrollno = request.getParameter("stdrollno");
if ( stdname != null && stdname.length() > 0 )
{
if ( stdrollno != null && stdrollno.length() > 0 )
{
/* Creating a bean instance.*/
course = home.create(stdname,stdrollno);
} } %>
< H1>University Registration Application< /h1>
< p>Welcome < %=stdname%> !!!< /p>
< p> Please a Course Subject
< select name=ch size=1>
< option>C, C++< /option> < option>Core Java< /option>
< option>J2EE< /option> < option>VB.NET< /option>
< option>C#.NET< /option> < option>ASP.NET< /option>
< option>Oracle< /option> < option selected value="--"> Select a Course< /option>
< /select> < br>

< % int i=1;
String choice=request.getParameter("ch");
if(choice!=null)
{
if(!choice.equals("--"))
{
String str=course.addCourse(choice); %>
< p> < %=str%>
< % } }
String rmcourse=request.getParameter("c");
if(rmcourse!=null)
{
course.removeCourse(rmcourse);
}
Vector courseList = new Vector();
courseList = course.getSelectedCourse();
Enumeration enumer = courseList.elements(); %>
< form method="get" name="f2">
< p> < p> < table border=1>
< th> Course Name < /th>
< th> Select Course to remove < /th> < % while (enumer.hasMoreElements())
{
String title = (String) enumer.nextElement();
if (title!=null)
{
%>
< tr> < td> < %=title%> < /td>
< td> < input type=radio name=c value='< %=title%> ' > < /td>
< /tr>
< % }
} %>
< /table>
< input type="hidden" name="stdname" size="25" value=< %=stdname%> >

< input type="submit" value="Submit">
< input type="reset" value="Reset">
< /form>
< /body>
< /html>

  • Right Click on MyCourseWeb -> Build Project

  • Right Click on MyCourseWeb -> Run Project

  • Following page is Welcome Page of Web Application using Stateful Session Bean

  • Enter Name of Student : John -> and Roll No. : 101 -> Click on Submit Button

  • Above page will display Welcome message followed by Name of Student
  • Now you are ready to select or remove any course.
  • Select any Course (Core Java)-> Click on Submit

  • Your Selected Course Will display in your Course Cart

  • Select other Course (J2EE)-> Click on Submit Button

  • Select same (Which already in Course Cart) for e.g. J2EE -> Click on Submit

  • Display message “You have already selected this course”

  • Now click on any radio button to remove the course

  • Your checked course is remove from Course Cart

Conclusion:

In this I used Concept of Stateful Session Bean. You can run this example using network with multiple client, will find that every client will get own selected course. Here details of every client stored in instance variable, and values of instance variable used in various method call like addCourse( ), removeCourse( ), getSelectedCourse( ).

Saturday, May 10, 2008

EJB or RMI

RMI and EJB offer technology for the development, installation, and management of distributed Java applications in the enterprise, Java developers frequently ask whether one is a better option than the other for their given architectures. This article provides demonstrations for using RMI and EJB technologies.

Since their introduction in 1997, Remote Method Invocation (RMI) and Enterprise JavaBeans (EJB) have represented a new direction in the development, installation, and management of distributed Java applications in the enterprise. The surprisingly powerful RMI guided Java developers into the world of distributed object transactions, while the componential architecture of EJB greatly simplified the development and management of corporate applications.

Today, Java developers frequently ask whether using EJB is even necessary when they can easily do the same things using only RMI—and vice versa in some cases. Certainly, you can use pure RMI to work with distributed objects in an architecture that also partially uses EJB, but whether you choose RMI or EJB depends almost completely on your needs and the required scalability of your application.

RMI Architecture
The basic objective of RMI is to allow programmers who develop distributed Java applications to use the same syntax and semantics that they use for non-distributed applications. To do this, the creators had to carefully investigate how Java classes and objects function on separate Java Virtual Machines (JVMs) and invent a new model for working with classes and objects accordingly. The new model would have to accommodate environments in which distributed object transactions occur (e.g., on several JVMs).

The architecture of RMI defines:
  • How objects are conducted;
  • How memory management works, in which place;
  • Why exceptions exist; and
  • Which parameters (arguments) are sent into remote methods, and how they return.
RMI technology architecture is based on one principle: “the definition of behavior and the implementation of this behavior should be kept separate”. RMI allows developers to separately store the behavior description and its implementation code on several, separately working JVMs. This concept is ideal for distributed systems where the client needs to know only the definition of a service used and the server directly provides this service (its implementation).
Initially, RMI uses Java interfaces as the definition of the remote service. Accordingly, the implementation of the service is coded in Java classes. So a key to understanding RMI is realizing that interfaces define behavior, while classes define implementation.
Following figure (Figure 1) shows this concept of division.


Figure 1: RMI Concept of Division


RMI in Use
The arithmetic calculator is a simple example of the distributed application, it has almost become the traditional example, and who are we to break tradition? To present an RMI system, this demonstration will carry out the actual calculations on the server side and receive the results on the client side

Remember that interfaces do not contain any executable code. RMI supports two classes that implement these interfaces. The first class directly implements behavior and works on the server side. The second plays the role of proxy for the remote service and works on the client side.

When the client program sends a call of a proxy object method, RMI sends the request to a remote JVM, which sends this request to the implementation code. Any returned values of a called method are sent back to the proxy object and then to the client.

RMI ImplementationRMI implementation consists of three abstract layers:

  • Stub classes, which hide implementation from the developer. This layer intercepts the set interface's methods calls (which the client sends) and redirects them to their remote RMI service.
  • Remote reference layer. This layer knows how to interpret and operate the references from the client to the remote service's objects.
  • Transport layer. This layer works with TCP/IP connections between networked machines. It enables the creation of connections and provides some detour strategies for firewall systems.

This architecture allows developers to replace any of these three layers with a new layer that contains different behavior logic. For example, you can replace a transport layer with a layer that supports UDP/IP protocols. As a result, none of the top layers will be visible.

How does the client define a location for the RMI service (server)? RMI uses simple service called RMI Registry (rmiregistry). RMI Registry must be started on each machine that acts as a storehouse of objects of the remote service (i.e., on a server) and accepts requests/connections to a specified port (the default port is 1099).

On the server side, before creating a remote service, the program first creates a local object, which is an implementation of this service. It then exports this object in RMI, and RMI creates a service that waits for the client's connections and requests. After export, the server registers this object in RMI Registry under a certain public name.

On the client side, the program addresses the RMI Registry with the help of the Naming static class. The program uses the lookup() method of this class to receive a URL string, which defines the names of a server and a desired service. This method returns the remote reference to the service object. The URL usually looks like this:

rmi://[:]/

HOST_NAME is the host name, PORT tells the port number (e.g., 1099 by default) and is not necessarily an argument, and SERVICE_NAME is the name of the service.

A working RMI system consists of the following parts:

  • Remote services interface definitions
  • Remotes services implementation
  • Stub files
  • A server with remote services
  • RMI Naming service, which allows clients to locate remote services
  • Container ("supplier") of Java classes (HTTP or FTP server)
  • A client program, which requires remote services

Definition of InterfacesFor the calculator interface, the remote service offers the following methods:

public interface Calculator extends java.rmi.Remote
{
public long add(long a, long b) throws java.rmi.RemoteException;
public long sub(long a, long b) throws java.rmi.RemoteException;
public long mul(long a, long b) throws java.rmi.RemoteException;
public long div(long a, long b) throws java.rmi.RemoteException;
}
Each of the listed methods can throw out an exception of RemoteException class or its derivatives. Each of these methods carries out a corresponding arithmetic operation (addition, subtraction, multiplication, and division) between two numbers, a and b.

Save all the methods above as Calculator.java and compile them with the following command:

javac Calculator.java

Implement this interface for your server as well. Name the implementation class

CalculatorImpl.java:

public class CalculatorImpl extends java.rmi.server.UnicastRemoteObject implements Calculator
{

// Implementation need to have constructor to define possibility of
// RemoteException
public CalculatorImpl() throws java.rmi.RemoteException {
super();
}
public long add(long a, long b) throws java.rmi.RemoteException {
return a + b;
}
public long sub(long a, long b) throws java.rmi.RemoteException {
return a b;
}
public long mul(long a, long b) throws java.rmi.RemoteException {
return a * b;
}
public long div(long a, long b) throws java.rmi.RemoteException {
return a / b;
}
}
Save all the methods above as CalculatorImpl.java and compile them with the following command

javac CalculatorImpl.java

Each of the methods offered in the implementation performs an arithmetic function.
As you can see, CalculatorImpl.java also extends the UnicastRemoteObject class, directly entering it into the RMI system. You don't have to extend the class to enter it into the RMI system, however. You can take advantage of the exportObject() method instead.

Since the CalculatorImpl class extends UnicastRemoteObject, you also have to define the constructor, designating from which declare it can throw out the RemoteException exception. When the constructor invokes the method super(), it carries out the constructor UnicastRemoteObject code, which communicates with RMI and initializes the remote objects.
The next step is to create the files Stub. You can do this with a special RMI compiler, which enables you to set the name of a class as an argument with the implementation.

For example, enter the following command:

rmic CalculatorImpl
Finally, you need to write the server and client parts for the application. In this case, the following is the server-side code for your calculator:

import java.rmi.Naming;

public class CalculatorServer {
public CalculatorServer() {
try {
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService", c);
} catch (Exception e) {
System.out.println(e.printStackTrace());
}
}
public static void main(String args[]) {
new CalculatorServer();
}
}
As you can see, this class simply creates a copy of the Calculator interface based on its implementation (CalculatorImpl) and assigns it a name in the naming service (with the help of the Naming.rebind() method).


So the client-side code will look like this:
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;

public class CalculatorClient {
public static void main(String[] args) {
try {
Calculator c = (Calculator) Naming.lookup("rmi://localhost/CalculatorService");
System.out.println( c.sub(8, 2) );
System.out.println( c.add(4, 5) );
System.out.println( c.mul(6, 7) );
System.out.println( c.div(8, 2) );
}
catch (Exception e) {
System.out.println(e.printStackTrace());
}
}
}
Execute Your RMI System
Now, having compiled all the classes and created the files Stub, you can execute your RMI system, which requires three separate consoles. In the first one, you start RMI Registry with the command rmiregistry. In the next console, start your server with the command java CalculatorServer. The server will start, load the implementation into memory, and wait for connections from clients. Lastly, start the client application with the command java CalculatorClient.

If everything passes correctly, you will see the following result in the client console:

6
9
42
4


That's it. You have created and tested your own complete RMI system.

EJB Architecture
Enterprise JavaBeans defines the server componential model and the interface for server-vendor-independent programming of Java applications. EJB initially utilized two fundamental models for constructing enterprise applications: the session bean and the entity bean. In the first model (session bean), the client begins a session with an object, which behaves like the application, carrying out units of work on behalf of the client with the ability to perform multiple database transactions. In the second model (entity bean), the client gets access to an object stored in a database, which represents a certain entity. Following figures presents the general architecture of EJB Technology.


General architecture of EJB technology

EJB architecture allows those working with an application server and its components to use absolutely any client. The absence of a precisely fixed, specific protocol makes this possible. The server can support various communication protocols with the client (e.g., RMI, IIOP (CORBA), and DCOM), simultaneously. Therefore, the client does not have to be written in Java.

An EJB server provides a set of services for EJB support. These services include management functions for distributed transactions, distributed objects, and remote object calls, along with low-level system services. More to the point, the EJB server offers all the necessary resources for supporting EJB components.

Using EJB under RMI
A number of scripts are available for the construction of EJB applications and components. EJB development differs depending on what you're creating, whether a session bean component, an entity bean, an integral application, or the whole system, which includes a few of these types at once.

Consider the simple algorithm for developing a session bean component that updates a special account. Developing an EJB component is not, in and of itself, complex. First, you describe the business logic of your component or application using an IDE (e.g., Eclipse or NetBeans). After compilation, pack the components in an EJB JAR file (a JAR archive that contains a serialized copy of the DeploymentDescriptor class). The file contains adjustments for security and various descriptions. Furthermore, you must deploy this component (session bean) into an EJB server with server-specific tools that the vendor bundles with the server. After the deployer (for example, a database administrator) adjusts various specific attributes of this component (e.g., a mode of transactions or a level of security). As soon as the component is established on a server, clients can call remote methods of the received objects.

To demonstrate using EJB under RMI, this section uses an example from the field of electronic commerce: shopping cart. Shopping cart is an abstract container into which the e-shopper puts the goods he or she is going to purchase.

Consider an example of shopping cart as an EJB component. First, you create the remote interface for your component:

public interface ShoppingCart extends javax.ejb.EJBObject

{ boolean addItem(int itemNumber) throws java.rmi.RemoteException;

boolean purchase() throws java.rmi.RemoteException;

}


This interface defines two methods: addItem() and purchase(). The first adds goods to shopping cart, and the second completes the transaction. After that, you must write a class of your component:

public class ShoppingCartEJB implements SessionBean

{

public boolean addItem(int itemNumber)

{ // process of adding any goods into shopping cart // here can be database interaction with the help of JDBC }

public boolean purchase () { // code to proceed with purchasing }

public ejbCreate(String accountName, String account) { // object initializing }

}


Notice this class does not implement the remote interface of the component described previously. The EJBObject class will do that later. Also note that components such as session bean do not support automatic persistence mode. Therefore, direct access to a database should be made in the session bean's methods. For example, in the method purchase() you can use JDBC calls. You can also use them for updating the information in a database (if needed).

The EJBObject class, which a server's EJB container creates during component installation, implements the remote interface. This class operates as a proxy, passing method calls through itself and transferring them to a component (which is deployed on the server).

On the client side, the client should first use the JNDI service to locate the EJBHome object of the required component. In the shopping cart example, you do this with the following code:

public interface CartHome extends javax.ejb.EJBHome

{ Cart create(String customerName, String account) throws RemoteException;

}
Interface CartHome contains a method create(), which the client will call each time it requests a new copy of your component. This method is already implemented in the EJBObject class, so by calling it, the client also calls the ejbCreate() method of your component's class.

Now consider an example of how the code on the client side, which uses a session bean for shopping cart, can look. The client can be a "thin client" (browser) or an application written either in Java or C++ (using CORBA technology). But this article doesn't consider the latter because its covers EJB under RMI, not IIOP.

You can get the EJBHome object for the class ShoppingCart by using the following piece of code:

Context initialContext = new InitialContext();CartHome cartHome = (CartHome) initialContext.lookup("applications/mall/shopping carts");

In this snippet, InitialContext() gets the root of all JNDI names in its hierarchy, lookup() gets the CartHome object, and "applications/mall/shopping carts" is a JNDI path to the required CartHome class. Thus, now you have the cartHome reference to the EJBHome object for getting access to ShoppingCartEJB. However, don't forget that the JNDI naming space can be configured to include EJB containers located on different computers in a network. The client cannot determine the actual arrangement of the EJB container.

The following code shows how the client uses your component's EJBHome object call methods:

ShoppingCartEJB cart = cartHome.create("green","333"); cart.addItem(162);cart.addItem(375);cart.purchase();

Here, you used the create() method to create a new object of the session bean component. The variable cart now contains the reference to a remote EJB object and allows you to call its methods: addItem() and purchase().

Pure RMI or EJB?
Why use EJB when RMI enables you to easily do the same things without it? The answer depends on many factors, but perhaps a better question is 'why not use pure RMI to work with distributed objects even if your architecture partially uses EJB?' In fact, the example application in the previous section would work much faster this way, since you described practically everything independently.

The EJB framework is sufficient as a general framework that you can use in most cases where distributed components are necessary. And with such general use, its code should carry out many checks and have enough logic layers to solve practically any type of problem that comes up. All this results in significant productivity loss, however. Therefore, if the top priority of the application is productivity, the benefit of pure RMI code makes it the logical choice. Besides, you can always bypass the RMI framework altogether and work directly with the Sockets API. But again, understand that whether you choose RMI or EJB depends almost completely on your needs and the required scalability of your application.

Saturday, April 26, 2008

Applet to Applet Communication

The AppletContext class in the java.applet package contains the two member methods getApplet and getApplets. By using those methods, an applet can find other applets and invoke methods on them.
That can only be done if the following security requirements are met:

  • The applets originate from the same server and from the same directory on the server.
  • The applets are running on the same page and in the same browser window.

Those security restrictions may have been designed that way for good reason; however, the latter requirement limits the ways you can make interesting multiapplet interfaces featuring applet-to-applet (a2a) communication.

Using the AppletContext API
Before I explain the alternative a2a-communication mechanism, I will briefly show how the getApplet and getApplets methods work. An applet can find another applet in the same HTML page by either using the getApplet method to look it up by name or using the getApplets method to find all the applets on the page.

Both methods, if successful, return one or more Applet objects to the caller. Once the caller finds an Applet object, it can invoke the Applet's public methods.

Suppose that a snippet of the HTML page looks like this:

<applet code="Applet1" width="400" height="100" name="app1"> </applet> <br> <applet code="Applet2" width="400" height="100" name="app2"> </applet> <br>

By using the name attribute in the applet tag, you can refer to a specific applet in the following way:

Applet theOtherApplet = getAppletContext().getApplet("app1");
theOtherApplet.anyMethod(); //calling any public method

Or, we can use the following code to retrieve all applets on the page:

Enumeration allAppletsOnSamePage = getAppletContext().getApplets();
while(allAppletsOnSamePage.hasMoreElements()) {
Applet appl = (Applet) allAppletsOnSamePage.nextElement();
appl.anyMethod(); //Calling any public method
}

When the calling applet has retrieved one or several applets on the same HTML page, it can call those applets' public methods.

Example:
First Applet Program
//One.java
import javax.swing.*;
import java.awt.*;
public class One extends JApplet
{
JTextArea taOutput;
public void init()
{ getContentPane().setLayout( new FlowLayout());
taOutput = new JTextArea(5,20);
getContentPane().add(taOutput);
}

public void putText(String str)
{
taOutput.append( str + "\n");
}
}
Second Applet Program:
//Two.java
import javax.swing.*;
import java.awt.event.*;
import java.applet.AppletContext;
import java.awt.*;
public class Two extends JApplet implements ActionListener{
JTextField txtInput;
AppletContext ac;
JButton btnSend;
public void init()
{
getContentPane().setLayout( new FlowLayout());
txtInput = new JTextField(25);

getContentPane().add(txtInput);
btnSend = new JButton("Send");

getContentPane().add(btnSend);
btnSend.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
ac = getAppletContext();
One obj = (One) ac.getApplet("One");
if(obj != null)
{
obj.putText(txtInput.getText());
txtInput.setText("");
} }}
AppletToApplet.html file

<HTML> <HEAD> <TITLE> Applet-Applet Communicaton </TITLE> </HEAD>
<BODY BGCOLOR="#FFFFFF"> <h1> Applet-Applet Communicaton </h1>
<applet code="Two" width="400" height="300" name="Two"> </applet>
<br> <hr> <br>
<applet code="One" width="400" height="300" name="One"> </applet>

</BODY> </HTML>

  • Compile Both Program
  • Run the Program
Output 1:

Output after Click on Send Button


Conclusion:
So we can easily communicate one applet to another applet by using AppletContext with following restrictions:

  • The applets originate from the same server and from the same directory on the server.
  • The applets are running on the same page and in the same browser window

Monday, April 21, 2008

Upgrade to Visual Studio 2008

**Step Ahead to Visual Studio 2008**

Introduction

Visual Studio 2008 is carrying new features for developers and software industry. There are some features of Visual Studio 2008 Beta version discussed below:

Multi Targeting Support.
Web Designer and CSS Support.
Database Support Features.
AJAX, ASP.Net and Java Script Support.
Project Designer Support.
Language Integrated Query.


1. Multi Targeting Support:
In each Visual Studio release Microsoft supported a specific version of .Net Framework. For example, With VS 2003 : .Net 1.1 Framework, and With VS 2005 : .Net 2.0.

But with VS 2008 release, “Multi-Targeting” is supported. This means developers will be able to design application of any supporting framework. Developer can choose any type of supporting framework at design time.

In Visual Studio 2008 developer can not choose framework version 1.1, only 2.0, 3.0, 3.5 is supported.


2. Web Designer and CSS Support:

Split view editing is addition to visual studio 2008, till VS 2005 only designer view and code view were available. Main objective of this view is that developer can view HTML view and Design view at the dame time and easily make changes in any of the views. Like as he select a tag in code view, the corresponding elements/controls are selected in design view.
CSS Style Manager is new tool inside the IDE called Manage Styles which shows all CSS style sheets for the page.
It can be also useful when we are in any of the views like design, code and split view. It can be activated by choosing format->CSS Style->Manage Styles from the menu.



Transparent Intellisense Mode is new feature of Visual Studio 2008 While using VS 2005/2003 we often find ourselves escaping out of intellisense in order to better see the code around, and then go back and complete what we were doing.
But VS 2008 provides a new feature which allows us to quickly make the intellisense drop-down list semi-transparent. Just hold down the "Ctrl" key while the intellisense drop-down is visible and we will be able to switch it into a transparent mode that enables us to look at the code beneath without having to escape out of Intellisense.

3. Database Support Features:

The Object Relational Designer (O/R Designer) assists developers in creating and editing the objects (LINQ to SQL entities) that map between an application and a remote database.

Hierarchical update capabilities in Dataset Designer, providing generated code that includes the save logic required to maintain referential integrity between related tables.

Local database caching incorporates an SQL Server Compact 3.5 database into an application and configures it to periodically synchronize the data with a remote database on a server.


4. AJAX, ASP.Net and Java Script Support:

One new feature that developers will find with VS 2008 is its built-in support for JavaScript Intellisense. This makes using JavaScript and building AJAX applications significantly easier. A double click on HTML control in design mode would automatically create a click event to the button and would create the basic skeleton of the JavaScript function.

One new JavaScript feature in VS 2008 is the much-improved support for JavaScript debugging. This makes debugging AJAX applications significantly easier.

We can now set both client-side JavaScript breakpoints and VB/C# server-side breakpoints at the same time on the same page and use a single debugger to step through both the server-side and client-side code in a single debug session. This feature is extremely useful for AJAX applications.

5. Project Designer Support:
Windows Presentation Foundation (WPF) applications have been added to Visual Studio 2008. There are four WPF project types:
WinFX Windows Application
WinFX Web Browser Application
WinFX Custom Control Library
WinFX Service Library
When a WPF project is loaded in the IDE, the user interface of the Project Designer pages lets us specify properties specific to WPF applications.

6. Language Integrated Query:

LINQ is a new feature of Visual Studio 2008 that brings great querying capabilities into the language syntax. LINQ introduces patterns for querying and updating data. A set of new assemblies are provided that enable the use of LINQ with collections, SQL databases, and XML documents.

Conclusion:
This concludes my discourse on enhancement in Visual Studio .Net to Visual Studio .net 2008 Beta for now. I will continue update this article with new features and actual benchmarks in the future.

Thursday, April 10, 2008

Enhancements in Java SE 6

Java SE 6 contains a number of features that make programming easier with Java technology. In this article, we discuss four new features that allow us to do the following:

  • Set file and directory permissions
  • Obtain the free space and usable space on partitions
  • Add Component objects to the tabs of a JTabbedPane
  • Use the popular SwingWorker class in conjunction with Java Foundation Classes/Swing (JFC/Swing) applications

Setting File and Directory Permissions:
You can now set the readable, writable, and executable flag of a file in the local file system. This functionality has been added to the java.io.File class with the following methods:

public boolean setReadable(boolean readable, boolean ownerOnly)
public boolean setReadable(boolean readable)

public boolean setWritable(boolean writable, boolean ownerOnly)
public boolean setWritable(boolean writable)

public boolean setExecutable(boolean executable, boolean ownerOnly)
public boolean setExecutable(boolean executable)

The methods of determining whether a file is readable, writable, or executable remain from the previous version of this platform, Java 2 Platform, Standard Edition (J2SE) 5.0.

public boolean canRead();
public boolean canWrite();
public boolean canExecute();

Obtaining Space Allocation on Disks
Java SE 6 gives us three new methods to determine the amount of space available on the partition represented by a java.io.File object:

public long getTotalSpace();
public long getFreeSpace();
public long getUsableSpace();

Each of these methods returns the requested size, in bytes, of the partition represented by the java.io.File or 0L if a partition cannot be obtained from the File object.


With getFreeSpace() and getUsableSpace(), the returned number of unallocated bytes is, "a hint, but not a guarantee, that it is possible to use most or all of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine."


What's the difference between these two methods?
The getFreeSpace() method returns an instantaneous count of the amount of free space on the partition. The getUsableSpace() method, on the other hand, contains extra functionality to check for write permissions and other operating system restrictions, which returns a better estimate of how much space will be available. If you want to determine whether you have enough disk space before writing to a file, getUsableSpace() will typically give you a more accurate estimate. Note that both of these methods can throw a SecurityException.


Representing Tabs in JTabbedPane with Components :
This is a subtle but valuable change in Swing's JTabbedPane. Previously with JTabbedPane, you were limited to representing a tab with a String, an Icon, or a combination of both. In addition, you could add a tooltip to the tab if you wanted. It is now possible to use a Component to represent the tab in a JTabbedPane.


Although this may bring to mind a number of possibilities, the most common use of this feature will be to add a Close button that will remove the tab from the JTabbedPane.

You can set a Component as a tab using the following method:
public void setTabComponentAt(int index, Component component)

You can get this component with the following method:
public Component getTabComponentAt(int index)

You can test whether a component is used in this JTabbedPane with this method:
public int indexOfTabComponent(Component tabComponent)


Here is sample source code for a tabbed pane that allows you to add and remove tabs dynamically from a JTabbedPane. Note that in this example we have created a JPanel that consists of two components: a JLabel on the left side of the panel (BorderLayout.WEST) and a button with an ImageIcon on the right side of the panel (BorderLayout.EAST).


The graphic used is a 10x10 pixel gif that consists of a small X. In order to keep the size of the button small, we reset its preferred size to the icon's width and height plus two.

//code of TabbedPane
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TabbedPaneExample implements ActionListener {

private JFrame frame;
private JTabbedPane tabbedPane;
private JButton addTabButton;

private ImageIcon closeXIcon;
private Dimension closeButtonSize;

private int tabCounter = 0;

public TabbedPaneExample() {

// Create the tabbed pane.
tabbedPane = new JTabbedPane();

// Create a button that users can press to add a tab to the tabbed pane.
addTabButton = new JButton("Add Tab");
addTabButton.addActionListener(this);

// Create a frame to hold the tabbed pane.
frame = new JFrame();

/* Create an image icon of the small 'X' for use with a close button on teach tab. The gif loaded is a 10x10 graphic with transparency on areas that are not black. */

closeXIcon = new ImageIcon("C:/CloseX.gif");

// Create a Dimension that can be used to size the close buttons.

closeButtonSize = new Dimension(
closeXIcon.getIconWidth()+2,
closeXIcon.getIconHeight()+2);

/* Add the tabbed pane to the center of the graphic and the "Add Tab" button to the south. Then pack it, size it, and show it. */
frame.add(tabbedPane, BorderLayout.CENTER);
frame.add(addTabButton, BorderLayout.SOUTH);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();
frame.setMinimumSize(new Dimension(300, 300));
frame.setVisible(true);

}
public void actionPerformed(ActionEvent e) {
final JPanel content = new JPanel();

// Create a panel that represents the tab and ensure that it is transparent.
JPanel tab = new JPanel();
tab.setOpaque(false);

/ * Create a label and a Close button for the tab. Be sure to set its preferred size to nearly the size of the icon, and create an action listener that will locate the tab and remote it from the tabbed pane. */

JLabel tabLabel = new JLabel("Tab " + (++tabCounter));

JButton tabCloseButton = new JButton(closeXIcon);
tabCloseButton.setPreferredSize(closeButtonSize);
tabCloseButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
int closeTabNumber =
tabbedPane.indexOfComponent(content);
tabbedPane.removeTabAt(closeTabNumber);
}
});

tab.add(tabLabel, BorderLayout.WEST);
tab.add(tabCloseButton, BorderLayout.EAST);

/* Add the tab to the tabbed pane. Note that the first parameter, which would ordinarily be a String that represents the tab title, is null. */
tabbedPane.addTab(null, content);

// Instead of using a String/Icon combination for the tab, use our panel instead.
tabbedPane.setTabComponentAt(tabbedPane.getTabCount()-1, tab);
}
public static void main(String[] args) {
TabbedPaneExample main = new TabbedPaneExample();
}
}
The result is shown in Figure 1.

Figure 1. JTabbedPane With Several JComponents as Tabs

SwingWorker Is Now Included:
Most Swing programmers know that whenever they write event-handling code, such as an ActionListener that gets called when a button is pressed, events need to be processed quickly.

You never want to spend any more time than you have to processing on the event-handling thread, or your Swing graphical user interface (GUI) will become non responsive and be unable to repaint itself efficiently. Taking on a larger task from the event dispatch thread often means kicking off a separate "worker" thread from the event dispatch thread and letting that run in the background. Thus, when writing a multithreaded application using Swing, a programmer needs to keep these two rules in mind:
  • Time-consuming tasks should not be run on the event dispatch thread, which causes the application to become unresponsive. They should be run on a worker thread instead.
  • Updates to Swing components should be performed on the event dispatch thread only.

Because this means that there are at least two threads at play, it helps to have a class that can handle interthread communication. The good news is that the SwingWorker class, which has been a popular solution for some time with Swing programmers, is included in the latest release.

Here is the declaration of SwingWorker from the Javadocs.

public abstract class SwingWorker extends Object
implements RunnableFuture

Note that the declaration contains two generic type variables: T and V. [Generics, a feature that was introduced in J2SE 5.0]. Here are the definitions:

T: the result type returned by this SwingWorker's doInBackground() and get() methods
V: the type used for carrying out intermediate results by this SwingWorker's publish() and process() methods

We'll talk about these methods shortly. First, however, let's introduce the thread architecture that is used with a SwingWorker. To quote from the Javadocs: "There are three threads involved in the life cycle of a SwingWorker:

Current thread: The execute() method is called on this thread. It schedules SwingWorker for the execution on a worker thread and returns immediately. One can wait for the SwingWorker to complete using one of two get() methods.

Worker thread: The doInBackground() method is called on this thread. This is where all background activities should happen. To notify PropertyChangeListeners about bound properties changes, use the firePropertyChange and getPropertyChangeSupport() methods. By default, two bound properties are available: state and progress.

Event dispatch thread: All Swing-related activities occur on this thread. SwingWorker invokes the process() and done() methods and notifies any PropertyChangeListeners on this thread."
Typically, the current thread on which you instantiate the SwingWorker subclass is the event dispatch thread. The SwingWorker then usually follows this series of events:

1. The execute() method is called or run on the event dispatch thread.
2. SwingWorker notifies any PropertyChangeListeners that its state has shifted to SwingWorker.StateValue.STARTED.
3. The doInBackground() method is executed on the worker thread.
4. Once the doInBackground() method completes, the done() method is executed on the current thread.
5. SwingWorker notifies any PropertyChangeListeners that its state has shifted to SwingWorker.StateValue.DONE.

While in the doInBackground() method, you can set an integer progress property that indicates the current progress of the worker thread using the following method:
protected void setProgress(int progress);

Once this method is called, a property change event is fired by SwingWorker to all registered listeners to notify them of the updated progress value.

You can set or add to the final results of the worker thread using one of two methods:

protected void process(V... chunks);
protected void publish(V... chunks);

The latter of these methods, publish(), will take a variable number of objects of some intermediate type V and send them to the process() method for processing. You will typically call the process() method from the doInBackground() thread. The process() method should always be overridden to accept the incoming V parameters and concatenate these intermediate objects somehow into a type T. How the process() method accomplishes this task, of course, depends on the type parameters that are specified in your subclass of SwingWorker.

Meanwhile, on the current thread, you can call one of two get() methods to retrieve the results of the worker thread. The first method, get(), blocks indefinitely until the worker thread has completed. The second method will block for the specified amount of time before retrieving whatever results have been processed.

public T get();
public T get(long timeout, TimeUnit unit);

If you wish to cancel the worker thread before it has finished executing, you can call the cancel() method from the current thread.

public final boolean cancel(boolean mayInterruptIfRunning)

Here, the mayInterruptIfRunning parameter specifies whether the thread executing this task should be interrupted in an attempt to stop the task. Note that calling the cancel() method will fail if the task has already completed, if it has already been cancelled, or if it could not be cancelled for some other reason. If, however, calling the method returns true and this task has not already started when the cancel() method is called, the SwingWorker should never execute.

Conclusion :
Although these features are largely independent of each other, they represent the desire of the Java development.

Tuesday, March 25, 2008

Advantages of XML and Global JXDM

Justice-specific extensible markup language (XML), known as the Global Justice XML Data Model (Global JXDM), is a widely adopted standard for representing text and data in a format that can be exchanged across platforms, languages, and applications, and can be used with a wide range of development tools and utilities. The following list highlights some of the advantages of XML technology and the Global JXDM:

Built to evolve : XML and Global JXDM is built to evolve and advance with emerging technologies.

Simplicity : Information coded in XML is easy to read and understand, plus it can be processed easily by computers. XML is similar enough to HyperText Markup Language (HTML) in its actual format so that those familiar with HTML can fairly easily pick up basic XML knowledge.

Standards-based : XML is an adopted standard fore representing text and data for the purpose of data exchange; Global JXDM is justice-specific and adopts several XML and data standards.

Requirements-based : Global JXDM is built from existing data models, dictionaries, processes, and document specifications.

Extensibility : New tags can be created as they are needed. Global JXDM enables local additions of data components.

Object-oriented : Global JXDM can be efficiently extended and reused (inheritance).

Expandable : Global JXDM domain includes courts, law enforcement, corrections, juvenile, and intelligence communities.

Model-based : Global JXDM generates consistent XML schema.

Multiple data types : XML documents can contain any possible data type from multimedia data, such as images, video, and sound, to even more active components.Mapping existing data : Mapping existing data structures like file systems or relational databases to XML is simple. XML supports multiple data formats and can cover all existing data structures.

Self-description : In traditional databases, data records require schemas set up by the database administrator.

XML documents can be stored without such definitions, because they contain metadata in the form of tags and attributes.

Machine-readable context : Tags, attributes, and element structure provide machine-readable context information that can be used to interpret the meaning of content, opening up new possibilities for highly efficient queries, intelligent data mining, analysis, etc.

This is a major advantage over HTML or plain text, where context information is difficult or impossible to evaluate.

Separates content from presentation : XML tags describe meaning not presentation. Whereas HTML specifies an appearance, or presentation, XML specifies the content's meaning. The look and feel of an XML document can be controlled by Extensible Stylesheet Language (XSL) style sheets, allowing the look of a document (or Web site) to be changed without touching the content of the document. Multiple views or presentations of the same content are easily rendered.

Facilitates data comparison and aggregation : The tree structure of XML documents allows documents to be compared and aggregated efficiently element by element.

One-server view : XML documents can consist of nested elements that are distributed over multiple remote servers.


XML is currently the most sophisticated format for distributed data.

Friday, March 7, 2008

Advantages of Wireless Technology

Productivity and profitability have become of paramount importance for businesses today. Return on investment is one of the deciding factors in any business decision, and of equal importance is lowering the total cost of ownership.

This is as true for investment in IT infrastructure as in any other area.You may hear that wireless technology is the future, but these days it seems that revolutionary technologies are introduced almost on a weekly basis.

Technical departments may get excited by the latest innovation, but you need to look at each decision you make from a point of view of solid business criteria.So what are the advantages of wireless networking?

Stay connected:Among the most significant results revealed by recent end user surveys is that using wireless LANs allows users to stay connected to their network for approximately one and three-quarter more hours each day.

A user with a laptop and a wireless connection can roam their office building without losing their connection, or having to log in again on a new machine in a different location. This translates to a very real increase in productivity, as much as 22% for the average user.

Access to accurate information:A further advantage of wireless Local Area Networks (revealed by a recent NOP study) was greater accuracy in everyday tasks. For respondents from healthcare organizations, 51 percent felt the improvement in accuracy was "significant."

The "anytime, anywhere" aspect of wireless communications allows increased access to accurate information when it is needed most - with health care, this could mean the difference between a life or death decision.

Spaghetti free:Perhaps the most obvious advantage comes from removing the need for extensive cabling and patching. Are you moving your enterprise to a new building? Do you need to set up a new office and add it to your existing network? Are you adding a new department in the same building or simply adding a few machines to your network?

A wireless LAN makes all these tasks substantially easier. Of course this translates directly into return on your wireless networking investment.


ROI:ROI - perhaps the overriding considration in IT spend. eAccording to the NOP study, wireless networking has a measurable impact on return on investment (ROI), with organizations saving an average of $164,000 annually on cabling costs and labour, more than 3.5 times the amount IT staff had anticipated. These savings did not include the financial benefits of increased productivity, which can increase an organization's return on their wireless LAN investment by even more substantial amounts.

Increased productivity:Referencing the NOP study, Charles Giancarlo, Senior Vice President of Cisco Systems, had this to say: "Current economic conditions have made productivity and profitability the new benchmarks for business success.

Wireless networking has been viewed as one of the technologies promising the greatest impact on productivity but, until now, no formal studies existed to substantiate the many benefits of wireless LANs. The results of this research show that wireless LANs can have a direct impact on productivity - and that the benefits are even more significant than they were assumed to be."

And more...Wireless technology also has advantages which are not so easy to measure, but still have real benefit for businesses. Happy employees means a happier working environment which means a more productive working environment. 87 percent of respondents to the NOP study agreed that there is a discernible positive impact in their quality of life from wireless LAN use tied to increased flexibility, productivity and time savings. More can be accomplished in less time, leading to a better balance between work and life and a higher level of employee satisfaction. This translates to greater employee loyalty and productivity.