You are on page 1of 38

UNIT 4

Introduction to Java Beans


1. Java Beans are considered as a Forefront of Java programming because Beans are important,
because they allow you to build complex systems from software components.
2. These components may be provided by you or supplied by one or more different vendors.
3. Java Beans defines an architecture that specifies how these building blocks can operate
together.
4. To achieve the benefits of component software, component architecture is needed that allows
programs to be assembled from software building blocks, perhaps provided by different vendors.
5. It must also be possible for a designer to select a component, understand its
Capabilities, and incorporate it into an application.
6. When a new version of a component becomes available, it should be easy to incorporate this
functionality into existing code. Fortunately, Java Beans provides just such architecture.
Java Bean
A Java Beans is software component that has been designed to be reusable in a variety of
different environments. There is no restriction on the capability of a Bean. It may perform simple
function, such as checking the spelling of a document, or complex function, such as forecasting
the performance of a stock portfolio. A bean may be visible to an end user. One example of this is
a button on a graphical user interface. A bean may be designed to work autonomously on a users
workstation or to work in cooperation with a set of other distributed components.
Advantages of Java Beans
Software component architecture provides standard mechanisms to deal with Software building
blocks. The benefits that Java technology provides for a component developer:
1. A bean obtains all the benefits of Javas write once, run-anywhere paradigm.
2. The properties, events and methods of a bean that are exposed to an application builder tool
can be controlled.
3. A bean may be designed to operate correctly in different locales, which makes it useful in
global markets.
4. Auxiliary software can be provided to help a person configure a bean. This Software is only
needed when the design-time parameters for that component are being set. It does not need to be
included in the run-time environment.
5. The configuration settings of a bean can be saved in persistent storage and restored at a later
time.
6. A bean may register to receive events from other objects and can generate events that are sent
to other objects.
Application Builder Tools
When working with Java Beans, most developers use an application builder tool, a utility that
enables you to configure a set of Beans, connect them together, and produce a working
application.

Capabilities of Bean builder tools


A palette is provided that lists all of the available Beans. As additional Beans are developed
or purchased, they can be added to the palette.
A worksheet is displayed that allow the designer to lay out Beans in a graphical user
interface. A designer may drag and drop a Bean from the palette to this worksheet.
3. Special editors and customizers allow a Bean to be configured. This is the mechanism by
which the behavior of a Bean may be adapted for a particular environment.
4. Commands allow a designer to inquire about the state and behavior of a Bean. This information
automatically becomes available when a Bean is added to the palette.
5. Capabilities exist to interconnect Beans. This means that events generated by one component
are mapped to method invocations on other components.
6. When a collection of Beans has been configured and connected, it is possible to save all of this
information in a persistent storage area. At a later time, this information can then be used to
restore the state of the application.
Sun provides two Bean application builder tools. They were
1. Bean box. 2. Bean Builder.
Bean box
1. Bean Box, which is part of the Bean Developers Kit (BDK).
2. The BDK is the original builder tool provided by Sun.
Bean Builder
1. It is designed to supplant the Bean Box, Sun has stopped development of the BDK and all new
Bean applications will be created using Bean Builder and is the future of Bean development
2. It requires Java 2, version 1.4 or latter. It is incompatible with earlier versions of Java 2.
3. Users using Java 2, version 1.2 or 1.3 will not be able to use Bean Builder; they must use BDK.
4. When Java 2, version 1.4 is a released product, but Bean Builder is currently in beta testing.
This means that the only way for a 1.4 user to create a Bean application is to do so using latest
Bean Builder beta. For this reason, we will not examine its features in depth at this time.
Using the Bean Developer Kit (BDK)
1. It is available from the Java Soft site, is a simple example
2. It is a tool that enables you to create, configure, and connect a set of Beans.
3. It also consists of a set of sample Beans with their source code.
4. The procedures for Windows environment and UNIX platform are similar, but some of the
commands are different.
Installing the BDK
1. The Java 2 SDK must be installed on your machine for the BDK to work.
2. Confirm that the SDK tools are accessible from your environment.
3. BDK can then be downloaded from the Java Soft site (http://java.sun.com) and is packaged as
one file that is a self-extracting archive.
5. BDK is installed in a directory called C:\bdk, If substitute the proper directory in the system.

Starting the BDK


To start the BDK, follow these steps:
1. Change to the directory c:\bdk\beanbox.
2. Execute the batch file called run.bat. Then BDK display the three Windows shown in Fig 25-1.
Note
Toolbox lists all of the different Beans that have been included with the BDK. Bean Box provides
an area to layout and connects the Beans selected from the Toolbox. Properties provide the ability
to configure a selected Bean.
Using the BDK
1. It describes how to create an application by using some of the Beans provided with the BDK.
2. We will study about Molecule Bean, tick tock bean in this book.

Molecule Bean
It displays a three-dimensional view of a molecule. It may be configured to present one of the
following molecules: hyaluronic acid, benzene, buckminsterfullerene, cyclohexane, ethane, or
water. This component also has methods that allow the molecule to be rotated in space along its X
or Y-axis.
Create and Configure an Instance of the Molecule Bean Steps
1. Position the cursor on the Toolbox entry labeled Molecule and clicks the left mouse button.
You should see the cursor change to a cross.
2. Move the cursor to the Bean Box display area and click the left mouse button in approximately
the area where you wish the Bean to be displayed. You should see a rectangular region appear that
contains a 3-D display of a molecule. A hatched border, indicating that it is currently selected,
surrounds this area.
3. You can reposition the Molecule Bean by positioning the cursor over one of the hatched
borders and dragging the Bean.

4. You can change the molecule that is displayed by changing the selection in the Properties
window. Notice that the Bean display changes immediately when you change the selected
molecule.

Create and configure an Instance of the Our Button Bean and connect it to the Molecule
Bean Steps
NOTE: Our Button Bean provides a push-button functionality.
1. Position the cursor on the Toolbox entry labeled Our Button and clicks the left Mouse button.
You should see the cursor change to a cross.
2. Move the cursor to the Bean Box display area and click the left mouse button in approximately
the area where you wish the Bean to be displayed. You should see a rectangular region appear that
contains a button. A hatched border indicating that it is currently selected surrounds this area.
3. You may reposition the Our Button Bean by positioning the cursor over one of the hatched
borders and dragging the Bean.
4. Go to the Properties window and change the label of the Bean to Rotate X. The button
appearance changes immediately when this property is changed.
5. Go to the menu bar of the Bean Box and select Edit | Events | action | action Performed. You
should now see a line extending from the button to the cursor. Notice that one end of the line
moves as the cursor moves. However, the other end of the line remains fixed at the button.
6. Move the cursor so that it is inside the Molecule Bean display area, and click the left mouse
button. You should see the Event Target Dialog dialog box.
7. The dialog box allows you to choose a method that should be invoked when this button is
clicked. Select the entry labeled rotateOnX and click the OK button. You should see a message
box appear very briefly, stating that the tool is Generating and compiling adaptor class.
Test the application. Each time you press the button; the molecule should move a few degrees
around one of its axes.
Now create another instance of the OurButton Bean. Label it Rotate Y and map its action event
to the rotateY method of the Molecule Bean. The steps to do this are very similar to those just
described for the button labeled Rotate X. Test the application by clicking these buttons and
observing how the molecule moves.

JAR Files
1. It means JAR (Java Archive) files.
2. BDK expects Beans to be packaged within JAR files to create our own bean.
3. A JAR file allows you to efficiently deploy a set of classes and their associated resources.
For example, a developer may build a multimedia application that uses various sound and image
files. A set of Beans can control how and when this information is presented. All of these pieces
can be placed into one JAR file.
4. JAR technology makes it much easier to deliver and install software.
5. Elements in a JAR file are compressed, which makes downloading a JAR file much faster than
separately downloading several uncompressed files. Digital signatures may also be associated
with the individual elements in a JAR file. This allows a consumer to be sure that a specific
organization or individual produced these elements.
6. The package java.util.zip contains classes that read and write JAR files.
Manifest Files (MFT)
1. A developer must provide a manifest file to indicate which of the components in a JAR file are
Java Beans.
2. A manifest file may reference several dot class files. If a dot class file is a Java Bean, its entry
must be immediately followed by the line Java-Bean: True.
Example of a manifest file
It defines a JAR file that contains two .gif files and one dot class file. The last entry is a Bean.
Name: sunw/demo/slides/slide0.gif
Name: sunw/demo/slides/slide1.gif
Name: sunw/demo/slides/Slides.class
Java-Bean: True
JAR Utility
A utility is used to generate a JAR file. Its syntax is shown here:
Usage:
jar {ctxu}[vfm0Mi] [jar-file] [manifest-file] [-C dir] files...
Jar options files
-c
-T
-X
-U
-V
-f
-m
-0
-M
-i
-C

Meaning
Create new archive
List table of contents for archive
Extract named (or all) files from archive
Update existing archive
Generate verbose output on standard output
Specify archive file name
Include manifest information from specified manifest file
Store only; use no ZIP compression
Do not create a manifest file for the entries
Generate index information for the specified jar files
Change to the specified directory and include the following file

Note
1.If any file is a directory then it is processed recursively. The manifest file name and the archive
file name need to be specified in the same order the 'm' and 'f' flags are specified.
Creating a JAR File
To create a JAR file named Xyz.jar that contains all of the dot class and dot gif files in the current
directory:
Jar cf Xyz.jar *.class *.gif
If a manifest file such as Yxz.mf is available, it can be used with the following command:
Jar cfm Xyz.jar Yxz.mf *.class *.gif.
Tabulating the Contents of a JAR File
The command lists the contents of Xyz.jar:
Jar tf Xyz.jar
Extracting Files from a JAR File
The command extracts the contents of Xyz.jar and places those files in the current directory:
Jar xf Xyz.jar
Updating an Existing JAR File
The following command adds the file file1.class to Xyz.jar:
Jar -uf Xyz.jar file1.class
Recursing Directories
The following command adds all files below directoryX to Xyz.jar:
Jar -uf Xyz.jar -C directoryX *
Introspection
1. It is the process of analyzing a Bean to determine its capabilities and essential feature of the
Java Beans API.
2. It allows an application builder tool to present information about a component to a software
designer.
3. Without introspection, the Java Beans technology could not operate.
4. There are two ways in which the developer of a Bean can indicate which of its properties,
events, and an application builder tool should expose methods.
First way
Simple naming conventions are used to allow the introspection mechanisms to infer information
about a Bean.
Second way
The design patterns for properties and events that enable the functionality of a Bean to be
determined.

Design Patterns for Properties


1. A property is a subset of a Beans state. The values assigned to the properties determine the
behavior and appearance of that component.
2. Three types of properties: simple, Boolean, and indexed.
Simple Properties
It has a single value. It can be identified by the following design patterns, where N is the name of
the property and T is its type.
Public T getN ();
Public void setN (T arg);
A read/write property has both of these methods to access its values. A read-only
Property has only a get method. A write-only property has only a set method.
The following listing shows a class that has three read/write simple properties:
Public class Box
{
Private double depth, height, width;
Public double getDepth ()
{ return depth; }
Public void setDepth (double d)
{depth = d;
}
Public double getHeight ()
{ return height; }
Public void setHeight (double h)
{ height = h; }
Public double getWidth ()
{ return width; }
Public void setWidth (double w)
{ width = w; }
}
JAVA
Boolean Properties
It has a value of true or false. It can be identified by the following design patterns, where N is the
name of the property.
Public Boolean isN ();
Public Boolean getN ();
Public void setN (boolean value);
shows a class that has one Boolean property
Public class Line {
Private Boolean dotted = false;
Public boolean isDotted ()
{ return dotted;
}
Public void setDotted (boolean dotted) { this.dotted = dotted; }
}
Indexed Properties
It consists of multiple values. It can be identified by the following design patterns, where N is the
name of the property and T is its type:

Public T getN (int index);


Public void setN (int index, T value);
Public T[ ] getN( );
Public void setN (T values[ ]);
The following listing shows a class that has one read/write-indexed property:
Public class PieChart
{
Private double data [];
Public double getData (int index)
{ return data[index]; }
Public void setData (int index, double value) { data[index] = value; }
Public double [] getData( )
{ return data; }
Public void setData (double[ ] values)
{ data = new double[values.length];
System.arraycopy(values, 0, data, 0, values.length);}
}
Design Patterns for Events
Beans use the delegation event model. Beans can generate events and send them to other objects.
These can be identified by the following design patterns.
Public void addTListener( TListener eventListener);
Public void addTListener(TListener eventListener) throws TooManyListeners;
Public void removeTListener(TListener eventListener);
Here T is the type of the event:
Event listeners to register an interest in events of a specific type use these methods. The first
pattern indicates that a Bean can multicast an event to multiple listeners. The second pattern
indicates that a Bean cans unicast an event to only one listener. A listener uses the third pattern
when it no longer wishes to receive a specific type of event notification from a Bean.
The following listing outlines a class that notifies other objects when a temperature value moves
outside a specific range. The two methods indicated here allow other objects that implement the
TemperatureListener interface to receive notifications when this occurs.
Public class Thermometer
{
Public void addTemperatureListener (TemperatureListener tl)
{...}
Public void removeTemperatureListener (TemperatureListener tl) {...}
}
Methods
Design patterns are not used for naming nonproperty methods. The introspection mechanism
finds all of the public methods of a Bean. Protected and private methods are not presented.

Developing a Simple Bean Using the BDK


1. It shows how to develop a simple Bean and connect it to other components via the BDK.
2. Our new component is called the Colors Bean. It appears as either a rectangle or ellipse that is
filled with a color. A color is chosen at random when the Bean begins execution. A public method
can be invoked to change it. Each time the mouse is clicked on the Bean, another random color is
chosen. There is one Boolean read/write property that determines the shape. The BDK is used to
layout an application with one instance of the Colors Bean and one instance of the Our Button
Bean. The button is labeled Change. Each time it is pressed, the color changes.
Figure 25-3 shows how this application appears.

Steps Create a New Bean


1.Create a Directory for the New Bean.

Create a folder week6 at C:\bdk\demo\sunw\demo\week6.


2.Create the Source File for the New Bean:

Create a file vbean.java at C:\bdk\demo\sunw\demo\week6.


3. Compile the Source Code for the New Bean
Compile the source code to create a class file. Type the following:
C:\bdk\demo\sunw\demo\week6>javac vbean.java
C:\bdk\demo\sunw\demo\week6>
4. Create a Manifest File
Copy colors.mft file to C:\bdk\demo.
5. Generate a JAR File
C:\bdk\demo>jar cfm ..\jars\colors4.jar colors.mft sunw\demo\week6\*.class
C:\bdk\demo>
6. Start the BDK
Change to the directory c:\bdk\beanbox and type run. This causes the BDK to start. You
should see three windows, titled ToolBox, BeanBox, and Properties. The ToolBox
window should include an entry labeled vbean for your new Bean.
7. Test
In test we run the application.

colors.mft
Name: sunw/demo/week6/vbean.class
Java-Bean: True
Vbean.java
package sunw.demo.week6;
import java.awt.*;
import java.awt.event.*;
public class vbean extends Canvas
{
transient private Color color;
private boolean square;
public vbean()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
change();
}
}
);
square=false;
setSize(200,200);
change();
}
public boolean getSquare()
{
return square;
}
public void setSquare(boolean flag)
{
this.square=flag;
repaint();
}
public void change()
{
color=randomColor();
repaint();
}
private Color randomColor()
{
int r=(int)(255*Math.random());
int g=(int)(255*Math.random());
int b=(int)(255*Math.random());

return new Color(r,g,b);


}
public void paint(Graphics g)
{
Dimension d=getSize();
int h=d.height;
int w=d.width;
g.setColor(color);
if(square)
{
g.fillRect(0,0,w-1,h-1);
}
else
{
g.fillOval(0,0,w-1,h-1);
}
}
}
Create an Instance of the Colors Bean
After you complete the preceding steps, create an instance of the Colors Bean in the BeanBox
window. Test your new component by pressing the mouse anywhere within its borders. Its color
immediately changes. Use the Properties window to change the rectangular property from false to
true. Its shape immediately changes.
Steps to Create and Configure an Instance of the OurButton Bean
1. Go to the Properties window and change the label of the Bean to Change. You should see
that the button appearance changes immediately when this property is changed.
2. Go to the menu bar of the BeanBox and select Edit | Events | action | actionPerformed.
3. Move the cursor so that it is inside the Colors Bean display area, and click the left mouse
button. You should see the Event Target Dialog dialog box.
4. The dialog box allows you to choose a method that should be invoked when this button is
clicked. Select the entry labeled change and click the OK button. You should see a message box
appear very briefly, stating that the tool is Generating and compiling adaptor class.
5. Click on the button. You should see the color change. You might want to experiment with the
Colors Bean a bit before moving on.
JAVA
Using Bound Properties
A Bean that has a bound property generates an event when the property is changed. The event is
of type PropertyChangeEvent and is sent to objects that previously registered an interest in
receiving such notifications. The TickTock Bean is supplied with the BDK. It generates a
property change event every N seconds. N is a property of the Bean that can be changed via the
Properties window of the BDK. The next example builds an application that uses the TickTock
Bean to automatically control the Colors Bean. Figure 25-4 shows how this application appears.

Steps
For this example, start the BDK and create an instance of the Colors Bean in the Bean Box
window. Create an instance of the TickTock Bean. The Properties window should show one
property for this component. It is Interval and its initial value is 5. This represents the number
of seconds that elapse between property change events generated by theTickTock Bean. Change
the value to 1.

Now you need to map events generated by the TickTock Bean into method calls on
the Colors Bean. Follow these steps:
1. Go to the menu bar of the BeanBox and select Edit | Events | propertyChange| propertyChange.
You should now see a line extending from the button to the cursor.
2. Move the cursor so that it is inside the Colors Bean display area, and click the left mouse
button. You should see the Event Target Dialog dialog box.
3. The dialog box allows you to choose a method that should be invoked when this event occurs.
Select the entry labeled change and click the OK button. You should see a message box appear
very briefly, stating that the tool is Generating and compiling adaptor class.
You should now see the color of your component change every second.
Using the Bean Info Interface
Design patterns were used to determine the information that was provided to a Bean user. This
section describes how a developer can use the BeanInfo interface to explicitly control this
process.
This interface defines several methods, including these:
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( )
MethodDescriptor[ ] getMethodDescriptors( )
They return arrays of objects that provide information about the properties, events, and methods
of a Bean. By implementing these methods, a developer can designate exactly what is presented
to a user. SimpleBeanInfo is a class that provides default implementations of the BeanInfo
interface, including the three methods just shown. You may extend this class and override one or
more of them. The following listing shows how this is done for the Colors Bean that was
developed earlier. ColorsBeanInfo is a subclass of SimpleBeanInfo. It overrides

getPropertyDescriptors () in order to designate which properties are presented to a Bean user.


This method creates a PropertyDescriptor object for the rectangular property. The
PropertyDescriptor constructor that is used is shown here:
PropertyDescriptor(String property, Class beanCls) throws IntrospectionException
Here, first argument is the name of the property, and the second argument is the class of the Bean.
// A Bean information class.
package sunw.demo.colors;
import java.beans.*;
public class ColorsBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor rectangular = new
PropertyDescriptor("rectangular", Colors.class);
PropertyDescriptor pd[] = {rectangular};
return pd;
}
catch(Exception e) { }
return null;
}
}
You must compile this file from the BDK\demo directory or set CLASSPATH so that it includes
c:\bdk\demo. If you dont, the compiler wont find the Colors.class file properly. After this file is
successfully compiled, the colors.mft file can be updated, as shown here:
Name: sunw/demo/colors/ColorsBeanInfo.class
Name: sunw/demo/colors/Colors.class
Java-Bean: True
Use the JAR tool to create a new colors.jar file. Restart the BDK and create an instance of the
Colors Bean in the BeanBox.The introspection facilities are designed to look for a BeanInfo
class. If it exists, its behavior explicitly determines the information that is presented to a Bean
user.
Otherwise, design patterns are used to infer this information.
Figure 25-5 shows how the Properties window now appears. Compare it with Figure 24-3. You
can see that the properties inherited from Component are no longer presented for the Colors
Bean. Only the rectangular property appears.

Constrained Properties
A Bean that has a constrained property generates an event when an attempt is made to change its
value. The event is of type PropertyChangeEvent. It is sent to objects that previously registered
an interest in receiving such notifications. Those other objects have the ability to veto the
proposed change. This capability allows a Bean to operate differently according to its run-time
environment.
Persistence
It is the ability to save a Bean to nonvolatile storage and retrieve it at a later time. The
information that is particularly important are the configuration settings.
BDK allows you to save a set of Beans that have been configured and connected together to form
an application. The rectangular property of the Colors Bean was changed to true, and the interval
property of the TickTock Bean was changed to one second. These changes can be saved.
To save the application, go to the menu bar of the BeanBox and select File | Save. A dialog box
should appear, allowing you to specify the name of a file to which the Beans and their
configuration parameters should be saved. Supply a filename and click the OK button on that
dialog box. Exit from the BDK. Start the BDK again.
To restore the application go to the menu bar of the Bean Box and select File | Load. A dialog
box should appear, allowing you to specify the name of the file from which an application should
be restored. Supply the name of the file in which the application was saved, and click the OK
button.
Confirm that the rectangular property of the Colors Bean is true and that the interval property for
the TickTock Bean is equal to one second. The object serialization capabilities provided by the
Java class libraries are used to provide persistence for Beans. If a Bean inherits directly or
indirectly from java.awt.Component, it is automatically serializable, because that class
implements the java.io.Serializable interface. If a Bean does not inherit an implementation of the
Serializable interface, you must provide this yourself. Otherwise, containers cannot save the
configuration of your component.
The transient keyword can be used to designate data members of a Bean that should not be
serialized. The color variable of the Colors class is an example of such an item.
Customizers

The Properties window of the BDK allows a developer to modify the properties of a Bean.
However, this may not be the best user interface for a complex component with many interrelated
properties. Therefore, a Bean developer can provide a customizer that helps another developer
configure this software. A customizer can provide a step-by-step guide through the process that
must be followed to use the component in a specific context. Online documentation can also be
provided. A Bean developer has great flexibility to develop a customizer that can differentiate his
or her product in the marketplace.

The Java Beans API


The Java Beans functionality is provided Java Beans Application programming interface (API)
consists of set of classes and interfaces defined in java. beans package.

Interface
AppletInitializer
Bean Info
Customizer
Exception Listener
Design Mode
PropertyChangeListener
PropertyEditior
VetoableChangeListner
Visibility

Class
Bean Descriptor
Beans
IntrospectionException
PropertyChangeEvent
PropertyDescriptor

Java Beans API Interfaces


Description
Methods present in this interface are used to initialize Beans
that are also applets
This interface allows a designer to specify information about
the properties, events and methods of a Bean.
This interface allows a designer to provide a graphical user
interface through which a Bean may be configured.
A method in this interface is invoked when an exception has
occurred.
Methods in this interface determine if a Bean is executing in
design mode.
A method in this interface is invoked when a bound property
is changed.
Objects that implement this interface allow designers to
change and display property values.
A method in this interface is invoked when a constrained
property is changed.
Methods in this interface allow a bean to execute in
environments where graphical user interface is not available.

Description
This class provides information about a Bean.
This class is used to obtain information about a Bean
An exception of this type is generated if a problem occurs when
analyzing a bean.
This event is generated when bound or constrained properties
are changed.
Instances of this class describe a property o f a Bean

Class
DefaultPersistenceDelegate
Encoder
EventHandler
EventSetDescriptor
Expression
FeatureDescriptor
Indexed Property Descriptor
Introspection Exception
Introspector
MethodDescriptor
ParameterDescriptor
PersistenceDelegate
PropertyChangeEvent

Class
PropertyChangeListenerProxy
PropertyChangeSupport
PropertyDescriptor
PropertyEditorManager
PropertyEditorSupport
PropertyVetoException
SinpleBeanInfo
Statement
VetoableChangeListenerProxy

Description
A concrete subclass of Persistence Delegate.
(Added by java2, version 1.4)
Encodes the state of set of beans. Can be used to write this
information to a stream. (Added by java2, version 1.4)
Supports dynamic event listener creation. (Added by
java2, V 1.4)
Instances of this class describe an event that can be
generated by a bean.
Encapsulate a call to a method that returns a result.
This is the super class of the property Descriptor, Event
Set Descriptor, and Method Descriptor classes.
Instances of this class describe an indexed property of a
bean.
An Exception of this type is generated if a problem occurs
when analyzing the bean
This class analyzes a bean and constructs a BeanInfo
object that describe the component.
Instances of this class describe a method of a bean.
Instances of this class describe a method parameter.
Handles the state information of an object.
This is generated when bound or constrained properties
are changed. It is sent to objects that registered an interest
in these events and implement either the
PropertyChangeListner or VetoableChangeListener
interfaces.

Description
Extends EventListenerProxy and implements
PropertyChangeListener. (Added by java2, V 1.4)
Beans that support bound properties can use this class to
notify PropertyChangeListener objects.
Instances of this class describe a property of a bean.
This class locates a Property Editor object for a given
type.
This class provides functionality that can be used when
writing property editors.
An exception of this type is generated if a change to a
constrained property is vetoed.
This class provides functionality that can be used when
writing bean info classes.
Encapsulates a call a method. (Added by java2, V 1.4)
Extends EventListnerProxy and implements

VetoableChangeSupport
XlmDecoder
XlmEncoder

VetoableChangeListener. (Added by java2, V 1.4)


Beans that support constrained properties can use this
class to notify VetoableChangeListener objects.
Used to read a bean from a XML document.
(Added by java2, version 1.4)
Used to write a bean from a XML document.
(Added by java2, version 1.4)
The Classes defined in java. beans

Introspector, BeanDescriptor, PropertyDescriptor, and EventSetDescriptor classes and the


BeanInfo interface. It lists the properties and events of the Colors Bean that was developed earlier
in this chapter.
// Show properties and events.
package sunw.demo.colors;
import java.awt.*;
import java.beans.*;
public class IntrospectorDemo {
public static void main(String args[]) {
try {
Class c = Class.forName("sunw.demo.colors.Colors");
BeanInfo beanInfo = Introspector.getBeanInfo(c);
BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor();
System.out.println("Bean name = " +
beanDescriptor.getName());
System.out.println("Properties:");
PropertyDescriptor propertyDescriptor[] =
beanInfo.getPropertyDescriptors();
for(int i = 0; i < propertyDescriptor.length; i++) {
System.out.println("\t" + propertyDescriptor[i].getName());
}
System.out.println("Events:");
EventSetDescriptor eventSetDescriptor[] =
beanInfo.getEventSetDescriptors();
for(int i = 0; i < eventSetDescriptor.length; i++) {
System.out.println("\t" + eventSetDescriptor[i].getName());
}
}
catch(Exception e) {
System.out.println("Exception caught. " + e);
}
}
}
The output from this program is the following:

Bean name = Colors


Properties:
rectangular
Events
propertyChange
hierarchy
inputMethod

component
key

mouseMotion
focus

mouse
hierarchyBounds

Using Bean Builder


Bean Builder is similar to the BeanBox offered by the BDK, except that it is more powerful and
sophisticated. Its operation is also similar to the BeanBox except that it is easier to use.
Bean Builder operation modes
1. Design.
2. Test.
Design mode
In this, you construct a Bean-based application, adding the various components, and wiring them
together.
Test mode or runtime mode
The application is executed and all of the components are live. Thus, it is extremely easy to
construct and then test your application. Futhermore, you switch between these two modes by
checking or clearing a single check box. Bean Builder provides the three windows shown in
Figure.
1. The top (main) window holds the current palette set. This includes a default palette from which
you can choose various user-interface objects, such as buttons, scroll bars, lists, and menus. These
are Swing rather than AWT objects. You can also load other palettes and JAR files. Each
component has associated with it a set of properties. You can examine and set these using the
Property Inspector window provided by Bean Builder.
2. The third window, called the design window (or, designer for short), is the window in which
you will assemble various components into an application. In general, to build an application, you
will select items from a palette and instantiate them on the designer, setting their properties as
necessary by using the Property Inspector window. Once you have assembled the components,
you will wire them together by dragging a line from one to another. In the process, you will
define the input and output methods that will be called, and what action causes them to be called.
For example, you might wire a push button to a text field, specifying that when the push button is

pressed, the text field will be cleared.

Building a Simple Bean Builder Application


1. Open beanbuilder.jar which is in C:\beanbuilder\ beanbuilder.jar.
2. Click on the containers tab.
3. Select the JFRAME and drop it on the current palette set.
4. Click on swings tab.
5. Click on JSLIDER and drop it on the current palette set.
6. Click on JSCROLLBAR and drop it on the current palette set.
7. Left click on the JSLIDER a line will be appear if we drap,drop the line on the JSLIDER.
8. An interaction wizard appears.
9. On the interaction wizard choose Event Adapter.
10. From the Event Sets select change, state change (Change Event) method defiantly gets
activated.
11. Press next.
12. Select target method for JSCROLLBAR is Set Value (int) and press next.
13. Select matching source getter methods as getvalue() and click finish.
14. Remove the check mark on Design check box. So it will enter into test mode.
15. So if u move the JSLIDER automatically JSCROLLBAR moves.When the slider control is
moved, the scroll bar is also moved by the same amount, and vice versa.

First, create a new project by selecting New from the File menu. Next, select javax.swing.JFrame
in the list at the top of the Property Inspector window. JFrame is the top-level Swing class for the
design window. Next, scroll down in the Property Inspector window until you find title. Change
the title to A Bean Builder App.Your screen should look like the one shown in Figure 25-7.

of the Swing class JScrollbar. By default, both the slider and the scroll bar have the same range (0
to 100), so the value of one will translate directly to the value of the other. To make your
application look like the one in this book, position them as shown in Figure 25-9.
Now it is time to wire the components together. To do this, you will position the mouse pointer
over one of the connection handles, then drag a wire from the connection handle on one
component to a connection handle on another component. The component at which you start is
the source of some event and the component at which you end is the recipient of the event. Each
component has four connection

WARE

DEVELOPMENTUSING

1. Write a program to add a user-defined button to the bean box.


Steps: 1. Create a folder a at C:\bdk\demo\sunw\demo\a.
2. Create a file butbean.java at C:\bdk\demo\sunw\demo\a and compile the file their.
C:\bdk\demo\sunw\demo\a>javac butbean.java
C:\bdk\demo\sunw\demo\a>
3. Copy colors.mft file to C:\bdk\demo.
4. C:\bdk\demo>jar cfm ..\jars\colors.jar colors.mft sunw\demo\a\*.class
C:\bdk\demo>
5. C:\bdk\beanbox\run.bat.
Colors.mft: Name: sunw/demo/a/butbean.class
Java-Bean: True
butbean.java: package sunw.demo.a;
import java.awt.*;
public class butbean extends Button
{
public butbean()
{
setSize(50,500);
setBackground(Color.red);
setForeground(Color.white);
setVisible(true);
setLabel("but bean");
}
public void setButcaption(String s)
{
setLabel(s);
}
public String getButcaption()
{
return getLabel();
}
}

Enterprise Java Beans (EJB)


EJB defines how server-side components are written and provides a standard architectural
contract between the components and the application servers and containers that manage
them. The EJB specification provides a solution for a clear separation of the business
logic and the intricacies of dealing with persistency, transactions, and other middlewarerelated services. EJBs provide the architecture for server-side component-based
distributed computing. EJBs typically represent a business process that can be shared
across applications as well as across the network.

Web containers and EJB containers


Containers are runtime environments that provide components with specific services.
Web containers provide runtime support to clients by processing requests through
invoking JSPs and servlets and returning results from the components to the client.
Similarly EJB containers provide automated support for transaction and state
management of EJB components, as well as lookup and security services.

Containers Handle
1. Concurrency
2. Security
3. Availability
4. Scalability
5. Transactions
6. Distribution

Components Handle
1. Presentation of JSP, Servlets and Applets
2. Business Logic of EJB
3. Data Access Logic (optional) of EJB

Note
1. The container is the car. The component is the driver
2. The container is the platform. The component is your application
EJB specifications
The Enterprise Java Beans (EJB) specification is a foundation for the Java 2 Platform,
Enterprise Edition (J2EE) defined by Sun. Vendors use this specification to implement an
infrastructure in which components can be deployed, and use a set of services such as
distributed transactions, security, or life-cycle management. As a developer, you just
reuse the services detailed in the specification. For example, you do not need to include
any code in your components to make them transactional. This lets you concentrate on
the business logic of the application.

Enterprise beans are designed to be portable from one vendors execution environment to
another, independent of the choices made by the vendor to implement the services
described in the specification. The quality of service required by an enterprise bean is
described outside of the component in a deployment descriptor. The deployment
descriptor is analyzed at deployment time by a tool provided by the vendor. This feature
provides a great level of flexibility for reusing your component. For example, if you wish
to change the transactional behavior of an enterprise bean, you have to change only the
transaction attribute stored in the deployment descriptor, not the EJB business logic.
Changes are taken into account when you re-deploy the enterprise bean in the container.
Features and limitations of EJB 1.0
Features
1. Enterprise bean instances are created and managed at runtime by a container.
2. An enterprise bean can be customized at deployment time by editing its environment
properties.
3. Client access is mediated by the container and the EJB server on which the enterprise
bean is deployed.
4. Flexible component model.
5. Support for component distributions and security.
6. Stateless and state full session beans are defined and must be supported.
7. Container-managed persistence and bean-managed persistence entity beans are defined
and are not mandatory in this version.
8. For transaction support, either the original javax.jts package or the new
javax.transaction package can be used.
Limitations
1. Entity bean support is not mandatory.
2. Java RMI-IIOP support is not mandatory, which defies interoperability with other
heterogeneous components.
3. The deployment descriptor is not available in text format.
4. Requires a separate deployment file for each enterprise bean, causing large
applications composed of many beans to slow down.
5. Interoperability between containers is not defined.
6. No standard container API.
EJB Provides
1. Easier development
2. Open industry standard support
3. Multi-tiered architecture
4. Scalability
5. Distributed transaction support
6. Portable cross platform component model, Platform independence
7. EJB Components provide reusable Data and Business Logic
8. EJB Servers provide transactions and security support
9. N-tier Architecture provides scalability and performance
10. Component container contract provides cross platform portability

Java Beans versus Enterprise Java Beans


Java Beans is the component model for Java. Each JavaBean has properties, methods, and
events. Enterprise Java Beans also describe, among other things, a component model.
However, these two component models are not identical. Java Beans are intended to be
reusable software components that can be visually manipulated in a builder tool.
Therefore, the Java Beans specification describes in detail the APIs for connecting beans
to each other through the event model, where one bean acts as an event listener and the
other as an event source. Bean customization is done at assembly time by using
properties. Java Beans do not require a special container. They can exist inside a Java
Virtual Machine.
Enterprise Java Beans are strongly associated with a services framework. No event
model is used by Enterprise Java Beans. Customization is done at runtime by using a
deployment descriptor. Enterprise Java Beans do require an EJB container, in which they
are deployed. This container should provide all the services defined by the framework
and it must reside within an enterprise Java server.
So, the two component models are used in different ways. The Java Beans model
supports application assembly in a builder tool, while the Enterprise Java Beans model
supports a distributed object model. Java Beans do not have their own container, so trying
to locate them on a remote physical machine is theoretically impossible. Non-graphical
server-side Java Beans (for example, RMI server beans) could be also used instead of
Enterprise Java Beans, but that would require the implementation of an enterprise Java
server framework.
EJB roles
The EJB specification defines six roles for EJB development and deployment. Each role
has different responsibilities in the EJB development process.
1. Bean provider
The bean provider is the developer of the code, and is responsible for converting the
business requirements into actual physical code. He or she must provide the necessary
classes that constitute an EJB, as well as providing the deployment file describing the
runtime settings for the bean. The bean providers final product is an EJB JAR file.
2. Application assembler
The application assemblers responsibility is to package all the different EJB
components, along with any other application components, the final product being an
enterprise application EAR file.
3. Deployer
This person is responsible for deploying the EJB application on the target runtime
environment. The deployer should be familiar with all aspects of the environment,
including transaction and security support.

4. Server provider
The job of the server provider is to provide a runtime EJB server environment that is
compliant with the EJB specification. IBM is a server provider of the WebSphere
Application Server.
5. Container provider
The job of the container provider is to provide a runtime EJB container environment that
is compliant with the EJB specification, and is generally the same as the server provider.
The server and container cooperate to provide the quality-of-service runtime environment
for the EJBs.
6. Systems administrator
The system administrators task is to ensure that the runtime environment is configured in
such a way that the application can function correctly, and is integrated with all of the
required external components.
EJB framework Main components
There are six main framework components of EJB technology. They were
1. EJB server
It provides the actual primary services to all EJBs. An EJB server may host one or more
EJB containers. It is also called generically an Enterprise Java Server (EJS). WebSphere
Application Server is an EJBS.
2. EJB container
It provides the runtime environment for the enterprise bean instances, and is the
intermediary between the EJB component and the server.
3. EJB component
These represent the actual EJBS themselves. There are three types of enterprise beans:
entity, session, and message-driven beans.
4. EJB interfaces and EJB bean
The interfaces for client access (EJB home and EJB object) and the EJB bean class.
5. EJB deployment descriptor
The descriptor defines the runtime quality of service settings for the bean when it is
deployed. Many of the settings of an EJB, such as the transactional settings, are defined
in the deployment descriptor. The deployment descriptor is an external entity from the
bean, and therefore decouples the bean component itself from the runtime characteristics.
6. EJB client
A client that accesses EJBs.

EJB server
It is that part of the application server that hosts EJB containers. This is sometimes
referred to as an Enterprise Java Server (EJS). Containers are transparent to the client
there is no client API to manipulate the container, and there is no way for a client to tell
in which container an enterprise bean is deployed. The EJB server provides the
implementation for the common services to all EJBs. The EJB servers responsibility is to
hide the complexities of these services from the applications requiring them, thereby
obtaining access to the service on behalf of the EJB, but hiding it from the EJB.
The EJB specification outlines seven services that must be provided by an EJB server:
The responsibilities that an EJB container must satisfy can be defined in terms of the
primary services. Specific EJB container responsibilities are as follows:
Primary services
1. Naming
A client can invoke an enterprise bean by looking up the name of the bean in a
centralized naming space called a naming service, and this is accessed via the Java
Naming and Directory Interface (JNDI) API. The container is responsible for registering
the (unique) lookup name in the JNDI namespace when the server starts up, and binding
the appropriate object type into the JNDI namespace.
2. Transaction
A transaction is defined as a set of tasks that must execute together; either all must work
or all must be undone. The EJB container handles the transaction operations, as well as
the coordination activities between the transactions of the beans. The EJBs transaction
behavior is described in the deployment descriptor, and this is also referred to as
container-managed transactions (CMT). Because the container manages the
transactions, applications can be written without explicit transaction demarcation.

3. Security
The EJB container provides a security domain for enterprise beans. The container is
responsible for enforcing the security policies defined at deployment time whenever there
is a method call, through access control lists (ACL). An ACL is a list of users, the groups
they belong to, and their rights, and it ensures that users access only those resources and
perform only those tasks for which they have been given permission.
4. Persistence
The container is also responsible for managing the persistence of a bean (all storage and
retrieval of data) by synchronizing the state of the bean instance in memory with the
respective record in the data source. Concurrent access to the data from multiple clients is
managed through the concurrency and transaction services (entity beans only).
5. Concurrency
It is defined as access by two or more clients to the same bean, and the container manages
concurrency according to the rules of the bean type. Additionally, for message-driven
beans, concurrency is defined as managing the processing of the same message.
6. Life cycle
The container is responsible for controlling the life cycle of the deployed components. As
EJB clients start giving requests to the container, the container dynamically instantiates,
destroys, and reuses the beans as appropriate. The specific life-cycle management that the
container performs is dependent upon the type of bean. The container may ultimately
provide for some resource utilization optimizations, and employ techniques for bean
instance pooling. Bean state-management is a type of life-cycle management, where
activating and passivating of beans based on usage can be achieved. These techniques
become part of the bean life cycle that the container must manage.
7. Messaging
The container must provide for asynchronous messaging. Specifically, it must provide for
the reliable routing of messages from JMS clients to message-driven beans.
Bear in mind that the EJB container and the EJB server are not clearly separated
constructs. EJBs do not interact directly with the EJB server, but rather, do so through the
EJB container, which acts as a broker to the services provided by the EJB server. So,
from the EJBs perspective, it appears that the EJB container is in fact providing those
services. Additionally, the specification only defines a bean-container contract and does
not define a container-server contract, so determining who actually does what is a little
ambiguous. The container does not actually provide the service itself; rather it
communicates with the EJB server that actually implements the service, but how this is
actually implemented is up the individual EJB vendors. Therefore, for the sake of
simplicity, the seven services defined above will simply be referred to generically as EJB
services.

EJB container
The EJB container is a system that functions as a runtime environment for enterprise
beans by managing and applying the primary services that are needed for bean
management at runtime. In addition to being an intermediary to the seven services above
provided by the EJB server, the EJB container will also provide for EJB instance lifecycle management, and EJB instance identification. EJB containers create bean instances,
manage pools of instances, and destroy them. The container provides the service level
specified at deployment time in the deployment descriptor. For example, it will start a
transaction or check for security policies.
All the services are well defined within the EJB framework. The framework is
implemented through the bean callback methods. These methods are purely for system
management purposes and only the container calls them when it is interacting with the
deployed beans, and are invoked when the appropriate life-cycle event occurs. The
specification is clear on what actions trigger what events, and subsequently what callback
methods are invoked, and this provides the bean developer with a predictable runtime
model. All the interaction takes place in a way transparent to the bean developer and also
to the client.
Remote accessibility
Ultimately, EJBs are (usually) remote, distributed objects, and the containers primary
responsibility is to provide the means to access these remote objects. Remote
accessibility enables remote invocation of a native component by converting it into a
network component. EJB containers use the Java RMI interfaces to specify remote
accessibility to clients of the EJBs.

EJB component (the actual EJB)


The EJB components refer to the beans themselves, and include all the classes, interfaces,
and constructs that makes up the enterprise bean. There are three types of enterprise
beans: entity, session, and message-driven beans. The rules for bean construction (which
interfaces to use, classes to extend, and so forth) are governed by the type of bean, so a
quick introduction to the types of enterprise beans is presented here.
EJB types
There are three types of EJBs
Bean type classification revisited
Which EJB type to choose really depends on the functionality that it should provide, what
business process and behavior it represents, and how it should be invoked.
1. Entity beans
a. It is modeled to represent business or domain-specific concepts, and are typically the
nouns of your system, such as customers and accounts. They usually represent data
(entities) stored in a database.
b. It are typically modeled to represent domain objects, that is, data entities that are stored
in a permanent, persistent data store such as a database, and the behavior that can be
performed on that data. This is sometimes referred to as objectifying the data, and the
attributes of the entity object are mapped to rows in one or more database tables. Some
examples of entities might be accounts or customers. Its primary key uniquely identifies
each entity. Since multiple users may share data in a database, so may entity beans.
Managing the concurrency of the entity bean is one of the responsibilities of the
container.
2. Session beans
a. A session bean is modeled to represent a task or workflow of a system, and provide
coordination of those activities between beans, such as a banking service, allowing for a
transfer between accounts.
b. Session beans are often considered to be extensions, or agents, of the client, and
perform tasks on behalf of the client. Only one client may be processing on a given
session bean at a given time, so there is no concurrency of session beans. They are
modeled to encapsulate process or workflow-like behavior, such as transferring funds
between accounts. Although some session beans may maintain state data, this data is not
persistent in the sense that an entity bean represents persistent data.
3. Message-driven beans (MDB)
a. These are similar to session beans. may also be modeled to represent tasks. However,
the receipt of asynchronous messages invokes them. The bean either listens for or
subscribes to messages that it is to receive.
b. They may also represent business process-like behavior, but are invoked
asynchronously. They typically represent integration points for other applications that
need to work with the EJB.

Purpose
Shared Access
Persistence

Session Bean
Represents Process.Performs
a task, or process for a client.
One instance per client
Not persistent. When the
Client terminates its session
bean is no longer available.

Entity Bean
Represents Data: represents a business
entity object that exists in persistent
storage.
Shared instance for multiple clients
Persistent. Even when the EJB
container terminates, the entity state
remains in a database.

Bean-container contract revisited


The bean-container contract describes the interactions between an enterprise bean and its
container. We have already described the theory of the bean-container contract, such as
the callback methods, but we now describe some of the other parties involved. The bean
contract (Figure 2-28) includes callback methods, the EJBContext interface, and the
environment naming context.

Callback methods
EJBs interact with the container through a well-defined component model that is
implemented by the callback methods that a bean must implement. At runtime, the
container invokes the callback methods on the bean instance when the appropriate lifecycle event occurs, such as create or remove. The type of bean determines the callback
methods a bean must implement: entity, session, or message-driven bean.
EJBContext
It is also part of the bean-container contract is the EJBContext interface, which provides
the bean information about the container. Each bean type has its own type of EJBContext:
EntityContext, SessionContext, and MessageDrivenContext, all inheriting from
EJBContext.
Environment naming context
Is a localized JNDI namespace for the bean that the container provides, also called the
environment-naming context. Contains references to environment information, resources,
or other EJBs.
Additional flavors of EJB types
Other are two different flavors of both entity and session beans:
Flavors of an entity bean
The entity beans represent persistent data. There are two types of entity beans that govern
how the persistency behavior will be managed by the container.
a. Through container-managed persistence (CMP),
b. Through bean-managed persistence (BMP) Or by the bean itself.
Flavors of a session bean
There are two types of session beans. Stateless session beans are beans that maintain no
state, and are pooled by the container to be reused. Stateful session beans are beans that
represent a conversational state with a client, where the state is maintained between client
invocations.
Although the classifications above (CMP versus BMP, and stateful versus stateless) are
often referred to as types of EJBs, they are not really different types in the sense that
there are no new classes or interfaces to represent these types (they are still just session
and entity beans). Rather, how the container manages these beans is what makes them
different. All information regarding the way the container has to handle these different
bean flavors is managed in the deployment descriptor. For entity beans, the deployment
element of <persistence-type> determines if this bean is container or bean managed. For
session beans, the deployment element of <session-type> determines if it is stateful or
stateless. Figure 2-31 shows the types of beans, updated to show the additional types:

EJB interactions
And finally, we can see how each of the EJBs that we identified will work together
as part of the banking application (Figure 2-33).

Facade session beans


A common approach when designing EJB applications with entity and session beans is to
use a facade in front of entity beans that protects the persistent data layer and controls all
the client access. Such a facade can be built using a stateless session bean that provides:
1. Home interfacecreate method of the session bean
2. Component interfaceBusiness methods for the client
3. Business methods of entity beans, for example the deposit method of the
Account bean is made available as a deposit method of the session bean.
1. New business methods that combine entity bean methods, Example a transfer method
in the session bean that invokes withdraw and deposit methods in two entity beans.

2. New business methods that wrap entity bean finder methods and format the retrieved
entity beans into usable data for the client.
Advantages of using facade session beans:
1. The persistence model is hidden from the client. Entity beans are viewed as generalpurpose data sources and are not visible to client applications.
2. Session beans can tie together multiple data sources and act as the single point of entry
to the business data layer.
3. Centralized control of transactions and security is delegated to the session facade layer
and managed more efficiently for the application.
Figure Show session beans can act as a facade layer to entity beans in front of clients.

WebSphere Studio Application Developer


Application Developer brings together most of the functionality offered by VisualAge for
Java and WebSphere Studio classic edition. Besides the functionality of these two
products, new features were added, as shown in Figure 9-1.

You might also like