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
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 user’s
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 Java’s “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
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

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

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

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

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

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

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

A public method can be invoked to change it.Developing a Simple Bean Using the BDK 1.. Figure 25-3 shows how this application at “C:\bdk\demo\sunw\demo\week6”. titled ToolBox. 5. Steps Create a New Bean 1. A color is chosen at random when the Bean begins execution. 2. 2. BeanBox. It appears as either a rectangle or ellipse that is filled with a color. The ToolBox window should include an entry labeled “vbean” for your new Bean. 3. Test In test we run the application.mft sunw\demo\week6\*. This causes the BDK to start.Create a Directory for the New Bean. . 7.jar colors. It shows how to develop a simple Bean and connect it to other components via the BDK. You should see three windows. Create a Manifest File Copy colors. The BDK is used to layout an application with one instance of the Colors Bean and one instance of the Our Button Bean.” Each time it is pressed. Create a folder “week6” at “C:\bdk\demo\sunw\demo\week6”. Start the BDK Change to the directory c:\bdk\beanbox and type run.\jars\colors4. Each time the mouse is clicked on the Bean. another random color is chosen. the color changes. Compile the Source Code for the New Bean Compile the source code to create a class file. The button is labeled “Change. and Properties.mft file to “C:\bdk\demo”. Generate a JAR File C:\bdk\demo>jar cfm . Our new component is called the Colors Bean. There is one Boolean read/write property that determines the C:\bdk\demo\sunw\demo\week6> 4. Type the following: C:\bdk\demo\sunw\demo\week6>javac vbean.Create the Source File for the New Bean: Create a file vbean.class C:\bdk\demo> 6.

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

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

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

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

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

Description This class provides information about a Bean. However. Methods in this interface determine if a Bean is executing in design mode. Methods in this interface allow a bean to execute in environments where graphical user interface is not available. A method in this interface is invoked when a constrained property is changed. A method in this interface is invoked when an exception has occurred. A customizer can provide a step-by-step guide through the process that must be followed to use the component in a specific context. this may not be the best user interface for a complex component with many interrelated properties. 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. Online documentation can also be provided. events and methods of a Bean.The Properties window of the BDK allows a developer to modify the properties of a Bean. This event is generated when bound or constrained properties are changed. Objects that implement this interface allow designers to change and display property values. 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. Therefore. beans package. A method in this interface is invoked when a bound property is changed. This interface allows a designer to provide a graphical user interface through which a Bean may be configured. A Bean developer has great flexibility to develop a customizer that can differentiate his or her product in the marketplace. a Bean developer can provide a customizer that helps another developer configure this software. 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. Instances of this class describe a property o f a Bean .

(Added by java2.4) Instances of this class describe an event that can be generated by a bean. This class provides functionality that can be used when writing property editors. This class locates a Property Editor object for a given type. (Added by java2. Instances of this class describe a method of 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. This class provides functionality that can be used when writing bean info classes. Encapsulate a call to a method that returns a result. (Added by java2. V 1. Event Set Descriptor. version 1. 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. This is generated when bound or constrained properties are changed.4) Beans that support bound properties can use this class to notify PropertyChangeListener objects. Can be used to write this information to a stream. and Method Descriptor classes. Encapsulates a call a method. (Added by java2. Handles the state information of an object. This is the super class of the property Descriptor.4) Extends EventListnerProxy and implements . (Added by java2. version 1. It is sent to objects that registered an interest in these events and implement either the PropertyChangeListner or VetoableChangeListener interfaces. V 1. Instances of this class describe an indexed property of a bean.4) Encodes the state of set of beans. Instances of this class describe a method parameter. V 1. Instances of this class describe a property of a bean.4) Supports dynamic event listener creation. Description Extends EventListenerProxy and implements PropertyChangeListener. An exception of this type is generated if a change to a constrained property is vetoed.

println("\t" + propertyDescriptor[i].demo.println("Events:").length. " + e). import java. } } } The output from this program is the following: . System. EventSetDescriptor eventSetDescriptor[] = beanInfo.colors. i++) { System.println("Bean name = " + beanDescriptor. for(int i = 0.4) Beans that support constrained properties can use this class to notify VetoableChangeListener objects.println("Properties:").getName()). } System. Used to read a bean from a XML document. BeanDescriptor. version 1.4) The Classes defined in java.out. package sunw. import java. // Show properties and events. PropertyDescriptor propertyDescriptor[] = beanInfo.getName()).Colors"). (Added by java2.getEventSetDescriptors().println("Exception caught.length.getName()).out.out. BeanInfo beanInfo = Introspector. for(int i = 0.awt. } } catch(Exception e) { System. i < eventSetDescriptor.forName("sunw.colors.getPropertyDescriptors().4) Used to write a bean from a XML document. and EventSetDescriptor classes and the BeanInfo interface. (Added by java2.*. V 1.println("\t" + eventSetDescriptor[i]. BeanDescriptor beanDescriptor = beanInfo. i < propertyDescriptor. i++) { System. It lists the properties and events of the Colors Bean that was developed earlier in this chapter. beans Introspector.out. public class IntrospectorDemo { public static void main(String args[]) { try { Class c = Class.*. (Added by java2. version 1.out.getBeanDescriptor().beans.getBeanInfo(c).demo.VetoableChangeSupport XlmDecoder XlmEncoder VetoableChangeListener. PropertyDescriptor.out. System.

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

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

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

By default. both the slider and the scroll bar have the same range (0 to 100). Now it is time to wire the components together. so the value of one will translate directly to the value of the other. To do this.of the Swing class JScrollbar. position them as shown in Figure 25-9. 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 . 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. To make your application look like the one in this book.



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

transactions. . and other middlewarerelated services. EJBs provide the architecture for server-side component-based distributed computing. The EJB specification provides a solution for a clear separation of the business logic and the intricacies of dealing with persistency.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. EJBs typically represent a business process that can be shared across applications as well as across the network.

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

you just reuse the services detailed in the specification. Concurrency 2. or life-cycle management. Servlets and Applets 2. security. . you do not need to include any code in your components to make them transactional. Transactions 6. The container is the car. Data Access Logic (optional) of EJB™ Note 1. Enterprise Edition (J2EE) defined by Sun. The component is your application EJB specifications The Enterprise Java Beans (EJB) specification is a foundation for the Java 2 Platform. Distribution Components Handle 1. The container is the platform. For example. Presentation of JSP™. As a developer. and use a set of services such as distributed transactions. Availability 4. This lets you concentrate on the business logic of the application. The component is the driver 2. Vendors use this specification to implement an infrastructure in which components can be deployed. Scalability 5.Containers Handle 1. Business Logic of EJB™ 3. Security 3.

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

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

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

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

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

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

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

Bean-container contract revisited The bean-container contract describes the interactions between an enterprise bean and its container. or process for a client. but we now describe some of the other parties involved. the entity state remains in a database. . such as the callback methods. Shared instance for multiple clients Persistent. One instance per client Not persistent. Even when the EJB™ container terminates. and the environment naming context.Purpose Shared Access Persistence Session Bean Represents Process.Performs a task. the EJBContext interface. The bean contract (Figure 2-28) includes callback methods. 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. We have already described the theory of the bean-container contract.

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

for example the deposit method of the Account bean is made available as a deposit method of the session bean. Example a transfer method in the session bean that invokes withdraw and deposit methods in two entity beans. New business methods that combine entity bean methods. Component interface—Business methods for the client 3. 1. .EJB interactions And finally. 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. Business methods of entity beans. we can see how each of the EJBs that we identified will work together as part of the banking application (Figure 2-33). Home interface—create method of the session bean 2.

Advantages of using facade session beans: 1. Figure Show session beans can act as a facade layer to entity beans in front of clients. Session beans can tie together multiple data sources and act as the single point of entry to the business data layer. WebSphere Studio Application Developer Application Developer brings together most of the functionality offered by VisualAge for Java and WebSphere Studio classic edition. as shown in Figure 9-1. Besides the functionality of these two products. Entity beans are viewed as generalpurpose data sources and are not visible to client applications. new features were added. .2. 2. New business methods that wrap entity bean finder methods and format the retrieved entity beans into usable data for the client. 3. Centralized control of transactions and security is delegated to the session facade layer and managed more efficiently for the application. The persistence model is hidden from the client.