SL291 JavaBeans Component Development Ig 1098
SL291 JavaBeans Component Development Ig 1098
SL-291
Enterprise Services
MS BRM11
303 South Technology Court
Broomfield, Colorado 80021
U.S.A.
Please
Recycle
Contents
About This Course......................................................................................xv
Course Overview .............................................................................. xvi
Course Map...................................................................................... xvii
Module-by-Module Overview ..................................................... xviii
Course Objectives............................................................................. xxii
Skills Gained by Module............................................................... xxiii
Guidelines for Module Pacing ..................................................... xxiv
Topics Not Covered......................................................................... xxv
How Prepared Are You?............................................................... xxvi
Introductions ................................................................................ xxviii
How to Use Course Materials ....................................................... xxix
How to Use the Icons...................................................................... xxxi
Typographical Conventions and Symbols ................................. xxxii
Overview of JavaBeans .............................................................................1-1
Relevance............................................................................................ 1-2
Objectives ........................................................................................... 1-3
What Is JavaBeans? ........................................................................... 1-4
A Java Component Model .......................................................1-4
Extension of the Java Platform ................................................1-5
What Is a Bean? ................................................................................. 1-6
Features of Beans.......................................................................1-6
Examples of Beans ....................................................................1-7
Classes and Beans .....................................................................1-7
Design Goals of the JavaBeans Model ........................................... 1-8
Compact .....................................................................................1-8
Easy to Create and Use.............................................................1-9
Fully Portable.............................................................................1-9
Flexible Build-time Component Editors ..............................1-10
Leverage Distributed Computing Mechanisms .................1-10
Component Architectures.............................................................. 1-11
Why Are They Useful? ...........................................................1-11
Services of Component Models ............................................1-12
Component Interface Publishing and Discovery ...............1-12
iii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Event Handling .......................................................................1-13
Persistence................................................................................1-13
Layout Control ........................................................................1-13
Application Builder Support .................................................1-13
Putting Beans Together .................................................................. 1-14
The BDK 1.0 Overview................................................................... 1-16
ActiveX as a Component Model ................................................... 1-18
Overview of ActiveX ..............................................................1-18
Advantages of ActiveX...........................................................1-20
Platform ....................................................................................1-21
Heavyweight or Lightweight ................................................1-21
Network Device Support .......................................................1-22
Interoperability........................................................................1-22
Software Versioning and Distribution.................................1-22
Distributed Computing..........................................................1-23
Performance .............................................................................1-23
Security .....................................................................................1-24
Check Your Progress ...................................................................... 1-25
Think Beyond .................................................................................. 1-26
The BeanBox ...............................................................................................2-1
Relevance............................................................................................ 2-2
Objectives ........................................................................................... 2-3
What Is the BeanBox? ....................................................................... 2-4
Running the BeanBox ...............................................................2-5
Windows of the BeanBox ................................................................. 2-6
ToolBox Window ......................................................................2-7
BeanBox Window......................................................................2-7
PropertySheet Window............................................................2-8
Design Mode in the BeanBox .......................................................... 2-9
Manipulating a Bean....................................................................... 2-10
Placing a Bean on the BeanBox Window.............................2-10
Selecting a Bean .......................................................................2-11
Moving a Bean.........................................................................2-12
Resizing a Bean........................................................................2-13
Changing Bean Properties – PropertySheet Window................ 2-16
Mechanics.................................................................................2-16
Effects on the BeanBox Window...........................................2-17
Changing Bean Properties – Customizers................................... 2-19
Bound Properties............................................................................. 2-22
Connecting Beans With Event Handlers ..................................... 2-26
Connecting Beans Through Events ......................................2-28
Saving and Restoring the BeanBox............................................... 2-31
Adding Your Own Bean to the ToolBox Window ..................... 2-33
JAR Files ...................................................................................2-33
Specifying a JAR File in an HTML File ................................2-35
v
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Objectives ........................................................................................... 4-3
What Is a Bean Property?................................................................. 4-4
Types of Bean Properties .........................................................4-4
Properties and get/set Methods .................................................. 4-6
Read and Write Properties.......................................................4-6
Naming Conventions ...............................................................4-7
Simple Properties .............................................................................. 4-8
Defining Simple Properties......................................................4-8
Adding Simple Properties to a Bean ....................................4-10
Bound Properties............................................................................. 4-13
Defining Bound Properties ....................................................4-13
PropertyChangeSupport Class ...........................................4-14
Modifying the Property set Method ...................................4-14
Example of Creating a Bound Property...............................4-15
Bound Properties and the BeanBox Edit Menu ..................4-17
Recap of Bound Properties ............................................................ 4-19
Constrained Properties................................................................... 4-20
Overview ..................................................................................4-20
Defining Constrained Properties ..........................................4-21
Handling Vetoes......................................................................4-22
Using the VetoableChangeSupport Class.........................4-23
Registering Listeners ..............................................................4-24
Modifying the Property set Method ...................................4-24
Example of Creating a Constrained Property.....................4-25
Constrained Properties and Validation ....................................... 4-27
By Source or Listener? ............................................................4-27
Validating the Property Change ...........................................4-28
Constrained Properties and the BeanBox.................................... 4-29
Recap of Constrained Properties .................................................. 4-30
Properties and the BeanBox........................................................... 4-31
Discovering Bean Properties .................................................4-31
Properties on the PropertySheet Window...........................4-32
How a View Is Determined ...................................................4-35
Example of Views ...................................................................4-36
Exercise: Defining Bean Properties............................................... 4-37
Preparation...............................................................................4-37
Overview ..................................................................................4-38
Tasks .........................................................................................4-38
Exercise Summary...................................................................4-42
Check Your Progress ...................................................................... 4-43
Think Beyond .................................................................................. 4-44
Introspection ...............................................................................................5-1
Relevance............................................................................................ 5-2
Objectives ........................................................................................... 5-3
Introduction to Introspection .......................................................... 5-4
vii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Think Beyond .................................................................................. 5-62
Persistence ...................................................................................................6-1
Relevance............................................................................................ 6-2
Objectives ........................................................................................... 6-3
Goals for Bean Storage ..................................................................... 6-4
General Java Object Storage ....................................................6-4
Bean Storage...............................................................................6-5
Java Object Serialization................................................................... 6-6
Serializable Interface...........................................................6-6
Classes That Are Serializable ..................................................6-7
What Is and Is Not Saved ................................................................ 6-8
Bean Properties and Internal State .........................................6-8
Pointers and Event Adapters ..................................................6-8
Fields Automatically Serialized ..............................................6-9
Fields Not Serialized.................................................................6-9
The Keyword transient ......................................................6-10
Input and Output Interfaces.......................................................... 6-11
Saving Beans to Streams ................................................................ 6-12
ObjectOutputStream Class..................................................6-12
Example of Code Syntax ........................................................6-13
Retrieving Beans From Streams .................................................... 6-14
ObjectInputStream Class....................................................6-14
Example of Code Syntax ........................................................6-15
Creating a Java Beans Prototype................................................... 6-16
Packaging a Prototype Bean ..................................................6-17
Deserialization and Class Loaders ............................................... 6-18
Using Beans.instantiate() ..............................................6-19
Beans.instantiate() Methodology.................................6-19
Recap of Persistence........................................................................ 6-20
Exercise: Creating a New Bean Through Serialization.............. 6-21
Tasks .........................................................................................6-21
Exercise Summary...................................................................6-23
Check Your Progress ...................................................................... 6-24
Think Beyond .................................................................................. 6-25
Customization.............................................................................................7-1
Relevance............................................................................................ 7-2
Objectives ........................................................................................... 7-3
What Can You Do Through Customization?................................ 7-4
Can You Extend Editor Support to New Property Types? .7-6
When Is a Property-Specific Editor Not Enough?................7-7
Property Sheets and Property Editors ........................................... 7-8
Property Sheets..........................................................................7-8
Property Editors ........................................................................7-9
Review of Views.............................................................................. 7-10
The PropertyEditor Interface..................................................... 7-11
ix
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Example of an Adapter Hookup Class ..................................8-6
Types of Adapters............................................................................. 8-8
Common Uses of Adapters......................................................8-9
Diagrams ..................................................................................8-10
Differentiating Adapters From Normal Listeners...................... 8-12
Case With No Adapters .........................................................8-12
Case With Adapters................................................................8-13
Demultiplexing Adapter Example ............................................... 8-14
Application Window ..............................................................8-14
Description of Application ....................................................8-15
Appl.java Code .....................................................................8-16
Widgets.java Code...............................................................8-17
ActionAdapter.java Code..................................................8-18
Multiplexing Adapters ................................................................... 8-20
Overview of Multiplexer Exercise ........................................8-20
Exercise: Working With Adapters ................................................ 8-23
Preparation...............................................................................8-23
Tasks .........................................................................................8-24
Exercise Summary...................................................................8-30
Check Your Progress ...................................................................... 8-31
Think Beyond .................................................................................. 8-32
Distributed Computing
With Beans...................................................................................................9-1
Relevance............................................................................................ 9-2
Objectives ........................................................................................... 9-3
Motivating Scenarios for Distributed Bean Programming ......... 9-4
Areas of Familiarity ..................................................................9-4
Future Enterprise JavaBeans ...................................................9-6
Applications for Distributed Beans ........................................9-6
JavaSoft Distributed Computing Technologies .......................... 9-10
Definition of JDBC .......................................................................... 9-11
JDBC API and Drivers............................................................9-11
Overview of JDBC Architecture.................................................... 9-12
BeanBox JDBC Bean........................................................................ 9-14
Advantages of Database-Related Beans ..............................9-16
Definition of RMI ............................................................................ 9-17
BeanBox RMI Bean.......................................................................... 9-18
RMI Architecture Overview .......................................................... 9-19
Transport Layer.......................................................................9-20
Remote Reference Layer ........................................................9-20
RMI Stubs and Skeletons .......................................................9-21
rmic Command.......................................................................9-21
rmiregistry Application ....................................................9-21
RMI Exercise Code.......................................................................... 9-22
Exercise Description ...............................................................9-22
xi
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Instantiating a Bean From a Serialized Stream .................10-38
Roles of Class and ClassLoader .............................................. 10-39
The Class Class ....................................................................10-39
The ClassLoader Class .......................................................10-41
Sample Code .................................................................................. 10-43
Instantiating a Bean in an Applet .......................................10-43
Instantiating a bean in an Application...............................10-45
Hooking Beans Together.............................................................. 10-50
Exercise: Writing Applets or Applications With Beans........... 10-52
Preparation.............................................................................10-52
Tasks .......................................................................................10-53
Exercise Summary.................................................................10-61
Check Your Progress .................................................................... 10-62
Think Beyond ................................................................................ 10-63
Business Environment for
JavaBeans...................................................................................................11-1
Relevance.......................................................................................... 11-2
Objectives ......................................................................................... 11-3
“Write once, run anywhere” ......................................................... 11-4
Component-Based Software Review............................................ 11-5
Business Influences .................................................................11-5
Major Elements........................................................................11-6
Review of Services ..................................................................11-7
Bridging JavaBeans to Other Component Models ..................... 11-8
ActiveX Bridge.........................................................................11-9
InfoBus Technology ...................................................................... 11-10
InfoBus Technology and JavaBeans ...................................11-11
InfoBus Architecture Overview ..........................................11-11
Development Environments ....................................................... 11-12
Integrated Development Environments ............................11-12
Rapid Application Development........................................11-13
Visual Application Builder Tools ............................................... 11-14
What Are They?.....................................................................11-14
Examples ................................................................................11-15
Deciding on the Tool for You ..............................................11-19
Check Your Progress .................................................................... 11-20
Think Ahead .................................................................................. 11-21
Transitional Beans
(Optional) ..................................................................................................12-1
Relevance.......................................................................................... 12-2
Objectives ......................................................................................... 12-3
What Are Transitional Beans?....................................................... 12-4
Compatibility With JavaBeans FCS ......................................12-4
Browser Support for JavaBeans ............................................12-5
Creating a Transitional Bean ......................................................... 12-6
xiii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
About This Course
Course Goal
JavaBeans Component Development provides you with the knowledge
and skills necessary for creating reusable software components using
the JavaBeans™ API (application programming interface). This
includes an understanding of: Bean properties, introspection and
reflection, Bean events and event handling, customization, and
persistence.
✓ You should use this module to get the students excited about this course.
✓ With regard to the overheads: To avoid confusion among the students, it is very important
to tell them that the page numbers on the overheads have no relation to the page numbers
in their course materials. They should use the title of each overhead as a reference.
✓ The strategy provided by the “About This Course” is to introduce students to the course
before they introduce themselves to you and one another. By familiarizing them with the
content of the course first, their introductions will have more meaning in relation to the
course prerequisites and objectives.
✓ Use this introduction to the course to determine how well students are equipped with the
prerequisite knowledge and skills. The pacing chart on page xxiv enables you to
determine what adjustments you need to make in order to accommodate the learning
needs of students.
xv
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Course Overview
Developers taking this class will gain the essential knowledge and
skills to create JavaBean components that run on every Java virtual
machine and can be reused in the widest variety of development tools,
containers, and popular environments available.
Each module begins with a course map that enables you to see what
you have accomplished and where you are going in reference to the
course goal. A complete map of this course is shown below.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
● Module 5 – Introspection
● Module 6 – Persistence
● Module 7 – Customization
Lab exercise: Use Beans on the client side to make method calls
through remote method invocation (RMI) to a remote Java
application.
In this module, you will learn what code you need to write to
have your Beans run in an applet or an application.
Module
1 1 1
Skills Gained 1 2 3 4 5 6 7 8 9
0 1 2
✓ Refer students to this matrix as you progress through the course to show them the
progress they are making in learning the skills advertised for this course.
✓ Module 12 is optional and thus does not cover any skills that are essential to the course.
The table below provides a rough estimate of pacing for this course.
This course does not cover the topics shown on the above overhead.
Many of the topics listed on the overhead are covered in other courses
offered by Sun Educational Services (SES):
To be sure you are prepared to take this course, can you answer the
questions shown on the above overhead in the affirmative?
✓ It might be appropriate here to recommend resources from the SES catalog that provide
training for topics not covered in this course.
Now that you have been introduced to the course, introduce yourself
to each other and the instructor, addressing the items shown on the
above overhead.
Exercise objective – Indicates the objective for the lab exercises that
follow. The exercises are appropriate for the material being discussed.
Typeface or
Meaning Example
Symbol
Philosophy
The JavaBeans Component Development course has been created to allow
for interactions between the instructor and the student as well as
among the students themselves. In an effort to enable you to
accomplish the course objectives easily, and in the time frame given, a
series of tools have been developed and support materials created for
your discretionary use.
Course Tools
To enable you to follow this structure, the following supplementary
materials are provided with this course:
● Relevance
The course map allows the students to get a visual picture of the
course. It also helps students know where they have been, where
they are, and where they are going. The course map is presented
initially in the “About This Course” section in the student’s
guide. The course map is then displayed at the beginning of each
module with the appropriate module highlighted.
● Lecture Overheads
● Small-Group Discussion
Network
Hardware
● A server machine with ample disk space for loading the majority
of the required software; directories containing loaded software
are to be exported to student workstations for mounting
▼ 32 Mbytes RAM
Software
Mention to students at the beginning of the course that they can copy
all their work to a tape or diskette to take home with them. This will
give them time to purchase a tape or diskette if they did not bring one
with them.
● Set up student accounts with a copy of the lab files to use in this
course in each account on every workstation.
● Install the jam utility for creating JAR files (included with
distribution files in the $HOME/SL291files/bin directory).
Note – Any browser can be used to view the API docs provided with
the JDK. However, at the time of this writing, Netscape
Communicator 4.0, Microsoft Internet Explorer, and HotJava browser
support JDK 1.1 and Beans developed with BDK 1.0. If you think you
might be doing Module 12, “Transitional Beans,” and that you may
have students who will want to do some work creating transitional
Beans, you will also want to have a Java-enabled browser that does not
yet support JDK 1.1.
If you have a projection system for projecting HTML slides and are
planning to use the HTML slides, you need to do the following:
/location_of_HTML_directory/
OH.Title.doc.html
Note – This document does not describe the steps necessary to set up
an overhead projection system because it is unknown what will be
available in each training center. This setup is the responsibility of
each training center.
All of the course files for this course are available from the
education.central server in the file SL291_revX_XXXX.tar.Z.
Each component below can also be accessed separately from
education.central.
Course Components
The SL-291 course consists of the following components:
● Instructor’s Guide
● Student’s Guide
● Art
● Overheads
● Lab files
You will need approximately 2.5 Mbytes of disk space for the
lab files.
Student Workstations
/ 20 Mbytes
swap 75 Mbytes
/usr 230 Mbytes
/opt 70 Mbytes
/var 70 Mbytes
/home Remainder
Student Accounts
Note – Follow the procedures used at your training center for creating
student accounts on each workstation.
Student Workstations
After you have created the student accounts, copy the contents of the
labfiles directory to each account on every student workstation
(approximately 2.3 Mbytes).
Each student account should have a file structure similar to that shown
in the following figure:
SL291files
and so on
Source files
Jamfiles course_examples solutions
sunw
run command
and so on
Student Workstations
jam Command
Note – If using Solaris 2.6, see the section called Solaris 2.6 users and
JDK 1.1.
Mount the directories from the server that contain the JDK, JDK docs,
and browsers. For example, the server could share a central directory
and the clients’ vfstab or auto_master could mount that directory as
/SL291 or /javafiles.
Environment Variables
● Set the PATH variable to include the path to the JDK’s bin
directory (for accessing the commands javac, java, and so on),
and the absolute directories for the executables of the browsers
you installed (or the appropriate mount point directories).
Student Workstations
mv jam to jam0
mv jamsol26 to jam
Server Machine
After installing the operating system, install the following software in
directories that are exported to and mounted by student workstations.
Pull the latest JDK (JDK 1.1 or later) and JDK doc files from
http://www.javasoft.com/nav/download/index.html and follow
the installation instructions provided to install the JDK and docs.
Note – The JDK and doc files can be installed on one machine. The
remaining machines in the lab can then mount the directory with the
JDK software.
Browsers
You can use any browser to view the JDK API documents. Download
the browser from the Web and follow the installation instructions
provided with the browser to install it on each student workstation.
Course Map
The main goal of this module is to help you understand the JavaBeans
architecture as a component model.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
1-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.
✓ The developer must understand how to use the software, its functionality, properties, and
methods. This understanding can be provided by good documentation. This requires that
the documentation be written and then read. Sometimes this does not happen. In addition,
the use of standard naming conventions combined with encapsulation can add to the
reusability of software.
✓ You might also briefly discuss how hardware or automotive systems are developed from
components to help set the scene for this module.
2. What advantage does the Java component model offer over other
component models?
✓ The Java component model (JavaBeans) provides greater portability because it is created
in the Java programming language. It is also enhanced by functionality provided by the
Java Platform, such as object serialization, cut-copy-paste on the desktop, network
awareness, and distributed computing mechanisms such as RMI and JavaIDL, to name a
few. In addition, all JDK 1.1 components are simple beans.
● Define JavaBeans.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
What Is JavaBeans?
JavaBeans APIs
The JavaBeans 1.0 API specification describes the core specification for
the JavaBeans component architecture. The Javadoc documentation for
the JavaBeans classes and interfaces is provided in the doc directory of
the Beans Development Kit (BDK 1.0).
✓ Refer to the URL locations under "References" on page -3.
What Is a Bean?
Features of Beans
Bean components can vary in the functionality they provide, however,
the following features are typical in all beans:
Examples of Beans
Beans vary in functionality and purpose. Some examples of beans
include:
Note – All JDK 1.1 AWT components are simple bean components.
● An animation applet
● A spreadsheet application
✓ Note that applets and applications can themselves be beans.
Compact
The JavaBeans architecture was designed to leverage much of the
functionality provided with the Java Platform so that the JavaBeans
architecture would remain a very compact model.
Compact (Continued)
The JavaBeans component model also uses the JDK 1.1 Serialization
API for bean persistence, and the cut-copy-paste mechanisms of the
AWT.
✓ Serialization, distributed mechanisms, reflection mechanisms, and so forth are not part of
the JavaBeans API, but the JDK itself. Other component models may actually have to build
this functionality into their model.
Fully Portable
JavaBeans components have a distinct advantage over other
component models: they are not bound to a particular platform,
container, or component model. Because the JavaBeans model is
written in the Java programming language, and the JavaBeans API is
part of the standard Java Platform, JavaBeans components are fully
portable.
Component Architectures
Component Architectures
● Event handling
● Persistence
● Layout control
Event Handling
Event passing is the mechanism by which components communicate
with each other. Components broadcast events and the underlying
framework delivers the events to the components that want to be
notified. The notified component usually takes some action based on
the event that took place.
Persistence
Component models provide a mechanism for persistence that enables
the state of components to be stored in a non-volatile place for later
retrieval.
Layout Control
Layout control in component models is two-fold:
Suppose you connect these beans so that when the timer bean triggers
an alarm, the random number generator produces a new number
between two specified values. This new number is then sent to the
animation bean to control the speed at which Duke does cartwheels in
the animation. The graphing bean graphs the speed of the Duke over
time (intervals are based on the timer bean).
Figure 1-1 shows the BDK BeanBox which is used by developers to test
their beans before deploying them in an actual tool. Using the BeanBox
to test Beans is very similar to how developers use the appletviewer to
test applets before implementing them in a full-blown browser.
Hashed boundary
around the BeanBox
Bean indicates
the currently selected
Bean
Overview of ActiveX
ActiveX is a component model from Microsoft (and thus provides the
five major services of a component model). The ActiveX model
supports components written in other languages, but these other
components must be accessed through ActiveX, not their native APIs.
Component-based
application
ActiveX API
OLE OLE
control document
OCX Java
Components control Bean
1. Diagram taken from the white paper “Component-Based Software With JavaBeans
and ActiveX.”
Advantages of ActiveX
ActiveX is built on a mature technology (Object Linking and
Embedding [OLE] technology) and there are many components
available. As mentioned previously, the ActiveX model supports
components from different programming languages, providing access
to the rich functionality of Microsoft components.
✓ OCX definition from http://www.zdnet.com/wsources/content/topics/ocx.html: An OLE
Custom control. An object-oriented custom control that is developed under OLE. OCXs
are created as separate executable modules and are dynamically linked at runtime. An
OCX object allows the application more control and customization of the object’s
functions than does a standard OLE object.
Platform
ActiveX is platform-specific—it can only be used where Microsoft has
ported the framework and components. JavaBeans components are
platform neutral because they are written in the Java programming
language.
Heavyweight or Lightweight
ActiveX components require a heavyweight application to provide a
container in order to run. JavaBeans components are considered
lightweight and require only the Java interpreter or an applet viewer
(such as a browser or the Applet Viewer).
Interoperability
Unlike the ActiveX model, JavaBeans components do not encapsulate
components from other vendors. A JavaBeans component
interoperates with other architectures (ActiveX components included)
through a two-way bridge.
Distributed Computing
ActiveX components use Distributed Common Object Model (DCOM)
in object-oriented distributed computing applications. However,
CORBA is being used in the industry as the standard in distributed
computing for network connectivity in enterprise-wide applications.
The JavaBeans model leverages on the Java Platform, which includes
the CORBA standard for object-based distributed computing. This
implies that through CORBA, Beans can communicate and access
components written in many different languages on a wide range of
computing platforms.
Performance
To be efficient in the ActiveX model, existing OLE components must
be rewritten. ActiveX components enjoy some performance advantage
over JavaBeans components because of their inherent native code.
However, with just-in-time (JIT) compilers and HotSpot compilers for
Java, performance of Beans is improving and quickly becoming a non-
issue.
Security
The ActiveX model relies on digital signatures on components. Digital
signatures verify the source of a component, but do not limit the
functionality accessible by the component. Trojan horses and viruses
coded into third-party components can invade a system.
Before moving on to the next module, check that you are able to
accomplish or answer the following:
❑ What is a bean?
Course Map
This module covers how to run, work with, and load your beans in
the BeanBox.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
2-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Relevance
✓ Pose the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.
• Proper handling of events (this usually requires interaction with other beans)
• Presented in lab – The objective is to have students actually do what you are
presenting so that they better understand the content. You will have to monitor the
class carefully so that students do not start doing other things on their own as you
move through the presentation. Restrict students to what is asked of them as each
piece of information is presented. After everything is covered, you might give them
15–20 minutes to experiment with the beans provided with the BDK. Try to keep the
total time limited to about 1.5 hours total lecture and lab time.
• Self-paced – Let students read the module, and do the short exercises as they
progress through the module. You then can walk around the room, monitoring
progress and answering questions. This alternative is especially attractive if you find
it difficult to control what students do when they perform the short exercises as you
present the material.
● Explain what a Java archive (JAR) file is and how it can be used.
● Create a JAR file for a prewritten bean and add it to the ToolBox
window of the BeanBox.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
The BeanBox is not a builder tool. Using the BeanBox, you cannot
generate code to create applications or applets for what you have
connected together in the BeanBox.
✓ Installation of the BDK is not covered since it is very straightforward—download the BDK
from the JavaSoft Web pages and run the downloaded script.
Hashed boundary
around the BeanBox
Bean
✓ Note that when the windows are displayed, they all appear in a row: the ToolBox, the
BeanBox, and then the PropertySheet window.
ToolBox Window
The ToolBox window, also referred to as the bean palette, displays the
current beans available to the BeanBox.
✓ When the BeanBox is started (using run.sh), JAR files located in the jars directory are
read and the beans in these JAR files are loaded into the ToolBox window. If you modify
your beans and rebuild the JAR files, quit the current BeanBox and restart using run.sh.
Your JAR files are reread with the changes you made.
BeanBox Window
The BeanBox window, also called the Composition window, is where a
bean from the bean palette is placed. Sizing, moving, changing
properties, using the BeanBox menus, and so forth are carried out
relative to the bean currently selected in this window.
PropertySheet Window
The PropertySheet window displays the properties of the bean
currently selected in the BeanBox window.
Manipulating a Bean
Note – You can clear the BeanBox window of all beans by choosing
File ➤ Clear.
Selecting a Bean
A bean in the BeanBox window is selected by clicking on the
boundary area of the bean. When the bean is selected, a hashed border
is displayed around the bean.
Manipulating a Bean
Moving a Bean
Once a bean is selected, you can move it by positioning the mouse on
the hashed boundary (the mouse pointer changes to four-way arrows
) and then pressing SELECT while you drag the bean to the new
position.
Resizing a Bean
To resize a bean, select the Bean and position the mouse in a corner of
the boundary for the bean (the mouse pointer changes to a diagonal
arrow pointing into an angle ). Then press SELECT while you
stretch the bean.
2. Move the two buttons to the top of the BeanBox window (side by
side) and resize them to be 1.5 inches wide and 1 inch in height.
✓ To remove a bean from the BeanBox window, select the bean and choose Edit ➤ Cut.
As noted earlier, when you select a bean in the BeanBox window, the
properties of the bean are displayed in the PropertySheet window.
This enables you to change and customize the bean. For example,
change the foreground or background color, change the font type or
size, and so forth.
Mechanics
The mechanics of changing a property vary according to the property
type. Some properties provide a menu of choices, some are an editable
text field, while still others display a dialog window of choices.
✓ Here are some questions to stimulate thinking ahead to the module on introspection: How
are the properties of a bean discovered? How is the functionality for the type of changes
allowed for each property defined? The answers to these questions are provided later in
this course during the discussions on introspection, properties, property editors, and
customization.
if (Beans.isInstanceOf(target, Component.class)) {
((Component)(Beans.getInstanceOf(target, Component.class))).repaint();
}
Assuming you have the beans in the BeanBox from the previous
demonstration, do the following:
JDBC SELECT
customizer
ExplicitButton
customizer
Bound Properties
Notice that the menu displayed in Figure 2-5 on page 20 also shows a
Bind property choice. If a bean has a bound property (considered a
source), you can connect the bound property to another property, the
target property, on some other bean. When this is done, then the target
property is updated when the bound property is changed.
Note – More details on bound properties and how to create them can
be found in Module 4, ‘‘Bean Properties.”
Figure 2-7 Property Dialog Window for the Source bean With a
Bound Property
Figure 2-8 Selecting the Target Bean for the Bound Property
Note – The visual style used in the BeanBox for connecting a bound
property to a target property (and for connecting an event from a
source bean to a method in a target bean as you will see on page 26) is
not part of the JavaBeans architecture. Other builder tools may provide
a different interface.
8. Change the foreground color of the button and notice that the
background color of the BeanBox also changes.
To have the events fired by one bean cause another bean to take some
action, you need to connect (or hook up) the beans. Hooking up two
beans involves the following steps:
Each bean will have its own submenu of events. The events are
grouped, and the groups are named by their event listener
interface. For example, a button is the source for ActionEvent
events (which are associated with the ActionListener
interface), so a button will have an action submenu.
Events will be sent from the source bean to the target bean.
✓ The BeanBox code will create an adapter class for the source and target to be hooked
together. This code is stored in the beanbox/tmp/sun/beanbox directory.
Note – The Load option is for loading a file that you had previously
saved using File ➤ Save into the BeanBox. The Loadjar option is for
loading a specific JAR file created from a makefile, such as the JAR
files found in the jars directory of the BDK.
✓ Notice that when you reload the properties.lab.jar file, the background of the BeanBox
window remains the same color as it was before the load (regardless of the color of the
background of the BeanBox when the BeanBox was saved to properties.lab.jar). Why?
I am not sure. This happens whether you are in design mode or not.
✓ Note – I have noticed that when in design mode (the View menu), the situation sometimes
occurs that the BeanBox is cleared and the BeanBox itself is not selected. When this
happens, the Load File dialog window does not display when you choose File ➤ Load. To
solve this problem, click on the BeanBox window to select the BeanBox. Then do
File ➤ Load again.
Stop Juggling
Start Juggling
You can save what you have created in the BeanBox by using
File ➤ Save. A dialog window is displayed for you to specify a file
name to save to.
All the beans in the BeanBox window are written to a serialized stream
(called ___comp_ROOT.ser), and then to a manifest file. The ser file
and all of the hookup classes (that were generated from the beans you
hooked together using events) are written to a JAR file. The name of
the JAR file is the file name you enter in the dialog window.
✓ The ser file created is located in beanbox/tmp. So each time a save is done in the
BeanBox window, this file is rewritten. Serialization is covered in Module 6, ‘‘Persistence.”
Hooking beans up manually to run outside the BeanBox is covered in Module 10, ‘‘Beans
Outside of the BeanBox.”
4. Make sure the Start, Stop, Hide, and Show buttons function as
expected.
✓ If students saved the state of the BeanBox with the juggler not juggling, when the bean is
restored from the saved file, the juggler is juggling. Why? If you read through the code for
the Load() method in BeanBox.java, it calls readContents(ois) to read back the contents
of the JAR file. In the readContents() method, it checks if the bean is an applet (which the
juggler is), and if so, calls ((Applet)bean).start(); The start() method in the juggler
calls startJuggling(), so the applet begins juggling after being restored.
In order to add a bean that you have written (or acquired from the
Internet or a third-party) to the ToolBox window for testing, you need
to create a JAR file.
JAR Files
JAR stands for Java ARchive and is a file format based on the ZIP file
format. It was created for the main purpose of enabling Java applets
and related components (.class files, images, sounds) to be
downloaded to a browser in a single hypertext transfer protocol
(HTTP) transaction. However, a JAR file can contain files of any type.
In beans development, JAR files usually contain a manifest file, may
contain serialized beans (stored in .ser files), and always contain Java
class files.
One of the added benefits of using the JAR format is that it supports
compression (reducing the size of the downloaded file and
consequently the download time). Moreover, entries in a JAR file can
have digital signatures for authentication and security.
✓ The JAR format is written in the Java programming language and therefore provides a
format that is cross-platform. (The ZIP and tar formats are available for almost every
platform because these formats have been ported to a wide variety of platforms.) The JAR
format is the preferred way to bundle the pieces of a Java applet and to distribute beans.
To use a JAR file in an HTML file, specify the JAR file using the
archive parameter of the applet tag:
<applet code=Animator.class
archive="jars/animator.jar"
width=460 height=160
>
</applet>
The JAR file must be relative to the location of the hypertext transfer
markup language (HTML) file or the CODEBASE parameter, if used.
Using JAM
An easy way to create a JAR file is to create a makefile to use with JAM
(Just Another Make). The online version of the examples provided in
this course can be compiled using the provided JAM makefiles. JAM is
freely available and can be downloaded from
http://www.perforce.com/jam/jam.html.
✓ If a JAR file does not contain a MANIFEST, all entries in the JAR file are considered to be
beans.
✓ The jam utility was chosen for use in this course because it is a cross-platform makefile
utility and freely available on the web.
and so on
JamfilesSource files course_examples solutions
get_started
jars demo beanbox
sunw
run command
and so on
All directories named modx-something have been created for this course
and contain course examples used in the Student’s Guide and
solutions for the lab exercises. The packages directory will contain
Jamfiles that you run to compile the exercises. The work subdirectory
will contain the Java source files that you create in the exercises.
Tasks
There are many jam files in the work directory. The -s flag sets a
variable value that is passed to the jam program. When jam is
invoked, it automatically processes the Jamfile. The Jamfile in
the work directory processes the file specified by the jf variable,
if no value is specified, the Jamfile will compile every makefile
in the work directory.
Tasks
% jam -sjf=twoSimple.jam
Note – Make sure you are in design mode so that you can see the bean
added to the ToolBox window.
or
Note – The details of why the following beans used can be connected
together and how this all works is presented in Module 3, the bean
event model.
● What events does each bean display on the Edit ➤ Events menu?
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the demonstrations.
● Experiences
✓ Ask students what their overall experiences with the BeanBox have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of the demonstrations in
this module.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of these demonstration
experiences.
Before moving on to the next module, check that you are able to
accomplish or answer the following:
❑ Create a JAR file for a prewritten bean and add it to the ToolBox
window of the BeanBox.
How does the event handling work for beans? How do you define
your own events? How do you indicate you want to receive a
particular event?
Course Map
The JDK 1.1 event model was designed to accommodate the JavaBeans
architecture. So to understand how events and event handling works
in the JavaBeans component model, it is necessary to understand
events, listeners, and sources under JDK 1.1.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
3-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Relevance
✓ Yes, you can develop a Bean component that is not a source of any events. For example,
a simple graphic of a circle whose size and color can be changed through property
methods would not require you to understand event handling. However, if you intend to
write more complex Beans that are meant to be connected to other Beans in meaningful
ways, you must understand the event model.
✓ Although this module spends time illustrating how to create new events, listener
interfaces, and sources, you should mention to students that they should try to use those
provided by the JDK whenever possible (for greater reusability). The intent here is to have
students completely understand all aspects of the delegation event model.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
✓ As more students progress through SL-275 and the new event model, you may find that
much of the material in this module can be covered quickly as review.
What Is an Event?
When the user performs an action at the user interface, this causes an
event to be issued. In the Java programming language, events are
objects that describe what happened. A number of different types of
event classes exist to describe various general categories of user action.
The event model in JDK 1.1 and the event model used by the
JavaBeans architecture is a delegation model. This model is composed
of three main parts: sources, events, and listeners.
Register listener
✓ Rather than using an adapter, you could create a different action listener, one for each
distinct purpose and registered with just one source that fires an ActionEvent.
Code Explanation
There are several key items to point out in the code example:
For each category of events, there is an interface that must be defined by any class that
wants to receive the events. That interface specifies one or more methods that must be
defined. Those methods will be called when particular events arise. Table 3–1 lists the event
categories, giving the interface name for each category and the methods required. The
method names are mnemonic, indicating the conditions that will cause the method to be
called.
The event argument shown for each method indicates the event type that is handled by the listener.
When handler methods are called, they receive an event state object
that contains all of the relevant information about the event. The
attributes associated with the event are accessed through the object’s
methods. All event classes derive from java.util.EventObject. The
most useful method in the EventObject class is:
public Object getSource()
This method returns the object that generated the event. Notice the
source object does not have to be a subclass of java.awt.Component.
The event model in JDK is most often applied to GUI components, but
it can just as easily be applied to a non-visual timer, file transfer
protocol (FTP) client, or database query object.
Although the JDK defines many types of events, there may come a
time when an appropriate event class does not exist. In these cases,
create a new event class by subclassing either java.util
EventObject or one of its subclasses.
For example, suppose you want to create an event that signifies the
change of a stock price. You could define an event called
StockPriceChangeEvent. The definition of the event could be:
1 import java.util.*;
2 public class StockPriceChangeEvent extends EventObject {
3 private Stock stock;
4
5 public StockPriceChangeEvent(Object source, Stock s) {
6 super(source);
7 stock = s;
8 }
9 public Stock getStock() {
10 return stock;
11 }
12 }
✓ Point out to students that the Stock is not derived from Component and it acts as the
source of the event.
Listeners
Event Listeners
Every event class is matched to one or more event listener interfaces.
For example, ActionListener handles ActionEvent, FocusListener
handles FocusEvent, and KeyListener handles KeyEvent. Some
event types are supported by multiple-event listener interfaces. For
example, MouseEvent is supported by MouseListener and
MouseMotionListener interfaces.
Listeners
ActionListener Interface
Event listener interfaces are always defined with EventListener as
one of the base interfaces. The ActionListener interface of the JDK is
defined in the ActionListener.java file. Its contents are shown
below:
1 package java.awt.event;
2 import java.util.EventListener;
3
4 /**
5 * The listener interface for receiving action events.
6 */
7 public interface ActionListener extends EventListener {
8 /**
9 * Invoked when an action occurs.
10 */
11 public void actionPerformed(ActionEvent e);
12 }
Listeners
Once the event and the listener interface are defined, you need to
define a source that generates the StockPriceChangeEvent and
indicates how listeners are to register to receive the event.
✓ Try to use the standard interfaces whenever possible.
Event Sources
Identifying Sources
A source for a type X event identifies itself by defining the registration
methods that a listener is required to use in order to receive
notification of type X events. These registration methods include an
addXXXListener(XXXListener al) and a
removeXXXListener(XXXListener rl) method.
Multicast Syntax
A multicast source can have multiple listeners at any time.
The syntax for creating a multicast source (the typical case) is to define
the add and remove methods for the listener type:
1 private Vector listeners = new Vector();
2
3 public void addStockPriceChangeListener(StockPriceChangeListener spl)
{
4 listeners.addElement(spl);
5 }
6
7 public void
8 removeStockPriceChangeListener(StockPriceChangeListener spl) {
9 listeners.removeElement(spl);
10 }
Unicast Syntax
If you have a situation that warrants only one listener at any time (the
source is unicast), the syntax is similar to the multicast case. The only
difference is that the add method needs to throw a
TooManyListenersException if there is already a listener registered.
1 private StockPriceChangeListener listener = null;
2
3 public void addStockPriceChangeListener(StockPriceChangeListener spl)
4 throwsjava.util.TooManyListenersException
5 {
6 if (listener == null) {
7 listener = spl;
8 } else {
9 throw new java.util.TooManyListenersException();
10 }
11 }
12
13 public void removeStockPriceChangeListener
14 (StockPriceChangeListener spl) {
15 if (listener == spl) {
16 listener = null;
17 }
18 }
Note – Complete code for the Stock example can be found in the
course_examples directory for this module.
✓ The JavaBeans specification recommends that you copy the listener vector in order to
freeze the state of the set of EventListeners that the event should be delivered to prior to
delivery. This ensures that any changes made to the vector from a target listener’s method
during the delivery of this event will not take effect until after the event is delivered.
Synchronous Delivery
Most event sources are multicast, in which case the source is
responsible for keeping track of all of the listeners for each different
event type it fires. When an event occurs, the source must call each
target listener for that event. This event delivery is synchronous; the
call to a target listener is a normal Java method invocation, executed
synchronously, using the caller’s thread.
✓ It is important, therefore, that event handler methods do not take an excessively long time
to complete as that would reduce the perceived responsiveness of the overall system.
Time-consuming processing, such as querying a database, should be delegated to
separate threads.
Multiple Listeners
If you want to write a program that performs multiple actions based
on a single event, you should code that behavior into your handler
method. However, sometimes a program’s design requires multiple
unrelated parts of the same program to react to the same event. This
might happen if, for example, a context-sensitive help system is being
added to an existing program.
✓ There are issues with how delivery of events is handled by the source if a target listener
throws an exception (which they are allowed to do). There are also race and deadlock
situations in a multi-threaded system. See the JavaBeans specification for more details on
these situations.
XXXListener interface
public interface XXXListener extends EventListener{
XXXHandler(XXXEvent evt);
}
XXXEvent
public class XXXEvent extends EventObject{
//Definition for XXXEvents
}
Event source
Defines listener registration methods:
public void addXXXListener(XXXListener al) and
public void removeXXXListener(XXXListener rl)
Fires XXXEvent
Event listener
Implements the XXXListener interface
Stock Class
1 package sl291.stock;
2
3 public class Stock {
4 String company;
5 String symbol;
6 double price;
7
8 public Stock(String co, String sym, double p) {
9 company = co;
10 symbol = sym;
11 price = p;
12 }
13
14 public void setCompany(String co) { company = co; }
15
16 public String getCompany() { return company; }
17
18 public void setSymbol(String sym) { symbol = sym; }
19
20 public String getSymbol() { return symbol; }
21
22 public double getPrice() { return price; }
23
24 public void setPrice(double p) { price = p;}
25 }
StockPriceChangeEvent Code
Just in case, here is the source code for the event and listener again:
1 package sl291.stock;
2
3 import java.util.EventObject;
4
5 public class StockPriceChangeEvent extends EventObject {
6 private Stock stock;
7
8 public StockPriceChangeEvent(Object source, Stock s) {
9 super(source);
10 stock = s;
11 }
12
13 public Stock getStock() { return stock; }
14 }
1 package sl291.stock;
2
3 import java.util.EventListener;
4
5 public interface StockPriceChangeListener extends EventListener {
6 public void priceChange(StockPriceChangeEvent e);
7 }
StockWatcher Code
StockDetail Class
Now, the TextArea of the StockDetail Bean will display the real-time
information about the stock.
Preparation
To be prepared to do this exercise, you should understand the
terminology presented in Module 2, ‘‘The BeanBox.” This includes
understanding how Beans are hooked together in the BeanBox and
some familiarity with the Edit ➤ Events submenu. You also should be
able to code what is asked of you in the tasks for this exercise using
the sample code that was presented in this module.
Tasks
Note – All of the code that you create here will be part of the
sl291.dataTable and sl291.dataButton packages.
This directory contains the Java source and class files for the Bean
components and their associated event and listener definitions.
The makefile is already created and is called dataTable.jam.
▼ A source component
Tasks
Tasks
Note – The JAR file created for the DataTableButton Bean needs the
related class files for the listener interface and event type.
3. Use the makefile created in step 2 to generate your JAR files for
the DataTableBean and the DataTableButton Beans.
DataTableEvent DataTableBean
DataTableButton
handles DataTableEvents with
fireDataTableEvent
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.
Before moving on to the next module, check that you are able to
accomplish or answer the following:
Course Map
This module discusses the types of properties defined in the JavaBeans
specification and how to create different bean properties.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
4-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.
● Explain how the naming conventions for get and set methods are
used to locate properties.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
All properties of a bean are accessed using method calls on the bean.
These accessor methods follow a naming convention, and except for
Boolean properties, are the getXXX and setXXX methods.
Naming Conventions
The name of a bean property and the names of the property accessor
methods are dependent on each other. So, for example, a bean with a
read-write property called height would imply getHeight() and
setHeight() methods for the bean.
Simple Properties
Color property
Radius property
✓ Other properties are obtained from the Canvas component that the bean inherits.
Bound Properties
PropertyChangeSupport Class
The JavaBeans API provides a utility class called
PropertyChangeSupport that makes creating a bound property easier
for a developer. This class can be used to keep track of
PropertyChangeListeners and to fire the PropertyChangeEvent event
when your bound property changes. This means that you do not have
to maintain the vector of all listeners and call the propertyChange()
method on each listener when your bound property changes.
Below is the typical code you would incorporate into your bean to
handle registration of PropertyChangeListeners for your bound
property.
1 PropertyChangeSupport support = new PropertyChangeSupport(this);
2
3 //registration methods for PropertyChangeListeners
4 public void addPropertyChangeListener(PropertyChangeListener pl) {
5 support.addPropertyChangeListener(pl);
6 }
7
8 public void removePropertyChangeListener
9 (PropertyChangeListener pl) {
10 support.removePropertyChangeListener(pl);
11 }
✓ It is not shown here but the Edit ➤ Events submenu adds a PropertyChange option.
✓ Students may ask why properties that are not bound appear in the PropertyNameDialog
window. This question is out to the JavaSoft team—reading the source code in the
BeanBox (BeanBox.java and PropertyNameDialog.java) seems to indicate that the
only properties that should be displayed are the bound properties for the bean. Check the
TickTock and BridgeTester beans. The TickTock bean also displays a property that is not
bound (in addition to the bound property). The BridgeTester bean only displays the
property intValue (although there are many bound properties), but the BeanInfo file for
this bean specifically sets intValue as the only bound property using isBound(true),
whereas it sets isBound(false) for all other properties. The PropertyNameDialog
window then displays the properties you would expect (that is, only intValue).
✓ The only properties that are displayed in the Dialog window for the selected target bean
are the properties with the same property type as the property selected for the source
bean. If no properties are found of this type, an error message is displayed indicating no
suitable properties that could be bound to were found.
Listener InterfacePropertyChangeListener
EventPropertyChangeEvent
Handler methodpropertyChange(PropertyChangeEvent evt)
Utility classPropertyChangeSupport
✓ The second box above indicates the listener interface, event type, and handler method
that are used when implementing a bound property. The utility class
PropertyChangeSupport provides an easy way to implement the listener interface and
fire the required event.
Constrained Properties
Overview
Changes to a constrained property Y result in notification to registered
VetoableChangeListeners. A listener validates the change and if the
change is not appropriate (not allowed), the listener throws a
PropertyVetoException.
The source bean is responsible for catching the exception and reverting
to the old value of the property.
The order in which things are done within the setXXX method for the
constrained property is important.
Constrained Properties
✓ Some of the engineers in JavaSoft believe that most constrained properties will also be
bound properties.
Handling Vetoes
If a registered listener vetoes a proposed property change by throwing
a PropertyVetoException, the source bean with the constrained
property is responsible for the following:
● Catching exceptions.
Constrained Properties
Registering Listeners
The typical code you would add to your bean definition to handle
registration of VetoableChangeListeners for your constrained
property is:
1 private VetoableChangeSupport vetoes
= new VetoableChangeSupport(this);
2
3 // Registration methods for VetoableChangeListeners
4 public void addVetoableChangeListener(VetoableChangeListener vl) {
5 vetoes.addVetoableChangeListener(vl);
6 }
7
8 public void removeVetoableChangeListener(VetoableChangeListener vl) {
9 vetoes.removeVetoableChangeListener(vl);
10 }
By Source or Listener?
What property changes should be validated by a bean itself and what
property changes should be validated by external listeners? It is not
efficient for a bean to register itself as a VetoableChangeListener to
check for negative values on the radius if it “knows” that negative
values are invalid (as with negative radius values). In these cases, the
bean itself (within the setRadius() method) checks for a negative
property value, and disallows the change (optionally throwing an
exception).
Listener InterfaceVetoableChangeListener
EventPropertyChangeEvent
Handler methodvetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException
Utility classVetoableChangeSupport
✓ What is described here for PropertySheets and views is specific to the BeanBox. Other
builder tools may use some other interface for displaying and modifying bean properties.
Property Editors
Note – Developers can create their own property editor. More details
on property editors and creating them is provided in Module 7,
‘‘Customization.”
The BoolEditor provided with the BDK uses this view. The
molecule demo in the BDK defines its own property editor
(MoleculeNameEditor.java) that also uses this view for
modifying the moleculeName property of the Molecule bean.
Example of Views
Figure 4-5 illustrates how the different views appear on the
PropertySheet window of the BeanBox. The properties displayed in
the PropertySheet window are for an OurButton bean and a
MoleculeBean.
PropertyCanvas
views
PropertyText
views Dialog window
Preparation
To be prepared for this exercise, you should have completed the
exercise on the event model because you will modify the code written
in that lab. If you did not have time to complete the event model
exercise, use the solutions provided in that exercise to finish your code
and move on to the tasks in this exercise.
Overview
Create a subclass of java.awt.scrollbar and make the "value" property
of this component a bound property. This will make a handy Slider
type component which can be used to input numeric values.
Tasks
1. Change to the $HOME/SL291files/work directory.
3. Create the methods and fields required for this class to have
bound properties. For example:
addPropertyChangeListener().
5. Execute jam.
% jam -sjf=slider.jam
Tasks (Continued)
8. Drop the Juggler bean into the BeanBox.
9. Select the Slider, and choose the Bind Property... menu item.
10. Slide the scrollbar back and forth to make the juggler go faster or
slower.
Tasks
▼ Add a read-write property for the cell size in the table. When
the cell size is changed, the table should be resized with the
new cell size (unless constrained is true, of course).
▼ Add methods for getting and setting the number of rows and
columns in the table.
Make the properties for the setting of the rows and columns
constrained properties. Use the VetoableChangeSupport class
for managing the VetoableChangeListeners.
Name: sl291/dataTable/DataTableVetoer.class
Java-Bean: True
DataTableVetoer Bean
A DataTableVetoer bean has been provided for you. This bean will
validate the values for the number of rows and columns. The number
of rows or columns cannot be less than one. In addition, a 1 x 1 table is
not allowed
Tasks
2. Restart the BeanBox or load the new JAR file into the BeanBox
using File ➤ Loadjar.
vetoableChange DataTableVetoer
DataTableBean
handles change events with
vetoableChange
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.
Before moving on to the next module, check that you are able to
accomplish or answer the following:
❑ What are the naming conventions used for bean properties and
why is this significant?
Course Map
This module discusses introspection—the process that is applied to a
JavaBeans component to discover its events, properties, and methods.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
5-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Relevance
✓ Present the following scenario to stimulate the students and get them thinking about the
issues and topics presented in this module.
Consider the following options, which do you think would work best?
Why? Any ideas how it all could work?
• This discussion should provide a transition to get students thinking about how a
builder tool can learn about the way a Bean’s properties, methods, and events can
interact with other Beans in the system. In other words, how introspection and
reflection work to make this all happen.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
Introspection 5-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introduction to Introspection
Introspection 5-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introduction to Introspection
A third issue, also addressed with the introduction of JDK 1.1, is the
lack of support for the examination and invocation of methods on a
class at runtime for which there was no compile-time information.
Introspection 5-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introduction to Introspection
Definitions
Reflection
Naming Conventions
Definitions
Introspection
BeanInfo
Introspection 5-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Even though reflection can fill out a BeanInfo quite thoroughly with
information, a Bean developer often wants to influence the set of
information obtained by reflection. Here are some common examples:
The Introspector
Introspection 5-11
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
✓ Here is a concise outline of the steps involved: When java.Beans.instantiate() loads a Bean, a
method named java.beans.Introspector.getBeanInfo() searches for classes whose names looks
like BeanNameBeanInfo. Such a class extends the SimpleBeanInfo class (which
implements the java.Beans.BeanInfo interface). Normally, getBeanInfo uses reflection to
determine all information about a Bean, but SimpleBeanInfo provides a set of accessor
methods the developer can override to affect the way a Bean’s properties, events, and
methods are used within a builder tool.
✓ The end of this module contains an overview of reflection. Even though getBeanInfo()
uses reflection to build its own internal BeanInfo so it can do things such as fill out
property sheets, Bean developers are removed from this. The need for Reflection API
utilities arises in subtle ways when a specific Bean requires intimate knowledge about a
class.
Introspection 5-13
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Automatic Analysis
Automatic analysis is a term used to describe the entire process of
introspection on a Bean. It includes the three key concepts: naming
conventions, BeanInfo, and reflection.
The next section covers the naming conventions that reflection uses to
determine what properties, events, and methods a Bean has. Once
these naming conventions have been covered, a discussion of what a
BeanInfo class can specify will make more sense.
Introspection 5-15
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Simple Properties
Simple properties are the most common properties used by
components. Mutable properties appear on a GUI element called a
property sheet as names next to fields that are of various object or
primitive types such as, String, int, Color, Float and the like. The
designer indicates properties that may be changed or customized by
creating methods of the form:
public PropertyType getPropertyName() { code }
public void setPropertyName(PropertyType a) { code }
Boolean Properties
Boolean properties are really a subset of simple properties since a
boolean is just another object type; however, it has a well-defined
function as a property. Since a Boolean property can only be true or
false, it makes sense to supply an alternate naming convention to the
get/set syntax.
For example, the method isOn() makes more sense than getOn()
when used in a conditional:
if ( ! lightBulbBean.isOn() )
lightBulbBean.setOn ( true );
✓ A note of caution; it is possible to have both a getPropertyName() and an
isPropertyName() method. Choose your method names wisely based on an
understanding of the naming conventions.
Introspection 5-17
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Indexed Properties
Sometimes it makes sense for a property to actually be an array of
properties or objects. Indexed properties enable the accessor to specify
an element of a property they want to read or write.
and
public PropertyElement[] getPropertyName() { code }
public void setPropertyName(PropertyElement[] element){ code }
Introspection 5-19
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
The majority of sources that can send events to one listener can also
send them to multiple listeners. For example, the Reset button event
could be sent to multiple Animator Beans if multiple add listener calls
were made with different animator objects.
resetButton.addResetButtonListener(anAnimator1)
resetButton.addResetButtonListener(anAnimator2)
resetButton.addResetButtonListener(anAnimator3)
Introspection 5-21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introspection 5-23
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
These public methods are identified and used for purposes such as
matching an event listener to an event source so that the appropriate
method is involved in firing the event.
Capitalization Rules
There are some miscellaneous rules that apply to capitalization for a
property name versus the accessor and mutator names. For instance,
public setForeground(Color c) indicates that there is a property
named foreground, not Foreground. For naming conventions applied
to properties and events that start with multiple capital letters such as
URLLocation, the decapitalize() method normally used within the
Introspector class does not result in changes. These conventions
result from strong reviewer input that JavaBeans should preserve the
style of beginning field names with lowercase letters.
Now that the topic of naming conventions for Bean development has
been covered, you should have a better idea of what kinds of methods
and classes a Bean should have. A computer is even better than a
human at following these kinds of rules. The JavaBeans API supplies a
convenient method, getBeanInfo(beanName), that builder tools and
other automated environments can use any time they want detailed
information about a Bean.
Figure 5-1 shows some of the packages, classes, and methods you will
examine to understand how automatic analysis occurs.
Introspection 5-25
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Beans.instantiate Method
This code loads the pie chart Bean using the class loader (potentially
from a JAR file, a local disk, or a remote URL). (You will get into
details about ClassLoader later in Module , “.”) This is the first
argument to the Beans.instantiate method.
Introspection 5-27
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
The need for serialized Bean support is evident if you consider that a
generic Chart Bean might contain customizable options which allows
it to become different types of charts—for instance, a bar chart, a line
chart, or a pie chart. In a builder tool, the Chart can be customized by
setting its type property to pie and saving the Bean to disk as a
serialized object. An application that calls
Beans.instantiate("beanco.chart.PieChart") can use the
PieChart Bean whether it was coded manually or whether it is,
instead, the customized state of a more generic Chart Bean.
As a special case, the Bean class file can also be an applet. Applet class
files resolve just like normal Beans, except that the instantiate
method activates some extra code to support a running applet, and
attempts are made to accumulate information that would ordinarily be
supplied in an HTML file’s APPLET tag as a CODE, CODEBASE, ARCHIVE,
or OBJECT attribute.
Introspector.getBeanInfo Method
Introspection 5-29
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introspector.getBeanInfo Method
Properties:
rowsintgetRows/setRows
cellSizeintgetCellSize/setCellSize
foregroundclass java.awt.ColorgetForeground/setForeground
backgroundclass java.awt.ColorgetBackground/setBackground
fontclass java.awt.FontgetFont/setFont
nameclass java.lang.StringgetName/setName
colsintgetCols/setCols
constrainedbooleangetConstrained/setConstrained
...
Event sets:
vetoableChangeaddVetoableChangeListener/removeVetoableChangeListener
vetoableChange
mouseaddMouseListener/removeMouseListener
mouseClicked
mousePressed
mouseReleased
mouseEntered
mouseExited
...
Introspection 5-31
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
SimpleBeanInfo Class
Method Description
Introspection 5-33
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
1 package sl291.circle;
2
3 import java.beans.*;
4
5 public class CircleBeanBeanInfo extends SimpleBeanInfo {
6 public PropertyDescriptor[] getPropertyDescriptors() {
7 try {
8 PropertyDescriptor props[] = {
9 new PropertyDescriptor("radius", CircleBean.class)};
10
11 props[0].setDisplayName("Radius of circle");
12 props[0].setBound(true);
13
14 return props;
15 } catch (IntrospectionException ex) {
16 ex.printStackTrace();
17 return super.getPropertyDescriptors();
18 }
19 }
20 }
21 }
Introspection 5-35
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introspection 5-37
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
A BeanInfo Class That Affects Properties
Using getAdditionalBeanInfo
Introspection 5-39
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Using getAdditionalBeanInfo
Introspection 5-41
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
How a Bean Is Analyzed
Now that you have studied three scenarios in which a BeanInfo file
was provided for a Bean to override various get methods, you will
examine a general example of a BeanInfo that defines
getEventSetDescriptors().
Introspection 5-43
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Details of How a BeanInfo Is Processed
Now the BeanBox (or builder tool) has “learned” that it can hook
adaptor Bean event sources for Foo events with Beans that implement
the FooListener interface.
You have already seen in Table 5-1 the set of methods that the
BeanInfo interface provides, but there are also many important
methods you will need to know about. For each method in Table 5-1
that returns a descriptor class, there is an additional table that
describes the accessor methods that return specific information about a
property, method, event, or another Bean.
Use Table 5-2, Table 5-3, Table 5-4, Table 5-5, and Table 5-6 as reference
material to help you decide when to create BeanInfo classes that
override and set certain types of information. There are matching
mutator methods for almost all of the following accessors, but in many
cases you will want to use the constructor for a descriptor class such as
PropertyDescriptor() since it can make assumptions and fill out a
lot of the default information.
Method Description
Introspection 5-45
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Method Description
Method Description
Introspection 5-47
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Available BeanInfo Methods
Method Description
Method Description
Method Description
isExpert() The “expert” flag is used to
distinguish between those
features that are intended for
expert users from those that are
intended for normal users.
isHidden() The “hidden” flag is used to
identify which features are
intended only for tool use, and
which should not be exposed to
humans.
setDisplayName(String) The localized display name for
the property/method/event.
setShortDescription(String) You can associate a short
descriptive string with a feature.
setValue(String, Object) Associate a named attribute with
this feature.
Introspection 5-49
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
● Saves you from the tedium of defining and maintaining a full set
of BeanInfo information for your class. Since the use of BeanInfo
is optional, you only use it when something would otherwise be
unclear or in the few cases reflection does not handle, such as
support for providing Bean icons.
Introspection 5-51
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
You might have noticed that only public method signatures have been
mentioned during the discussion of reflection. In fact, reflection works
on all types of methods, but the scope of methods that are visible is
restricted by the security manager (whether it is done within an applet
or within an application).
The BeanInfo class is provided as the ultimate control point for how
naming conventions are interpreted. It can be used to limit the number
of valid properties and events that are visible from outside the Bean,
or to provide additional information to the Introspector.
Introspection 5-53
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Additional Information on Introspection
Security
Security applies to introspection just as it applies to applets,
applications, packages, and classes in the Java programming language.
The security manager always has control, if that manager is in the Java
Virtual Machine of a browser, instantiated within the Applet Viewer,
or applied, in a very minimal case, in a locally run application.
Introspection 5-55
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Final Words on Introspection
Preparation
To be prepared for this exercise, you should have completed the
exercise on properties because you now will be adding a BeanInfo file
to the DataTableBean Bean. If you were not able to complete coding
the exercise on Bean properties, use the solutions provided for that lab
exercise to finish your code before beginning this exercise.
Introspection 5-57
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Exercise: Creating a BeanInfo File
Tasks
There are three short objectives in this exercise to help you become
more familiar with the structure of BeanInfo:
● Add display names for these properties that are more descriptive
than “color,” “background,” or “foreground.” (See table below.)
% jam -sjf=dataTable.jam
Introspection 5-59
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Exercise: Creating a BeanInfo File
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you find you do not have time to spend on discussion, then
just highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspect of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they have learned in this exercise to
situations back at their work place.
Before continuing on to the next module, check that you are able to do
the following:
Introspection 5-61
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Think Beyond
Many new concepts were briefly introduced in this module, and you
can practically chart the road map of the course from them. Here is a
sketch of upcoming modules which will put to use many of the
methods and classes that were discussed in the course of learning
about introspection:
Course Map
This module discusses the mechanisms for persisting the state of a
bean.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
6-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.
✓ Using the Object Serialization API, which is part of JDK 1.1, you can write out the state of
your bean to a serialized stream for later retrieval. Recall the File ➤ Save menu item
provided by the BeanBox. All of the beans on the BeanBox are written to a serialized file,
and then that file and the hookup classes are written to a JAR file (with the name you
specify in the Save dialog window).
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
✓ The April ‘97 release of the BDK added a new option to the File menu called Serialize
Component which enables you to write out to a serialized stream just a single component
in the BeanBox window and its internal state.
Persistence 6-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Bean Storage
Bean components will vary in complexity and use. They will range
from simple beans (that extend a Java AWT component) to more
complex beans that, for example, pretend to be a Microsoft Excel
document inside a Microsoft Word document. Moreover, not all beans
need to have persistent state. But any bean that allows its properties to
be modified should have a way of saving the changes and restoring
the bean with those changes.
The goals for bean storage are to provide not only the automatic Java
serialization mechanisms, but also an “externalization” stream
mechanism. In the latter case, a bean component will have full control
over how its state is written out to the serialized stream. In addition,
the externalization mechanism provides the capability of using
different data formats when writing to the stream.
Persistence 6-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Serializable Interface
To serialize objects, the JDK 1.1 provides an interface called
java.io.Serializable:
package java.io;
✓ Objects can be serialized by implementing the Externalizable interface, but this interface
is not covered in this course. Externalizable classes mean that the class is serializable,
but you must provide the methods for reading and writing objects; a default
implementation is not provided.
Persistence 6-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Persistence 6-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
java.io.DataOutput
ObjectOutput ObjectOutputStream
java.io.DataInput
ObjectInput ObjectInputStream
Legend
Class
Interface
Extends
Implements
Persistence 6-11
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
ObjectOutputStream Class
Writing Java objects, and a bean component in particular, to a
serialized stream is a simple process. The ObjectOutput interface is
implemented by the ObjectOutputStream class. You can use the
writeObject() method defined by the ObjectOutputStream class to
write out your bean.
The class of the object, the signature of the class, and the values of the
non-transient and non-static fields of the class and all of its supertypes
are written by the writeObject() method. The writeObject()
method throws both IOException and ClassNotFoundException.
Persistence 6-13
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
ObjectInputStream Class
Deserialization is re-creating an object that has been written out to a
serialized stream by reading the object back from the stream. The
ObjectInputStream class implements the ObjectInput interface and
defines a readObject() method that you can use to deserialize your
object. The readObject() method also throws both IOException and
ClassNotFoundException.
Persistence 6-15
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
3. Choose File > Serialize Component... and enter a file name, such
as GreenBean.ser.
6. Clear the BeanBox and load the new JAR file. A new type called
GreenBean should appear on the Toolbox . Drag a GreenBean
onto the BeanBox; it should appear just as you saved it.
Persistence 6-17
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
So you could write out your bean to a .ser file using the
writeObject() method, and instantiate the bean from the .ser file
using Beans.instantiate().
Using Beans.instantiate()
Using the serialized object from the GreenBean example, here is the
source code to instantiate a GreenBean using Beans.instantiate():
1 public static void main(String args[]) throws Exception {
2 Component c = (Component)Beans.instantiate(null,
"sl291.GreenBean");
3 Frame f = new Frame();
4 f.add(c, BorderLayout.CENTER);
5 f.setSize(200, 200);
6 f.show();
7 }
The null first argument instructs the method to use the default system
class loader. The second argument is the bean name.
Beans.instantiate() Methodology
The Beans.instantiate() method performs the following steps to
load a class and instantiate an object:
Persistence 6-19
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Recap of Persistence
Figure 6-2 summarizes the mechanisms used for persisting the state of
a bean through object serialization.
Tasks
Persistence 6-21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Exercise: Creating a New Bean Through Serialization
Tasks
9. Move your new jar file to the jars directory in the BDK
directory.
10. Launch the BeanBox and try out your new Benzene bean. Note
that it will now start out set to Benzene instead of
HyaluronicAcid.
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.
Persistence 6-23
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Persistence 6-25
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Customization 7
Course Map
This module discusses how to augment the customization facilities of
your bean within the context of an application builder tool.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
7-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
Customization 7-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Property Sheets
Some of the changes made to beans so far have been fairly small,
atomic ones on common types. Recall the PropertySheet window used
in the BeanBox. The PropertySheet provides a text field to change
integers and strings. In addition, it provides slightly more
sophisticated GUI components such as choice boxes for Booleans that
can only be true or false. Even more complicated properties such as
Color and Font have their own pop-up GUI dialogs that coordinate a
few different controls. Figure 7-1 illustrates examples of these
properties on the BeanBox PropertySheet window.
String
Dialog window
(pop-up GUI)
Font
Boolean
Customization 7-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Property Editors
In this module, you will learn how simple it is to provide editors for
properties with a limited range of choices (similar to the true and false
choices provided for Boolean properties). Moreover, you will learn
how types such as Font and Color can have custom property editors
attached to them. This will enable you to create editors for your own
common object or property types.
Customizers
You will learn how a bean can provide support for customization
“wizards” that enter into a dialog with a user, providing a set of top-
level choices that lead to unique branches up a tree of choices for
configuring a bean.
✓ Remind the students of the Customize option that appears on the Edit menu when a bean
has a customizer class associated with it.
Customization 7-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Property Sheets
A property sheet is a window that becomes visible for each bean that
is selected in a builder tool. The window consists of property name
and value pairs. A developer can visually manipulate each of a bean’s
public readable and writable properties through a PropertySheet
window.
Property Editors
When a property on a property sheet cannot be edited as a simple
textual string provided by the StringEditor property editor, you should
provide a custom property editor to handle modification of that
property’s type. In the BeanBox, a property editor is launched by
clicking on the property’s value.
Customization 7-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Review of Views
PropertyCanvas
views
PropertyText
views Dialog window
Customization 7-11
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
a. Supports isPaintable().
Method Description
Customization 7-13
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
There are actually two ways you can create your own property editor:
Customization 7-15
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
PropertyEditor Requirements
Supporting setValue()
PropertyEditor Requirements
Supporting setValue()
The setValue() method is used to modify a property of a bean. This
method must never modify the incoming object; instead, create a new
variable to reflect the modified version of the property. Cast the
incoming object argument (representing the property) to the
appropriate type (for example, cast to Color) and then set the variable
that represents the property to this value.
1 public class LabelEditor implements PropertyEditor {
2 String value;
3
4 public void setValue(Object value) {
5 value = (String)value;
6 }
Customization 7-17
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
PropertyEditor Requirements
Note – The code shown here is the same as the code you used when
creating a bound property for a bean.
Customization 7-19
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Sample PropertyEditor for a MultipleLine Label
35
36 // This method is intended for use when generating Java code to set
37 // the value of the property.
38 public String getJavaInitializationString() { return value; }
39
40 // Return the property value as a human editable string.
41 public String getAsText() { return value; }
42
43 // Set the property value by parsing a given String.
44 public void setAsText(String text) {
45 value = text;
46 }
47
48 // If the property value must be one of a set of known tagged
49 // values, then this method should return an array of the tags.
50 public String[] getTags() { return null; }
51
52 // A PropertyEditor may choose to make available a full custom
53 // Component that edits its property value.
54 public Component getCustomEditor() {
55 final TextArea labelArea = new TextArea(value);
56 labelArea.setSize(300, 150);
57 labelArea.addTextListener(new TextListener()
58 {
59 public void textValueChanged(TextEvent e) {
60 value = labelArea.getText();
61 listeners.firePropertyChange(null, null, null);
62 }
63 } );
64 return labelArea;
65 }
66
67 // Return true if the propertyEditor can provide a custom editor.
68 public boolean supportsCustomEditor() { return true; }
69
Customization 7-21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Notes
✓ This option implies that getCustomEditor() returns a GUI component for editing the value
and for firing PropertyChange events (which is indicated by a true result from
supportsCustomEditor()). This is appropriate for property types that need more than a
simple TextField for editing values.
Customization 7-23
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Display Style Requirements
1 package sun.beans.editors;
2
3 import java.beans.*;
4
5 public class StringEditor extends PropertyEditorSupport {
6
7 public String getJavaInitializationString() {
8 return "\"" + getValue() + "\"";
9 }
10
11 public void setAsText(String text) {
12 setValue(text);
13 }
14 }
Customization 7-25
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Customization 7-27
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Notes
Extending PropertyEditorSupport
When to Use
Use the utility class java.beans.PropertyEditorSupport when
your bean only needs to change a few methods defined by
PropertyEditorSupport,instead of defining all of the methods
required when implementing the PropertyEditor interface.
Customization 7-29
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Extending PropertyEditorSupport
2. Failing that, add “Editor” to the given Java data type and search
for the resulting dataTypeEditor. Packages are searched in the
following order:
Customization 7-31
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Making Your Property Editor Known
Naming Conventions
The name of your property editor should follow the naming
conventions of the JavaBeans API specification: dataTypeEditor.
However, if you have created an editor for a bean property with a data
type that already has an editor associated with it, such as String, then
you can name your editor after the property name. For example, the
MultiLineLabelBeanInfo uses the LabelEditor to change the
label property for the MultilineLabel bean. You must explicitly
register your editor using a BeanInfo file so that your editor will be
used for the property.
Note – Since it is difficult for you to know all of the editors that are
registered with the PropertyEditorManager, you might want to include
a BeanInfo file with your bean to explicitly register your property
editor as the one to use for a property of your bean.
Customization 7-33
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Making Your Property Editor Known
Figure 7-3 recaps what is necessary for creating your own property
editor.
Customization 7-35
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Property Editor
Preparation
To be prepared for this exercise, you should understand what methods
you need to define in a property editor to create a specific display style
on the PropertySheet window of the BeanBox.
✓ It is recommended that you stop the lecture at this point and have the students work on
creating their own property editor before moving on to customizers. Otherwise, students
become confused with what needs to be done in creating a property editor versus
creating a customizer.
Tasks
2. Create a JAR file for the Chart bean by typing the following
command:
% jam -sjf=chart.jam
3. Load the chart.jar file into the BeanBox using File ➤ Loadjar
or by restarting the BeanBox.
4. Create an instance of the Chart bean and become familiar with its
properties and how changing them affects the Chart bean.
Customization 7-37
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Property Editor
Tasks
2. Reload the JAR file into the BeanBox using File ➤ Loadjar or by
restarting the BeanBox.
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspect of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their work place.
Customization 7-39
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Notes
Customizers
Customizer Use
Customizers are used at design time, and often result in a bean that
can be saved in a serialized state to make a new bean. Use a
customizer when the configuration you want to do to a bean is
impossible with the property editor mechanism. For instance, a
customizer can easily display a graphical implementation of what can
be changed. So, for example, you could have a customizer that
displays a model of a car, enabling you to change the whole system
rather than wheel type, engine size, sport versus utility, and so on.
Customization 7-41
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Customizers
Characteristics of Customizers
The following characterize a customizer for a bean:
✓ This could mean that each change done affects the bean, and are backed out if the user
does something equivalent to a cancel on the customizer, it could mean that a new
version of the bean is customized and an apply applies it to the current in-design version,
or it could mean no changes occur until apply.
Naming Conventions
Your customizer should be named using the naming convention
BeanNameCustomizer. So, for example, a bean called Chart would
have a customizer called ChartCustomizer defined in
ChartCustomizer.java.
✓ This naming convention is not a requirement. In fact, there is no evidence that the
Introspector or a builder tool looks for this convention. The getCustomizer() method is
used to return the actual object.
Implementation Requirements
The following are required to implement a customizer for a bean:
Customization 7-43
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Defining BeanInfo
A bean with a customizer must have a BeanInfo file defined for it so
builder tools can locate the beans customizer class. The BeanInfo file
specifies the customizer class as shown in the following code:
1 import java.beans.*;
2
3 public class MyBeanBeanInfo extends SimpleBeanInfo() {
4 public BeanDescriptor getBeanDescriptor() {
5 return new BeanDescriptor(MyBean.class, MyBeanCustomizer.class);
6 }
7 }
Customization 7-45
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Defining setObject()
The setObject() method is called only once before your customizer
has been added to any parent AWT container. Within the
setObject() method, the argument passed to setObject() is cast to
the bean type and saved to a variable of the bean type (similar to what
is done in the setValue() method for property editors).
1 private MyBean bean;
2 public void setObject(Object beanToCustomize) {
3 bean = (MyBean) beanToCustomize;
4 // Code to get current properties for "bean" and/or
5 // Code to build GUI elements for customizer and add them to layout.
6 }
Customization 7-47
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Example of a Customizer
The BDK provides several beans that have customizers: JDBC SELECT,
BridgeTester, and OurButton beans. The code below is from the
OurButtonCustomizer class.
1 package sunw.demo.buttons;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.beans.*;
6
7 public class OurButtonCustomizer extends Panel
8 implements Customizer, KeyListener
9 {
10 public OurButtonCustomizer() {
11 setLayout(null);
12 }
13
14 public void setObject(Object obj) {
15 target = (OurButton) obj;
16
17 Label t1 = new Label("Caption:", Label.RIGHT);
18 add(t1);
19 t1.setBounds(10, 5, 60, 30);
20
21 labelField = new TextField(target.getLabel(), 20);
22 add(labelField);
23 labelField.setBounds(80, 5, 100, 30);
24
25 labelField.addKeyListener(this);
26 }
27
28 public Dimension getPreferredSize() {
29 return new Dimension(200, 40);
30 }
31
32 /**
33 * @deprecated provided for backward compatibility with old layout
34 * managers.
35 */
36 public Dimension preferredSize() {
37 return getPreferredSize();
38 }
39
Customization 7-49
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Recap of Customizers
Figure 7-4 recaps what is required for creating a customizer for a bean.
Preparation
To be prepared for this exercise, you should have completed the
exercise for writing the code for your ChartOrientationEditor. If
you did not have time to finish that exercise, use the solutions
provided for this module to complete your code before beginning this
lab exercise.
Customization 7-51
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Customizer
Tasks
Creating a Customizer
2. Add support for the customizer in the BeanInfo class for the
Chart bean.
2. Modify the chart type using your customizer and make changes
to the Chart bean using your existing orientation editor. See how
the customizer and property editor interact.
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspect of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their work place.
Customization 7-53
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
The next module on adaptors addresses some of the issues that can
occur when trying to handle events that an object has registered for.
For instance, if you register with several components that send
ActionEvents, how do you determine which component the
ActionEvent originated from? What about the case where an event
source has several interested objects that want tailored information
from the event sent by the source?
Customization 7-55
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Course Map
This module discusses event adapters—what they are and how they
can be used to add an event delivery policy between sources and
listeners.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
8-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.
✓ The code generated by builder tools is actually an adapter class. It sits between the
source of the event and the object interested in the event. It receives the event from the
source and forwards that event to the targeted method of the “listener” object. This code
is necessary because a builder tool does not know what Beans you plan to hook together
through events. The builder tool must dynamically generate this code to make the Beans
work together as one application.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
Event
source
Interested
object
Fires (“listener”)
XXXEvent
XXXEvent
Event
adapter
(implements
XXXListener
interface; does
decision-making)
When you connect two Beans in the BeanBox using the Edit ➤ Events
submenu, a hookup class is created in the beanbox/tmp/sun/beanbox
directory. Each hookup class is actually an event adapter. It
implements a listener interface and defines the handler method
specified by that interface.
args[0] = hookup;
esd.getAddListenerMethod().invoke(source, args);
where esd is an EventSetDescriptor object.
You might recognize some of the code shown here. This hookup class
was generated when the MyChoice Bean was chosen as the target of
the ActionEvent generated by the MyButton Bean. This adapter
implements the ActionListener interface and defines the required
handler method actionPerformed.
Types of Adapters
● Acting as a filter
Diagrams
Figure 8-2 gives a conceptual overview of how demultiplexing and
multiplexing adapters function.
Event
source1 Fire
event
Forward
Event Fire Demultiplexing event Interested
source2 event adapter or call object
specific
method
Event Fire
source3 event
Interested
Fire object
event
Fire
event Interested
object
What distinguishes an event adapter from the event listeners you are
familiar with from previous modules?
Application Window
Consider the many window applications you have used in the past.
Common buttons include Apply, Reset, Save Changes, Cancel, and
Quit. To illustrate a demultiplexing adapter, assume you are writing an
application that includes two buttons (Apply and Quit) and a List. The
application is shown in Figure 8-3.
Description of Application
There are three source files for this application: Appl.java,
Widgets.java, and ActionAdapter.java.
Appl.java Code
The code below is used in the main application.
1
2 // An application that creates a Frame with several widgets that
3 // each generate an ActionEvent
4 // The ActionEvent is fired to the ActionAdapter, which decides
5 // what widget the event originated, and calls an appropriate method
6
7 public class Appl {
8 public Widgets wid;
9
10 static public void main(String args[]) {
11 Appl app = new Appl();
12 app.wid = new Widgets(app);
13 }
14
15 public void apply() {
16 System.out.println("Do apply ...");
17 }
18
19 public void quit() {
20 System.out.println("Quitting...");
21 }
22
23 public void doFonts() {
24 System.out.println("put up Fonts dialog");
25 }
26
27 public void doColor() {
28 System.out.println("put up Color dialog");
29 }
30
31 public void doPatterns() {
32 System.out.println("put up Patterns dialog");
33 }
34 }
Widgets.java Code
The code below defines the button and list widgets for the application
and registers an adapter as the listener for each.
1 import java.awt.*;
2 import java.awt.event.*;
3
4 // Create the Widgets for this application
5 // and register the adapter as the listener for each
6
7 public class Widgets {
8 Button apply, quit;
9 List myList;
10
11 public Widgets(Appl app) {
12 Frame f = new Frame("My Widgets");
13 f.setLayout(new FlowLayout());
14 ActionAdapter adapt = new ActionAdapter(app);
15
16 //Build the widgets
17 apply = new Button("Apply");
18 quit = new Button("Quit");
19 myList = new List();
20 myList.add("Fonts");
21 myList.add("Color");
22 myList.add("Patterns");
23
24 f.add(apply);
25 f.add(quit);
26 f.add(myList);
27
28 // add adapter as listener for buttons, list
29 apply.addActionListener(adapt);
30 quit.addActionListener(adapt);
31 myList.addActionListener(adapt);
32
33 //put up Frame
34 f.pack();
35 f.setVisible(true);
36 }
37 }
ActionAdapter.java Code
Below is the code for the demultiplexing adapter which decides what
method should be called based on the information that it receives.
1 import java.awt.event.*;
2
3 // The demultiplexing adapter that receives ActionEvents from
4 // several sources, determines which type source sent the event
5 // and calls the appropriate method
6
7 public class ActionAdapter implements ActionListener {
8 private Appl app;
9
10 public ActionAdapter(Appl app) {
11 this.app = app;
12 }
13
14 public void actionPerformed(ActionEvent evt) {
15 Object x = evt.getSource();
16 if (x == app.wid.apply)
17 app.apply();
18 else if (x == app.wid.quit)
19 app.quit();
20 else if (x == app.wid.myList){
21 int index = app.wid.myList.getSelectedIndex();
22 if (index == 0)
23 app.doFonts();
24 else if (index == 1)
25 app.doColor();
26 else if (index == 2)
27 app.doPatterns();
28 else
29 return;
30 } else
31 // Unidentified source
32 System.out.println("Error: widget item not recognized");
33 }
34 }
✓ The course_examples directory for this module includes the code presented here in the
directory OneAdapter. There is also a directory called ManyAdapters which takes this same
code and modifies it slightly so that each widget registers its own particular adapter.
✓ Note that with the code used in the adapter, there is no tie to the actual string names on
the Widgets. Thus, the code in the adapter can be used even if the Widgets class changes
its strings for the component labels to strings in another language.
✓ You might describe for the students what the code would look like without the adapter and
what restraints or issues that might raise. For instance, without the adapter, the Widgets
class would have to determine where the ActionEvent originates by itself. The widgets are
no longer separated from the logic of the application.
Multiplexing Adapters
You are provided with an AdapterButton Bean that will generate and
fire the DataEvent events with test data to the multiplexing adapter
that you create.
Test button
fires DataEvent
to adapter YAxis
DataTableBean
Multiplexing
adapter generates
DataTableEvents and
fires it to XAxis
DataTableBeans DataTableBean
Table
DataTableBean
Preparation
This exercise builds on the work done in previous exercises with the
DataTableBean, DataTableEvent, and DataTableListener classes.
Be sure you have completed code from previous exercises for these
classes, or use the solutions provided in those exercises to finish your
code for use in this exercise.
✓ It might be helpful (and save time) to walk through all of the steps that describe what the
students are supposed to code to make sure they understand what they will be doing.
Tasks
AdapterButton
DataTableBean
(Table)
ent
Fires DataEvent
e Ev
abl
t aT
DataTableBean
Da
b leEvent (XAxis)
DataTa
DataEventMultiplexer
Data
Tabl
eEve DataTableBean
nt
(YAxis)
Tasks
▼ Defines get and set methods for each of the private data
members.
Tasks
Tasks
2. Use the jam command to create the JAR files for your new Beans.
▼ Make sure the third DataTableBean has more than one row
and more than one column.
Tasks
Tasks
XAxis
Main table
YAxis
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” You might find you do not have time to spend on discussion.
Then just highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Answer: The multiplexer is a source for DataTable, YAxis, and XAxis listeners, so it
defined the registration methods addXXXListener and removeXXXListener. The
introspection process found these add/remove methods for listeners and generated
the appropriate menu items.
Course Map
This module provides an overview of the role JavaBeans components
play in a distributed computing environment.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
9-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Relevance
JavaBeans components can be designed to act as intelligent front ends for network
servers by leveraging the network access mechanisms provided by JavaSoft (Java
DataBase Connectivity API (JDBC), Java Remote Method Invocation (Java RMI), and Java
IDL) or leveraging other distributed computing mechanisms.
✓ Note:
• The intent of this module is not to teach students how to write JDBC, RMI, or JavaIDL
applications (in fact, they will not be able to do so after taking this module), but rather
to show them how these JavaSoft distributed programming technologies can be used
with beans.
• For those students interested in learning how to program in these APIs, refer them to
the SL-301 course, Distributed Programming With Java.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
Areas of Familiarity
A developer who needs to be able to answer this question should have
some understanding of the following:
Workflow Applications
Application Servers
Agents
Beans themselves are individual pieces of code that can easily model
behavior and attributes of real objects. They are in a sense small
applications themselves that can travel as objects from location to
location to retrieve or update data. The agent can act as a container for
data and it can also intelligently operate on that data in ways
appropriate to the data. Part of this intelligent operation involves
locating and invoking certain beans available within the environment
depending on the data. You can imagine a generation of object-
oriented database systems in which hundreds or thousands of agents,
possibly beans themselves, are cached for retrieval, and then asked to
carry out certain tasks upon themselves in a uniform way so that the
client retrieving the object need not concern itself with the semantics of
how to operate on the object's data.
1. Orfali, Harkey, and Edwards. The Essential Distributed Objects Survival Guide. (John
Wiley & Sons, Inc. 1996).
Agents (Continued)
● JDBC API
● RMI API
Database Database
J protocol
server
JavaBeans D
component B
C
JavaBeans IIOP
CORBA
component
server
JavaBeans RMI
component
Java
Server
Application
makes calls to JDBC
JDBC driver
implements API for
specific database
Database
DriverManager
Driver Driver
Connection Connection
Connection Statement
ResultSet
ResultSet ResultSet
The BeanBox provides a JDBC bean called JDBC SELECT that contacts
a database at a specified JDBC URL and runs a SQL SELECT statement
to display specified columns from a target table.
The RMI API is a set of classes and interfaces designed to enable the
developer to make calls to remote objects that exist in the runtime of a
different Java Virtual Machine (JVM) invocation. This “remote” or
“server” JVM can be executing on the same machine or on an entirely
different machine from the RMI “client.”
Implementation
Class
Client Server
Application Object
Implementation
Method call
Method results
Note – The stub and skeleton classes are generated by the rmic
command using the implementation classes that were previously
compiled.
Note – Imaginary stock quotes are generated if you start a local RMI
quote server.
QuoteMonitor
RMI Bean
Server
application
✓ The idea for the RMI bean used in the exercise stems from this sample bean.
As a developer, you are responsible only for creating the Java RMI
interface definitions and implementation classes, and for generating
the stub and skeleton classes with rmic. The Remote Reference layer
and Transport layer implementations are taken care of for you.
Stubs Skeletons
Transport Transport
In the lab exercises, you will be asked to write the RMI client as a
JavaBeans component. This bean will replace the AdapterButton bean
used in the exercise that sent test data to the multiplexing adapter
bean. The remainder of the code for the RMI system (the RMI
interfaces, RMI implementation classes, and server) is provided for
you.
The RMI bean will communicate with the RMI server to request stock
data for a specific week.
Transport Layer
The Transport layer is responsible for setting up the connection,
managing the connection, and keeping track of and dispatching
remote objects (the targets of remote calls) residing in the transport’s
address space.
rmic Command
The rmic command creates stub and skeleton code from the interface
and implementation class definitions. The RMI interface and
implementation classes must be compiled before the rmic command is
executed. The rmic command is then run on the implementation
classes.
✓ The rmiCode.jam makefile, provided in the SL291files/work directory, invokes the Rmic
rule (see jambase). Rmic runs the rmic command.
rmiregistry Application
The rmiregistry is an application that provides a simple naming
lookup service. The server application provides rmiregistry with
the object reference and a String name through the rebind method
call.
Exercise Description
The DataServer application creates a set of objects that have data
associated with them. Each of these objects has a unique ID. The IDs
are displayed in a list by the DataClient bean. When a user selects an
item in the client list, the client requests the data from the server
associated with this ID. The client then creates a DataEvent event
using the data it received from the server and fires this event to the
multiplexing adapter bean.
Server
Client
DataFactory
Constructs
DataEvent Get data information Creates
from data
retrieved
from server Data
instance
DataClient.java DataServer.java
DataFactory.java DataFactoryImpl.java
(interface)
Data DataImpl.java
Data.java
(interface) instance
✓ It might be beneficial to review on the whiteboard the definition of the DataEvent object
because the RMI code described on the following pages was written based on this event
object. The DataEvent object was created in Module 8; recall that the DataEvent object
• Defines get and set methods for each of the private data members.
Interfaces
There are two interface classes used in the RMI exercise, Data and
DataFactory.
Note – The RMI API defines many exception types that your code
must be written to handle. Make note of the exceptions and exception
handling that are used in the RMI exercise code that is discussed in the
next several pages.
Data.java File
Interfaces (Continued)
DataFactory.java File
Implementation Classes
DataImpl.java File
1 package sl291.rmilab;
2
3 import java.rmi.*;
4 import java.rmi.server.*;
5 import java.awt.Dimension;
6
7 public class DataImpl extends UnicastRemoteObject implements Data{
8
9 private String id, xLabel, yLabel;
10 private String [] xAxis, yAxis;
11 private String [][] dataValues;
12 private Dimension size;
13
14 public DataImpl(String id, String xLabel, String yLabel)
15 throws RemoteException {
16
17 this.id = id;
18 this.xLabel = xLabel;
19 this.yLabel = yLabel;
20 this.size = new Dimension (8,5);
21 xAxis = new String [size.height];
22 yAxis = new String [size.width];
23 dataValues = new String [yAxis.length] [xAxis.length];
24 }
25
26 public String getID() throws RemoteException {
27 return id;
28 }
Implementation Classes
29 public String getXLabel() throws RemoteException {
30 return xLabel;
31 }
32
33 public String getYLabel() throws RemoteException {
34 return yLabel;
35 }
36
37 public String [] getXAxis() throws RemoteException {
38 return xAxis;
39 }
40
41 public String [] getYAxis() throws RemoteException {
42 return yAxis;
43 }
44
45 public Dimension getSize() throws RemoteException {
46 return size;
47 }
48
49 public String [] [] getDataValues() throws RemoteException {
50 return dataValues;
51 }
52
53 public void setXAxis(String [] sa1) {
54 xAxis = sa1;
55 }
56
57 public void setYAxis(String [] sa2) {
58 yAxis = sa2;
59 }
60
61 public void setSize(int width, int height) {
62 size = new Dimension(width, height);
63 }
64
65 public void setDataValues(String [] [] sa3) {
66 dataValues = sa3;
67 }
68 }
Implementation Classes
DataFactoryImpl.java File
Implementation Classes
CORBA/JavaIDL (Optional)
Preparation
To be prepared for this exercise, you should have completed the code
from the exercise on adapters: the DataEventMultiplexer,
DataEvent, and DataEventListener classes should be written. You
will need these classes to test the DataClient bean you will write in
this exercise. If you did not finish the adapter exercise code, use the
solutions provided with the adapter module to complete your code
before beginning this exercise.
✓ If the rmiregistry is started and the JDK class files are not included in CLASSPATH, there is
a binding problem with the server and error messages are generated when you start the
RMI server. In addition, you cannot instantiate the DataClient bean in the BeanBox.
✓ The DataClient is created as a unicast source for the same reasons as the AdapterButton
bean supplied in the multiplexing adapter lab.
Tasks
Note – Remember that when writing your DataClient bean, you must
catch exceptions that might occur when you make a request from the
server or do a name lookup in the RMI registry. Also, import
java.rmi.*.
▼ Is a List component
(DataFactory)Naming.lookup("//localhost/dataServer"
)
Tasks
% jam -sjf=rmiCode.jam
Tasks
DataClient
DataTableBean
(Table)
ent
Fires DataEvent
Ev
b le
Ta
ta DataTableBean
Da
nt (XAxis)
DataT ableEve
DataEventMultiplexer
Data
Tabl
eEve DataTableBean
nt
(YAxis)
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
❑ Draw a diagram that illustrates the main concepts of the Java RMI
architecture.
❑ How would you implement a Java RMI bean for a given RMI
application?
You have been running and testing bean components using the
BeanBox. The BeanBox is not considered an application builder tool.
Without such a tool, how do you use your beans and build an
application that runs outside of the BeanBox?
Course Map
In this module, you will write the code necessary to utilize beans in
applets or applications.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
10-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Relevance
✓ Present the following question to stimulate the students and get them thinking about the
issues and topics presented in this module.
✓ The BeanBox builds adapters that connect your beans to one another. This Java source is
built automatically and compiled when events are connected to targets.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
Sample Code
Subclassing a Bean
In the code fragments below that compose the BeanInfo file for the
ExplicitButton bean, the following items are addressed:
Adding Icons
The visible events for the bean are limited to the “button was pushed”
event (indicated by the actionPerformed method) and the “property
was changed” event (indicated by the propertyChanged method).
1 public EventSetDescriptor[] getEventSetDescriptors() {
2 try {
3
4 EventSetDescriptor push = new EventSetDescriptor(beanClass,
5 "actionPerformed", java.awt.event.ActionListener.class,
6 "actionPerformed");
7
8 EventSetDescriptor changed = new EventSetDescriptor(beanClass,
9 "propertyChange", java.beans.PropertyChangeListener.class,
10 "propertyChange";
11
12 push.setDisplayName("button push");
13
14 changed.setDisplayName("bound property change");
15
16 return EventSetDescriptor[] rv = { push, changed};
17
18 } catch (IntrospectionException e) {
19 throw new Error(e.toString());
20 }
21 }
Note – The composite bean is responsible for making sure all beans are
read and written properly, and for restoring connections between
beans in the event that a composite bean is loaded from a persisted
state.
The following application instantiates a bean from the .ser file that
was created previously:
1 import java.awt.Frame;
2 import java.awt.Component;
3 import java.beans.Beans;
4 import java.io.*;
5
6 // Read the serialized file and display the bean
7 public class BeanUnSer extends Frame {
8 private static Component myBean;
9 public BeanUnSer(String beanSerFile) {
10 super("Unserialized from: "+beanSerFile);
11 try {
12 myBean = (Component) Beans.instantiate(null,beanSerFile);
13 } catch ( Exception e) {
14 System.out.println("Error unserializing bean " +
15 beanSerFile+ ": "+e);
16 }
17 this.add(myBean);
18 this.setSize(300,300);
19 this.show();
20 }
21
22 public static void main (String args[]) {
23 BeanUnSer m = new BeanUnSer(args[0]);
24 }
25 }
The following steps are involved with using a builder tool to create
applets or applications that use beans:
2. Lay out the applet, dragging JDK classes and bean components
from the toolbar onto the GUI surface.
Coding Programmatically
✓ Refer students to Section 3.2 of the beans specification 1.0a for a detailed scenario.
The same steps that are used with a builder tool apply to coding by
hand, except an entire applet or application must be written including
all the adapter classes that make addXXXListener calls between
event listeners and event sources, all the Beans.instantiate method
calls, and so forth. See the example on page 43 for details.
Scripting
A scripting language works at an extremely high level. Script
commands provide high-level, generic but practical functionality that
would normally take hundreds of lines of code to develop.
Note – You saw earlier that an applet can be built from beans, but an
applet can also be a bean.
The following issues can arise with applets that are beans or that are
composed of beans:
JAR files were described briefly in Module 2. This module will take an
advanced look at how they fit into the larger scheme of how beans are
used.
Classes that represent beans still could be made available this way, but
the practice is discouraged, not specifically supported, and sacrifices
many of the advantages JAR files provide.
● JARs can be loaded into your builder tool (as you saw with the
BeanBox).
● JARs can be used in HTML files with the OBJECT or APPLET tags as
an alternate source besides CODEBASE or local CLASSPATH (more
on this later).
Here are some sample entries for the MANIFEST portion of a JAR file.
Notice that not all classes are beans.
Name: sl291.dataTable.DataTableBean.class
Java-Bean: True
Name: sl291.dataTable.DataTableBeanBeanInfo.class
Java-Bean: False
Name: sl291.dataEvent.DataEventMultiplexor.class
Java-Bean: True
APPLET Tag
Note – The above OBJECT is the OBJECT attribute of the APPLET tag,
not the OBJECT tag discussed on page 22.
● Know the restriction about which properties are restored when the
applet is loaded from a serialized state.
Note – A recent JDK change makes all applets on a page use the same
class loader.
✓ Is this true even if the applets are loaded from entirely different servers?
OBJECT Tag
The OBJECT tag is a proposed extension beyond HTML 3.2 that was
introduced as a generic way to identify a range of object types. The
OBJECT tag contains several attributes that are not part of the APPLET
tag.
● DATA – The URL for the object’s data; for example, a bean class
object.
● TYPE – Specifies the Internet Media (Mime) type for the data
referenced by the DATA parameter.
<OBJECT
WIDTH=300 HEIGHT=100
CODETYPE="juggler.jar"
NAME="FastJuggler"
TYPE="application/x-java-serialized-object"
DATA="sunw/demo/juggler/FastJuggler.ser"
>
</OBJECT>
✓ Note that JDK 1.1 datatransfer.DataFlavor used the wrong MIME type for serialized
objects. It used application/x-javaserializedobject. Other valid types as of JDK 1.1
include application/java-vm, application/x-java-vm and application/x-java-archive.
Definition
A digital signature is the result of an algorithmic computation on data
using a private key.
● Unique subject name – Identifies the subject of the data signed and
the entity who signed it.
Private key
Certificate
● Signed code, leveraging the JDK 1.1 digital signature support and
signed JAR files
● Internet communication
● Digital signatures
● Message hashing
● Java Security at
http://java.sun.com/security/codesign/index.html
Coding Possibilities
There are several cases for writing code to load and instantiate a bean.
These involve loading and instantiating a bean within various
contexts:
● From within a Java applet off a server using the applet’s class
loader
▼ The class loader for the bean class or, if this is null, the System
class loader
The following code shows how to load and instantiate a bean from
within an application. The class loader used is either the class loader
associated with the bean class, or, if this is null, the System class
loader.
1 import myorg.mypkg.MyBean;
2 ...
3 ClassLoader cl = Class.forName("myorg.mypkg.MyBean").getClassLoader();
4 myBean = (MyBean) Beans.instantiate(cl, "myorg.mypkg.MyBean");
The code below illustrates how to use a JAR file to load and instantiate
a bean. The JarLoader class is defined as part of the BeanBox code.
1 import sun.beanbox;
2 ...
3 JarLoader jl = new JarLoader(jarFileName);
4 ClassLoader cl = jl.getLoader();
5 JarInfo ji = jl.loadJar();
6 Component myBean = (Component)
7 Beans.instantiate(cl,beanClassName);
✓ try and catch statements were left out intentionally for simplicity.
✓ The JarLoader class is not part of the JDK—it is part of the source code for the BeanBox.
See JarLoader.java in the beanbox/sun/beanbox directory of the BDK. The licensing of the
BeanBox code is very open.
Now the class loader object, cl, can be passed in as the first argument
of Beans.instantiate().
✓ At some point in development, beans developers realize that the class loader almost
always returns null. It is a crime to pass null into Beans.instantiate because at a future
date the core classes may no longer return null. When the class loader is the JarLoader
from the BeanBox, for example, the class loader is the only means of obtaining a resource
such as a bean or an image from within a JAR file.
✓ The following functionality has been added to the Class class in JDK 1.1:
• Finds a resource given its name and returns a URL for it. See getContent for
information on pulling an ImageProducer, AudioClip, or InputStream from the URL.
• After obtaining the resource using getResource, open an input stream to it.
What Is It?
The Applet Viewer has a built-in class loader that knows how to use
the APPLET, CODE, CODEBASE, and other HTML tags, attributes, and
parameters to load beans from JAR files or remote URLs.
The BeanBox has built-in utilities that include a class loader for beans
that exist in JAR files. The JDK 1.1.1 does not know how to load beans
directly from JAR files. This may change in the future.
✓ Several methods have been added to the ClassLoader class in JDK 1.1.
• The following methods for ClassLoader work like the Class versions:
• The methods below restrict the resources that can be loaded down to those present on
the system (local CLASSPATH, for example).
<APPLET
ARCHIVE="file:/home/BDK/jars/twoSimple.jar"
CODE="sl291.twoSimpleBeans.LabelChanger"
WIDTH=300
HEIGHT=100
></APPLET>
Here is the source code for the LabelChanger applet referenced in the
HTML code above. This applet (built manually) connects the MyText
and MyButton beans from Module 3 and displays them.
1 package sl291.twoSimpleBeans;
2
3 import java.awt.Frame;
4 import java.awt.BorderLayout;
5 import java.applet.Applet;
6 import java.beans.*;
7 import java.io.*;
8
9 public class LabelChanger extends Applet {
10 public void init() {
11 MyButton myButton = null;
12 MyText myText = null;
13 try {
14 ClassLoader cl = this.getClass().getClassLoader();
15 myText = (MyText) Beans.instantiate(cl,
16 "sl291.twoSimpleBeans.MyText");
17 myButton = (MyButton) Beans.instantiate(cl,
18 "sl291.twoSimpleBeans.MyButton");
19 } catch (Exception e) {
20 throw new Error(e.toString());
21 }
✓ Note that the code shown here can be run as an application or as an applet.
Sample Code
JarLoader Example
Below is a generic JAR testing application that shows how the JAR
loader can be used. See the comments for usage instructions.
1 import java.awt.*;
2 import java.beans.*;
3 import java.io.*;
4 import sun.beanbox.*;
5
6 /**
7 * Usage: java JarBeanTest beanName jarFileName
8 * Where beanName is a fully qualified class like
9 * “sunw.demo.jelly.JellyBean”, or it is a serialized file named like:
10 * “serFiles.redJellyBean” for serFiles/redJellyBean.ser or
11 * often “sunw.demo.jelly.JellyBean” for sunw/demo/jelly/JellyBean.ser
12 * if the JAR package includes one.
13 *
14 * Note: This test program was written to test pulling stuff out of a
15 * JAR file, but it is important to note that because it’s an
application
16 * anything within CLASSPATH will be found too. If the program were
17 * modified so jar files were optional then it could be made to look
18 * exclusively at local and system files.
19 *
20 * Note also that this is very much an academic exercise because the
21 * AppletLoader already understands JARs with ARCHIVE tag and
serialized
22 * objects with OBJECT tag. The BeanWrapper with BDK uses AppletLoader
23 */
24 public class JarBeanTest extends Frame {
25 JarLoader jl;
26 JarInfo ji;
27
28 public Component loadBeanFromJar(String beanClassName,
29 String jarFileName) {
30
31 try {
32 jl = new JarLoader(jarFileName);
33 if (jl == null) {
JarLoader Example
43 ClassLoader cl = jl.getLoader();
44 // Ok, loaded all the classes -- now, instantiate *the requested
one*
45
46 ji = jl.loadJar();
47
48 try {
49 // We can either get an instance of one of the entities in
the archive
50 // (not the right thing to do for a bean but interesting)
51 //return (Component) ji.getInstance(beanClassName);
52
53 // Or we can instantiate a specific bean from the archive
54 // This should work for both ser and class versions of a bean
55 return (Component) Beans.instantiate(cl,beanClassName);
56
57 } catch (Exception e) {
58 System.err.println("Error instantiating "+beanClassName);
59 e.printStackTrace();
60 return null;
61 }
62 }
63
64 public static void main (String args[]) {
65 JarBeanTest me = new JarBeanTest();
66
67 Component myBean = me.loadBeanFromJar(
68 args[0], // bean class name
69 args[1]); // jar file name
70
71 me.add(myBean);
72 me.pack();
73 me.setVisible(true);
74 }
75 }
What code did the BeanBox need to generate? When you hook beans
together, you must write code similar to that generated by the
BeanBox.
3. The beans that visually display (all beans but invisible ones)
must be registered with the layout manager so they will be
visible.
1 setLayout(new BorderLayout());
2 add("Center", myText);
3 add("South", myButton);
Preparation
To be prepared for this exercise, you should have completed the
DataClient, DataEventMultiplexer, and DataTableBean beans from
previous lab exercises. If any of the code for these beans is incomplete,
use the solutions from the appropriate lab directories to complete your
beans.
Tasks
% jam -sjf=browser.jam
Tasks
Note – You can specify more than one JAR file with the ARCHIVE tag
by using a comma-separated list of JAR files, enclosed in double
quotes: ARCHIVE="../jars/first.jar,../jars/second.jar".
Tasks
Tasks
Here you will use the BeanBox to create .ser files of the three
different types of DataTableBeans and then use the .ser files in your
applet to instantiate these beans.
Tasks
9. Modify tableBrowser.jam:
Tasks
% jam -sjf=browser.jam
Tasks
Note – The solution to this exercise currently does not implement the
JAR loader used in the JarBeanTest application.
Tasks
4. Verify that your application can select and display weeks of stock
just like the applet did.
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” You might find you do not have time to spend on discussion.
Then just highlight the key concepts students should have learned from the lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
You have seen in this module how beans are built, how they are
assembled into applets and applications, and how they are delivered.
You have seen the specific connecting code that is required to glue
these beans together.
Builder tools were mentioned and how they can off-load some of the
tedious coding required was described briefly.
In the next module, you will see a broader display of the sort of tools
that are becoming available to enable the use of beans in the business
environment. You will also get a preview of what current and future
advances will make beans even easier to use and even more attractive
as part of your enterprise solutions.
Course Map
Application developers are more productive working in environments
that provide them with the programming tools and mechanisms
necessary to build, test, debug, and modify code. This module reviews
component-based software and discusses the programming
environments available for JavaBeans component development.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
11-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Relevance
✓ The BeanBox provided with the BDK is not a true development environment—it is not
intended as such. You cannot generate the code for an applet, application, or another
Bean component within the BeanBox. The BeanBox is meant only as a testing
environment and as a reference base. A true development environment would provide
mechanisms for choosing whether you are building an applet, application, or Bean
component, providing visual tools to aid in this endeavor, generating source code for you,
possibly providing mechanisms for you to edit or add source code, providing the means
to test and debug what you are building, and then delivering the final, functioning
product—your Bean, applet, or application.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
The phrase “write once, run anywhere”SM is associated with the Java
programming language since this language is a platform-independent,
object-oriented programming environment. With the JavaBeans API
packaged as part of the Java Platform, a component model is added to
the Java environment. JavaBeans components integrate into a variety
of containers, as well as being used as independent Java applets and
applications. They are portable and highly reusable in the broadest
number of containers and environments. Hence, the “write once, run
anywhere” Java phrase has become “write once, run anywhere, reuse
everywhere” for JavaBeans components.
In addition, with the coming of the Java Platform for the Enterprise,
president of JavaSoft, Alan Baratz, noted at JavaOne Developer
Conference in April, 1997 that the Java technology is extending to
enterprise infrastructures. This initiative includes Enterprise JavaBeans
and services that will make it far easier to do enterprise-wide Java
applications.
✓ For more information regarding the Enterprise Java initiative, see http://www.javasoft
.com/features/1997/april/enterprise.html.
Business Influences
The corporate computing environment is changing, influenced by the
competitive and economic pressures of the marketplace.
Heterogeneous intranets and Internet connectivity are becoming
realities for many companies. Companies are seeking to reduce costs
and create applications that are easily portable to the different
platforms on their intranets/Internets. Applications that are platform
independent are becoming a requirement.
Major Elements
A component model consists of three major elements:
Review of Services
Recall that all component-based software models and their APIs must
provide five basic services:
● Event handling
● Persistence
● Layout control
● Internet Explorer
● Netscape Navigator
● HotJava
● Visual Basic
● Word
● ClarisWorks
ActiveX Bridge
The ActiveX bridge, which is available for download from JavaSoft,
provides users of legacy OLE/COM/ActiveX containers (Word or
Visual Basic, for example) with the ability to embed and use portable
JavaBeans components as if they were platform-specific
OLE/COM/ActiveX components.
✓ For more details on the ActiveX bridge, see http://splash.javasoft.com/beans/bridge/.
InfoBus Technology
✓ Sun is also considering a proposal for an Object Aggregation/Delegation Model for future
releases of the Java programming language and JavaBeans. The draft specifications can
be found at http://splash.javasoft.com/beans/glasgow.html.
Development Environments
One expects the modern day IDE to let a developer follow a project
build through a compile phase in which errors are output, through a
maintenance phase in which the developer can click on the “hot” text
of the errors to bring the trouble-spot into the editor, and on a more
intense debugging phase in which the developer steps through code
observing the program's operation to watch for problems.
Examples
The following products have been announced as visual builder tools
that support the JavaBeans component model. Many of these tools are
advertised as RAD tools or environments. For specific information
about any of these tools, refer to the URL listed under "References" on
page -3.
Examples (Continued)
● Mojo from Penumbra Software
Examples (Continued)
● JBuilder from Borland
Examples (Continued)
The tools mentioned here were some of the first tools described on the
JavaSoft Web site. Additional tools now include the following:
Before continuing on to the next module, check that you are able to
answer the following:
Course Map
Until browsers and other applications support JDK 1.1, you need to
write transitional Beans for use in these applications.
Introduction to JavaBeans
Persistence Customization
Optional
Transitional Beans
12-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.
References
Additional resources – The following references can provide
additional details on the topics discussed in this module:
Marker Classes
The JavaBeans API (and JDK 1.1) uses certain classes or interfaces to
determine that a given class is intended to perform a given role. These
classes or interfaces are referred to as marker classes, and currently
include java.io.Serializable, java.util.EventListener, and
java.util.EventObject. To enable transitional beans to make use of
these markers for events and serialization, three transitional marker
classes are provided for transitional beans developers:
sunw.util.EventObject, sunw.util.EventListener, and
sunw.io.Serializable.
Example
Developer Rules
If you, as a bean developer, want your transitional beans to work
correctly under JDK 1.1, you need to adhere to the following rules for
creating transitional beans:
✓ Whomever receives your JAR file must be able to extract the classes (jar xvf
jarFileName) or use the JAR file directly in their application.
✓ A zip file can be created using the zip command (a free software utility). The zip file must
be created without using compression. On a UNIX platform, this implies using the -0
option.
● The bean must use the getFoo() and setFoo() patterns for
properties, as defined in the JavaBeans 1.0 specification.
✓ The HotJava 1.0 beta browser, however, is able to run applets from an HTML file that uses
a JAR or zip file as the value of the ARCHIVE parameter.
Sample Description
Figure 12-1 shows an applet running in the Netscape Navigator 3.01
browser. The applet contains two simple transitional beans: a button
bean and a jellybean bean. The button fires a pushButtonEvent when
clicked, which causes the jellybean to change its color from green to
blue.
✓ The 3.01 version of the Netscape Navigator browser supports JDK 1.0.2. This applet also
runs in the HotJava 1.0 beta browser, which supports JDK 1.1.
ButtonPushEvent Class
The ButtonPushEvent class extends the marker class
sunw.util.EventObject to comply with event objects under JDK 1.1.
The following code creates a new event type:
1 package demo;
2
3 /**
4 * JDK1.1 Event Model
5 * This class describes the event that gets generated when
6 * OurButton gets pushed.
7 */
8
9 public class ButtonPushEvent extends sunw.util.EventObject {
10 public ButtonPushEvent(java.awt.Component source) {
11 super(source);
12 }
13 }
Listener Interface
The following interface extends the marker class
sunw.util.EventListener for compliance with the new JDK 1.1
event model for sources and listeners.
OurButton Class
In JDK 1.1, buttons are already defined as a source of an ActionEvent
event object. For beans in JDK 1.0.2, you must indicate that your
button is a source for ButtonPushListener that you defined on page
12. This means you define addButtonPushListener() and
removeButtonPushListener() methods for listeners to use.
1 package demo;
2
3 /**
4 * The OurButton class is a very minimal Bean that simply extends the
5 * standard JDK 1.0.2 Button class to throw a Bean event.
6 */
7
8 import java.util.Vector;
9 import java.awt.*;
10
11 public class OurButton extends java.awt.Button implements
12 sunw.io.Serializable {
13 private boolean dbg;
14 private Vector listeners = new Vector();
15
16 public OurButton() {
17 this("press");
18 }
19
20 public OurButton(String label) {
21 super(label);
22 }
23
24 // Register an Event Listener.
25 public synchronized void addButtonPushListener(ButtonPushListener
26 bl) {
27 listeners.addElement(bl);
28 }
29 // Remove an Event Listener.
30 public synchronized void removeButtonPushListener(ButtonPushListener
31 bl) {
32 listeners.removeElement(bl);
33 }
JellyBean Class
Below is the code for the JellyBean bean. It does not generate any
events; that is, it is not a source, so it does not require the event
mechanisms implemented in the OurButton class.
1 package demo;
2 /**
3 * A very simple example Bean.
4 *
5 * We have a screen appearance that is a color oval, and we have one
6 * property "color".
7 */
8
9 import java.awt.*;
10
11 public class JellyBean extends Canvas implements
12 sunw.io.Serializable {
13
14 public JellyBean() {
15 resize(60,40);
16 }
17
18 public void paint(Graphics g) {
19 g.setColor(ourColor);
20 g.fillArc(5, 5, 30, 30, 0, 360);
21 g.fillArc(25, 5, 30, 30, 0, 360);
22 g.fillRect(20, 5, 20, 30);
23 }
24
25 public Color getColor() {
26 return ourColor;
27 }
28
29 public void setColor(Color newColor) {
30 ourColor = newColor;
31 repaint();
32 }
33
34 private Color ourColor = Color.orange;
35 }
Flipper Applet
In the code below, an applet is defined as a listener for the button (it
implements ButtonPushListener interface).
✓ Remind students that implementing the ButtonPushListener interface implies that the
applet will define the push() method to handle a ButtonPushEvent.
1 package demo;
2
3 /**
4 * A very simple demo applet that uses the "OurButton" Bean
5 * and the "JellyBean" Bean.
6 *
7 * We catch "ButtonPush" events from the button and then change the
8 * color on the target JellyBean.
9 */
10
11 import java.awt.Color;
12
13 public class Flipper extends java.applet.Applet implements
14 ButtonPushListener {
15
16 public void init() {
17
18 // We do our own hand layout.
19 setLayout(null);
20
21 // Create a JellyBean.
22 jb = new JellyBean();
23 jb.setColor(firstColor);
24 add(jb);
25 jb.reshape(250, 25, 100, 40);
26
27 // Create a button.
28 btn = new OurButton();
29 btn.setLabel("flip");
30 add(btn);
31 btn.reshape(100, 30, 100, 30);
32
✓ Note that although the JavaBeans 1.0 specification recommends that you use
Beans.instantiate() to create a Bean; this is not possible under 1.0.2 since
Beans.instantiate() does not exist.
Things to Remember
When you create JDK 1.0.2 beans using JDK 1.0.2 AWT components,
you need to do the following:
● Define a JDK 1.1 compliant event X that the JDK 1.0.2 component
will generate.
● Catch the usual JDK 1.0.2 events for your AWT component and
generate event X.
● Notify all your listeners of the event X. This means that for all
listeners, you will call method Z.
References
Additional resources – The contents of this appendix were obtained
from the Web page “How to Convert Programs to the 1.1 AWT API.”
[Online]. Available: http://www.javasoft.com/products/JDK/
1.1/docs/guide/awt/HowToUpgrade.html.
A-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
A
Event Handling
When upgrading to the 1.1 release, the simplest way to convert event-
handling code is to leave it in the same class, and make it a listener for
that type of event.
The biggest part of converting most 1.0 AWT-using programs to the 1.1
API is converting the event-handling code. The process can be
straightforward, once you figure out which events a program handles
and which components generate the events. Searching for “Event” in a
source file lets you find the event-handling code.
Note – While you are looking at the code you should note whether
any classes exist solely for the purpose of handling events; you might
be able to eliminate such classes.
Table A-1 can be used in the conversion process to help map 1.0 events
and methods to their 1.1 counterparts.
● The first column lists each 1.0 event type, along with the name of
the method (if any) that is specific to the event.
● The second column lists the 1.0 components that can generate the
event type.
● The third column lists the listener interface that helps you handle
the 1.1 equivalents of the listed events.
1.0.x 1.1
Checkbox
CheckboxMenuItem ItemListener itemStateChanged(ItemEvent)
Choice
WINDOW_DESTROY windowClosing(WindowEvent)
WINDOW_EXPOSE Dialog WindowListener windowOpened(WindowEvent)
WINDOW_ICONIFY Frame windowIconified(WindowEvent)
WINDOW_DEICONIFY windowDeiconified(WindowEvent)
windowClosed(WindowEvent)*a
windowActivated(WindowEvent)*
windowDeactivated(WindowEvent)*
componentMoved(ComponentEvent)
WINDOW_MOVED Dialog ComponentListener ComponentHidden(ComponentEvent)*
Frame componentResized(ComponentEvent)*
componentShown(ComponentEvent)*
SCROLL_LINE_UP
SCROLL_LINE_DOWN AdjustmentListener
SCROLL_PAGE_UP (Or use the new ScrollPane adjustmentValueChanged(AdjustmentEvent)
SCROLL_PAGE_DOWN Scrollbar class)
SCROLL_ABSOLUTE
SCROLL_BEGIN
SCROLL_END
1.0.x 1.1
Canvas
MOUSE_DRAG/mouseDrag Dialog mouseDragged(MouseEvent)
MOUSE_MOVE/mouseMove Frame MouseMotionListener mouseMoved(MouseEvent)
Panel
Window
KEY_PRESS/keyDown keyPressed(KeyEvent)
KEY_RELEASE/keyUp Component KeyListener keyReleased(KeyEvent)
KEY_ACTION/keyDown keyTyped(KeyEvent)*
KEY_ACTION_RELEASE/keyUp
a.
Follow the general steps below to convert a 1.0 component into a 1.1
listener.
For example:
newComponentObject.addActionListener(this);
to this:
public void actionPerformed(ActionEvent event) {
B-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
B
Listing for Jamfile.template
1 include $(JAM_HOME)Jamrules ;
2 # set the name of the JAR file
3 jar = JAR_FILE_NAME.jar ;
4 # this sets the package name of the java files - this is used
5 # to check dependencies of all compiled classes
6 SetPackage sl291 seperate components with spaces ;
7 # list of java sources - if the files are in the package
8 # directory then set the global variable
9 # $(USE_FULL_PATH_FOR_SOURCE) to "TRUE"
10 classes = File1.java
11 File2.java ;
12 DEPENDS all : $(jar) ;
13 # add the package of the java files to the list of directories
14 # added to the JAR file
15 AddPackageToJar $(CURR_PACKAGE) ;
16 # set the manifest file name - manifest.tmp is normally used
17 SetManifest manifest.tmp ;
18 # build the JAR file
19 JarFile $(jar) : $(classes) ;
20 # copy the new jar file to the BDK jars directory
21 File $(BDK_JARS_DIR)$(SLASH)$(jar) : $(jar) ;
1 Manifest-Version: 1.0
2 Name: sl291/package/classname1.class
3 Java-Bean: True
4 Name: sl291/package/classname2.class
5 Java-Bean: True
References
Additional resources – Complete JAM documentation is available
from Perforce’s web site at
http://www.perforce.com/jam/jam.html.
C-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
C
JAM
Features
● Jam/MR is a make(1) replacement that makes building
uncomplicated things simple and building complicated things
manageable.
JAM ships with complete rules for compiling programs with C, C++,
Fortran, and other languages, but does not currently include rules for
producing Java applications. Special build rules were added to the
rules provided with the distribution. These special rules are provided
below. To use them, you must add them to the end of the Jambase file
in the build directory before building JAM.
# @(#)Jamrules1.83 97/12/22
#
# Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software
# and its documentation for NON-COMMERCIAL purposes and without
# fee is hereby granted provided that this copyright notice
# appears in all copies. Please refer to the file "copyright.html"
# for further important copyright and licensing information.
#
# SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
# THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
# TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
# ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
# DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
#
#
# Jam rule file
#
# For this file to work correctly the following environment variables must be
# defined:
# JAVA_HOME - the root directory of the JDK (does not end in slash)
#
# The BDK is assumed to be in $(JAVA_HOME)/BDK. If not then invoke the SetBdkHome
# rule to set the JAM variable $(BDK_HOME) and $(BDK_JARS_DIR) to the proper
# values.
# Variable definitions
if $(UNIX) {
JAVA_HOME?= /usr/local/jdk1.1 ;
JAVAC = $(JAVA_HOME)/bin/javac ;
JAR = $(JAVA_HOME)/bin/jar ;
if ! $(BDK_HOME) {
BDK_HOME = $(JAVA_HOME)/BDK ;
}
BDK_JARS_DIR = $(BDK_HOME)/jars ;
} else if $(NT) {
ECHO "On NT ..." ;
JAVA_HOME ?= C:\\jdk1.1 ;
JAVAC = $(JAVA_HOME)\\bin\\javac ;
JAR = $(JAVA_HOME)\\bin\\jar ;
if ! $(BDK_HOME) {
BDK_HOME = $(JAVA_HOME)\\BDK ;
}
BDK_JARS_DIR = $(BDK_HOME)\\jars ;
}
#javac and jar command-line flags
JCFLAGS = ;
JAR_OPTIONS = -cvf ;
DESTDIR ?= .$(SLASH) ;
ECHO "Java compiler is at: "$(JAVAC) ;
ECHO "Destination directory is: "$(DESTDIR) ;
#if TRUE then the relative path of JAVA source files is created using the package
#information - otherwise it is assumed the source files are in the current directory
USE_FULL_PATH_FOR_SOURCE = FALSE ; # TRUE if source files are located in a
# subdirectory equivalent to the package
PACKAGE_PATH = ; # the current package in dot notation
CURR_PACKAGE = ; # the current package of java source files being processed
JAR_MEMBERS = ; # non-class and non-manifest files to be placed in a JAR file
# such as serialized objects, image, or html files
JAR_DIRS = ; # the list of all of the directories to be recursively placed
# in the JAR file
MANIFEST = " " ; # the name of the manifest file to be included in the JAR file
CLASS_FILES = ; # a list of all of the class files to be generated
# General rules and actions
# this rule resets all global variables used by the java rules used to generate
# classes and JAR files
rule Reset_Java_Rules
{
JCFLAGS = ;
JAR_OPTIONS = -cvf ;
DESTDIR ?= .$(SLASH) ;
USE_FULL_PATH_FOR_SOURCE = FALSE ;
CURR_PACKAGE = ;
PACKAGE_PATH = ;
JAR_MEMBERS = ;
JAR_DIRS = ;
MANIFEST = " " ;
CLASS_FILES = ;
}
# changes the jar tool options to the target value
rule SetJarOptions
{
JAR_OPTIONS = $(<) ;
}
# sets the name of the manifest file and adds the proper option to the jar tool
# option flags
rule SetManifest
{
MANIFEST = $(<) ;
JAR_OPTIONS = $(JAR_OPTIONS)m ;
ECHO JAR option flags changed to $(JAR_OPTIONS) ;
}
# sets the current package used for generated class files. This rule must be
# invoked prior to invoking JarFile or Classes
rule SetPackage
{
#<[1 - end] fully qualified class name with one component per index
CURR_PACKAGE = $(<[1]) ;
PACKAGE_PATH = $(<[1]) ;
for i in $(<[2-]) {
CURR_PACKAGE = $(CURR_PACKAGE)$(SLASH)$(i) ;
PACKAGE_PATH = $(PACKAGE_PATH).$(i) ;
}
if (USE_FULL_PATH_FOR_SOURCE = TRUE) {
j = $(c:S=.java) ;
} else {
j = $(c:B).java ;
}
skel = $(DESTDIR)$(CURR_PACKAGE)$(SLASH)$(<:S=_skel.class) ;
fullname = $(PACKAGE_PATH).$(<:B) ;
if (USE_FULL_PATH_FOR_SOURCE = TRUE) {
source = $(DESTDIR)$(CURR_PACKAGE)$(SLASH)$(<:S=.java) ;
} else {
source = $(<).java ;
}
{
switch $(i:S)
{
case .java : j += $(i) ;
case * : JARMEMBERS += $(i) ;
}
}
if $(j) { Classes $(j) ; }
DEPENDS $(<) : $(CLASS_FILES) $(JAR_MEMBERS) $(MANIFEST) ;
ECHO $(msg)$(dirs) ;
}
}
address
A location on a computer network, on a peripheral device, or in
computer memory.
address space
The range of memory locations to which a CPU can refer;
effectively, the amount of memory a CPU could use if all of the
memory were available.
applet
A Java program that can be included in an HTML page using
the applet tag.
application
Any specific use of the computer. The term is often used
synonymously with program.
application programmer’s interface (API)
The interface to a library or package of language-specific
functions or methods.
Bean
A reusable software component that can be manipulated
visually in a builder tool.
beanbox
A test container for testing your Bean components.
browser
A program used to view World Wide Web materials and
capable of interpreting URLs and understanding different
Internet protocols.
Glossary-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
class loader
A class loader is the foundation of the Java Virtual Machine
(JVM). A class loader is an executable class object that converts
a named class into the bits that make up an implementation of
that class. Class loaders enable the JVM to load a class without
having to know anything about the underlying file system
semantics. Class loaders extend the abstract class
java.lang.ClassLoader and implement the loadClass
method at minimum.
client
A software program that requests information or services from
another software application (server). For example, a browser is
a client that accesses data from HTTP servers.
Common Object Request Broker Architecture (CORBA)
The architecture and specifications aimed at software
developers and designers who want to produce applications
that comply with OMG standards for the ORB.
content handler
A specialized Java program that enhances Java functionality by
providing a means to understand a new content type; for
example, email, video, or audio files of nonsupported types. It
is responsible for reading data from a stream (provided by a
protocol handler) and returning an object representation of the
stream’s content.
component architecture model
A software model that enables developers to create software
pieces called components that can be combined together to
create applications.
distributed application
A program that makes calls to other address spaces, possibly on
another physical machine.
distributed computing
The technique of allowing applications running on one machine
to access applications that are running on another machine.
That is, client programs make calls to programs in other address
spaces, either local or remote.
distributed object computing
An extension of distributed computing, where objects are
implemented in an address space separate from the client
program.
Glossary Glossary-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
operations and attributes and can specify exceptions that occur.
IDL is not a programmatic language—the IDL file must be
compiled to the specific language implementation desired.
Internet
The world-wide network of computers communicating using
the TCP/IP protocols.
introspection
The process provided by the JavaBeans API to enable builder
tools to discover the properties, methods, events, and behavior
of Bean components.
Java
A programming language developed by Sun Microsystems™
that enables dynamic Web pages.
JavaBeans
A portable, platform-independent component model written in
the Java language.
JDBC API
A set of interfaces designed to insulate a database application
developer from a specific database vendor.
JavaIDL API
A set of classes and interfaces that enables developers to define
a set of remote interfaces using the CORBA IDL standard and
maps IDL constructs onto a set of stubs and skeletons that can
be used to create a CORBA implementation.
multicast
A special form of broadcast where copies of the packet are
delivered to only a subset of all possible destinations.
multicast source
An event source that is allowed to have many event listeners at
the same time.
network
A group of connected computers.
NFS
A distributed application that enables remote file systems to be
accessed by the end-user in the same way as that user would
access a local file system.
Glossary Glossary-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
replicated
An object that has one or more exact copies of itself available
from multiple address spaces. For example, under NIS+,
Replica Servers provide the same information to clients as the
Master Server, and it is irrelevant to the client as to which server
the information comes from.
rmic
The RMI compiler that generates the RMI sub and skeleton
classes.
rmiregistry
An application that provides a simple naming lookup service of
remote objects in the RMI API.
Security Manager API
A class that enables developers to set and control the security
policy that must be followed by Java programs running on a
system.
serializable
Java objects are serializable if they implement the
java.io.Serializable interface and meet the following
criteria: they do not contain references to nonserializable objects
(for example, java.lang.Thread,
java.io.FileOutputStream) unless these references are
marked with the transient keyword. An object that is
serializable may be serialized.
serializing or serialized
Java objects that are serializable can be sent as a stream of bytes
over any type of java.io.Output stream and retrieved using
any type of java.io.InputStream. This includes files, pipes,
and sockets. An object is said to be serialized when it is
converted from its internal in-memory format to the stream of
bytes that can be sent over the wire.
server
In the client-server model for file systems, the server is a
machine with compute resources (and is sometimes called the
compute server) and large memory capacity.
skeleton
A server-side entity that contains a method that dispatches calls
to the actual remote object implementation.
Glossary Glossary-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Index
Symbols B
"write once, run Bean
everywhere" 11-4 examples of 1-7
features of 1-6
A Bean storage, goals 6-5
BeanBox
ActionEvent 3-8 adding your Beans to ToolBox
ActionListener 3-9 window 2-33
actionPerformed() 3-9 BeanBox window 2-7
ActiveX bound properties 2-22
a component model 1-20 changing Bean
advantages of 1-20 properties 2-16
ActiveX bridge 11-9 connecting Beans 2-26
addActionListener() 3-9 customizers 2-19
adding your Beans to the design mode 2-9
ToolBox window 2-33 JDBC SELECT Bean 9-14
addXXXListener(XXXListener moving a Bean 2-12
l) 3-19 placing a Bean on 2-10
advantages of ActiveX 1-20 PropertySheet window 2-8
agents 9-8 QuoteMonitor Bean 9-18
APPLET tag 10-20 resizing a Bean 2-13
applets run.sh 2-5
issues as Beans 10-17 running the BeanBox 2-5
architecture overview saving and restoring 2-31
JDBC 9-12 selecting a Bean in 2-11
architetecture overview ToolBox window 2-7
RMI 9-19 what is it? 2-4
automatic analysis windows of 2-6
definition 5-14 BeanInfo file
AWT components as customizers 7-44
sources 3-18 Beans
and scripting 10-16
issues for applets 10-17
Index-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
putting Beans together 1-14 defining 4-21
Beans in distributed definition 4-5
environments 9-10 fireVetoableChange 4-24
Beans.instantiate method 5-26, overview 4-20
10-16 recap 4-30
Beans.instantiate() method 6-18 validating a property
bound property 4-14 change 4-28
defining 4-13 VetoableChangeListener 4-24
definition 4-4 VetoableChangeSupport 4-24
firePropertyChange 4-14 constructors
overview 2-22 for customizers 7-45
recap 4-19 constructors for property
building Beans sheets 7-16
composing a Bean from other converting 1.0 event handling to
Beans 10-10 1.1 A-3
from a serialized CORBA 9-32
prototype 10-11, 10-12 creating applets and applications
from scratch 10-4 with Beans 10-14
inheriting from a Bean 10-5 creating transitional Beans 12-6
options for 10-4 creating your own source 3-18
subclassing a Bean and customer class for a Bean 2-19
adding BeanInfo 10-6 customization
definition 7-4
C customizers
BeanInfo file 7-44
capitalize rules 5-24 characteristics of 7-42
category of events 3-10 extending Component 7-45
changing Bean properties 2-16 implementation
Class class definition 10-39 requirements 7-43
class loader definition 10-41 implementing
classes that are serialized 6-7 Customizer 7-45
ClassLoader class 10-41 naming conventions 7-42
code integration problem 5-4 null argument
common uses of adapters 8-9 constructor 7-45
component model PropertyChangeListener
ActiveX 1-18 support 7-46
major elements 11-6 setObject() method 7-47
services 11-7 when a property editor is not
services of 1-12 enough 7-7
component-based software 11-5 when to use 7-41
components 1-4
composing a Bean from other
Beans 10-10 D
connecting Beans in the DataInput interface 6-11
BeanBox 2-26 DataOutput interface 6-11
constrained property defining bound properties 4-13
Index Index-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
categories of 3-10 and security 5-54
definition of 3-4 definition 5-9
delivery issues 3-23 key concepts 5-12
obtaining details 3-12 key issued addressed 5-6, 5-7
propagatiing notification 3-7 process overview 5-11
events in the BeanBox 2-26 summary 5-55
example code Introspector.getBeanInfo
Beans in an applet 10-43 method 5-29, 5-30, 5-31
Beans in an application 10-46 issues for applets as Beans 10-17
executeQuery() method 9-12
J
F J/Crypto 10-32
firePropertyChange for a bound JAR files
property 4-14 creating 2-36
fireVetoableChange 4-24 format 2-33
in HTML 10-20
G review 10-19
security and
getConnection() method 9-12 cryptography 10-31
using in HTML files 2-35
H Java Cryptography Architecture
hooking beans together in (JCA) 10-31
applets or applications 10-50 Java Studio 11-15
hookup class 8-5 Java technologies 9-10
Java Workshop 11-15
JavaBeans
I and introspection 5-5
identifying sources 3-19 as a component model 1-4
implementing Customizer bridging to other models 11-8
interface 7-45 browser support for 12-5
indexed property design goals 1-8
definition 4-5 motivating scenarios 9-4
InfoBus technology 11-11 vision 5-5
instantiating a Bean what is it? 1-4
coding possibilities 10-36 JavaIDL
in an applet 10-37 overview 9-32
in an application 10-37 javakey 10-33
steps involved 10-35 JavaSoft distributed
integrated development technologies 9-10
environment (IDE) 11-12 JBuilder 11-17
interfaces 3-16 JDBC
creating your own listener architecture overview 9-12
interface 3-17 Connection 9-12
introspection JDBC SELECT Bean 9-14
additional information 5-53 overview 9-11
Index Index-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
PropertySheet window 2-8 serializable
properties on 4-32 Beans.instantiate() 6-18
views 4-33 classes 6-7
PropertyText view 4-34 event adaptors 6-8
putting Beans together 1-14 fields automatically
serialized 6-9
Q fields not serialized 6-9
ObjectInput interface 6-11
QuoteMonitor Bean 9-18 ObjectInputStream class 6-14
ObjectOutputStream 6-12
R references to external
rapid application development Beans 6-8
(RAD) 11-13 static 6-9
readObject() method 6-14 the interface 6-6
reflection transient 6-9
advantages 5-50 what is not saved 6-8
and JavaBeans 5-50 what is saved 6-8
definition 5-8 writeObject method 6-12
major classes in the API 5-52 serializing Beans 6-12
remote reference layer 9-20 services of component
removeXXXListener(XXXListene models 1-12
r l) 3-19 setObject() method 7-47
resizing a Bean 2-13 setValue() method 7-17
RMI simple property
architecture overview 9-19 defining 4-8
definition 9-17 definition 4-4
exercise code conceptual sources
overview 9-22 creating your own 3-18
exercise code source files 9-23 definition of 3-6
QuoteMonitor Bean 9-18 identifying 3-19
remote reference layer 9-20 multicast 3-20
rmic commant 9-21 notifying your listeners 3-22
rmiregistry 9-21 provided by the AWT
stubs and skeletons 9-21 package 3-18
transport layer 9-20 unicast 3-21
rmic command 9-21 SQL statements 9-12
rmiregistry application 9-21 stub and skeleton layer 9-21
run.sh 2-5 subclassing a Bean and adding
BeanInfo 10-6
S
T
saving and restoring the
ToolBox window 2-7
BeanBox 2-31
TooManyListenersException 3-2
scripting and Beans 10-16
1
security and cryptography 10-31
transient keyword 6-10
selecting a Bean 2-11
U
unicast source 3-21
using a builder tool 10-15
V
validating a property
change 4-28
VetoableChangeListener 4-24
VetoableChangeSupport
class 4-24
views
determining 4-35
examples of 4-36
PropertyCanvas 4-33
PropertySelector 4-34
PropertyText 4-34
visual application builders
definition 11-14
Java Studio 11-15
Java Workshop 11-15
JBuilder 11-17
Mojo 11-16
Visual Café 11-16
VisualAge 11-17
Visual Café 11-16
VisualAge 11-17
W
windows of the BeanBox 2-6
writeObject() method 6-12
Index Index-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Index-8 JavaBeans Component Development
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
BeCopyright 1998 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, Californie 94303, U.S.A. Tous droits réservés.
Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la
copie, la distribution, et la décompilation. Aucune partie de ce produit ou documentat associée ne peut être reproduite
sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de
licence, s’il y en a.
Des parties de ce produit pourront être dérivées du système Berkeley BSD licenciés par l’Université de Californie. UNIX
est une marque déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company Ltd. Le
logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un
copyright et licencié par des fournisseurs de Sun.
Sun, Sun Microsystems, le logo Sun, sont des marques fabrique ou des marques déposées de Sun Microsystems, Inc. aux
Etats-Unis et dans d’autres pays. Toutes les marques SPARC, utilisées sous licence, et sont des marques de fabrique ou des
marques déposées de SPARC International, Inc. aux Etats-Unis et dans d’autres pays. Les produits portant les marques
SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.
L’ interface d’utilisation graphique OPEN LOOK® et Sun™ a été développée par Sun Microsystems, Inc. pour ses
utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour la recherche et le développement du concept
des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive
de Xerox sur l’interface d’utilisation graphique Xerox, cette licence couvrant aussi les licenciés de Sun qui mettent en
place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux licences écrites de Sun.
Le système X Window est un produit de X Consortium, Inc.
CETTE PUBLICATION EST FOURNIE “EN L’ETAT” ET AUCUNE GARANTIE, EXPRESSE OU IMPLICITE, N’EST
ACCORDEE, Y COMPRIS DES GARANTIES CONCERNANT LA VALEUR MARCHANDE, L’APTITUDE DE LA
PUBLICATION A REPONDRE A UNE UTILISATION PARTICULIERE, OU LE FAIT QU’ELLE NE SOIT PAS
CONTREFAISANTE DE PRODUIT DE TIERS. CE DENI DE GARANTIE NE S’APPLIQUERAIT PAS, DANS LA MESURE
OU IL SERAIT TENU JURIDIQUEMENT NUL ET NON AVENU.
Please
Recycle