Chapter 23. Java Beans in Theory

Java Beans in Theory

Java beans is the architecture for component software in Java. It’s a pretty big topic, so we’ll cover it in two chapters. This chapter explains the theory: what component software is, how it is used in Java, what software tools are used and when. The chapter concludes with a summary of Enterprise Java Beans, which is the use of component software to construct server-side systems rather than client applications.

The next chapter provides a program specification for two Java beans. It then walks through creating these components and integrating them. A bean info class is developed for each of the two beans. Beans are all about three things: properties, events, and methods. The bean info class describes these three qualities of the bean to a visual design tool. Chapter 24 concludes with a small amount of additional material on specialized features of the beans model. This chapter is a prerequisite for getting the most out of the following chapter.

Unhappily, a large number of the beans white papers, books, and tutorials in existence are dense and impenetrable. They fall into the classic pitfall of presenting material which is “clear only if already known.” The situation is made worse because, like much software, beans tend to be a little abstract. Throw in the confusing new terminology and the multistage lifecycle, and you have a recipe for something obscure and ponderous.

To remedy the situation we will go step by step. We’ll start with a description of components in general. Next, a refresher on events, followed by an outline of the code conventions for beans. Then we’ll look at the proof-of-concept design-time tool called the Beanbox. We won’t present any beans code in this chapter, but we will walk through a full example of how beans are integrated in the beanbox. That knowledge will be used in the next chapter, where we gradually develop two practical beans.

What Is Component Software?

If you are already familiar with the power of software components, perhaps through using one of the Windows-based tools like Visual Basic Extensions or Delphi, then you can safely skip over this first section. Otherwise, read on for an introduction to a powerful new technique that is widely used in the Microsoft Windows world, and emerging on Unix and the Mac.

Programming is one of the few professions where each piece of work starts more or less from first principles. When programmers are assigned to a new project, the design and coding often begins with literally a blank sheet of paper. By the time you have completed half a dozen projects, you can recognize similar situations and perhaps create some application-specific libraries. But that is often the extent of code sharing and reuse.

Imagine if plumbers worked that way. Think what it would mean if every job required the plumber to laboriously handcraft each pipe, bolt, and valve. Plumbing jobs would take a lot longer and be much more costly. Thankfully, plumbers buy their supplies ready made, and a lot of plumbing simply involves using standard pipes and joints to connect big preassembled components such as garbage disposals, dishwashers, and water heaters. Programming is still catching up with plumbing in this respect. Component software is an attempt to use software building blocks larger than “individual lines of code.”

In general, with most programming languages, there are two approaches for organizing and arranging executable code. The code can either be set up as an executable program (e.g., an application, an applet, or a servlet). Or it can be a library that implements some API and contains many related classes and methods. Component software is a third approach, with some aspects that are like “executable program” and some that are like “library.” Component software strives to combine the reusability of a library with the customized specialization of an individual program.

To look at it another way, when you use a large library (like Swing) sometimes you only use a handful of pieces from it. What if there were some way to bundle up just the code that has a single well-defined purpose, and quickly use it in several different programs without having to code it in line-by-line? What if you had a component editor which allowed you to add, move, and join together classes instead of “lines of code”? Coming from the Windows world, which places a heavy emphasis on GUI tools, component software relies on some kind of visual tool to assemble the units. Software components are intended to bring these three good things to your software products:

  • widespread reuse of code

  • simplicity of component integration via visual tools, leading to

  • higher overall productivity for code development

So what makes a good candidate to be a software component? Essentially, it is any self-contained piece of code with a well-defined function that you might use in several programs, and frequently with a GUI representation. For example, Figure 23-1 shows a “color chooser panel” that displays a matrix of different shades and allows the user to click on the color needed— a great candidate to be a software component.

A “color chooser panel” makes a good software component.

Figure 23-1. A “color chooser panel” makes a good software component.

This is the color chooser used on Windows 98, and you can’t tell from running the program whether this actually is implemented as a component or not. Regardless, it’s an example of the kind of self-contained functionality that makes a good component. A color chooser panel is written once, and can be turned into a software component by following some simple coding conventions which we will see later. The component can then be integrated with any of your programs that need to process colors by dragging and dropping in a visual builder tool. Components can be created out of several simpler components. This color chooser clearly uses simpler components like Button, TextField, Cursor, and Canvas. Most components also belong to a library, allowing you the choice of using a visual builder tool, or explicitly writing the lines of code to instantiate and invoke the functions you need.

Once you get used to it, the visual way can be quick. However, there is no free lunch. It takes perhaps twice the effort to write a software component and build in the flexibility. Generally speaking, the easier it is to customize and use a given software component, the more work it takes to implement it. Another factor to consider is that Java beans are not as easy to learn as some other parts of Java. There isn’t a single overall design philosophy, the way there is with, e.g., JDBC. Java beans (or more accurately, the bean info classes that accompany them) are built out of an obscure mixture of arbitrary rules, conventions, and language features. One programmer compared creating Java beans to “trying to build a space shuttle out of kitchen utensils for a child to operate.” So grab your egg whisk, spatula, and space helmet, and let’s get going.

What Is a Java Bean?

A Java bean is an individual software component written in Java. The definition of a Java bean from one of Sun’s white papers follows. To let a class be a Java bean you follow a few simple naming conventions, or you may prefer to write a “bean info” class that accompanies your bean and explicitly describes its interfaces. The bean-related framework is in the java.beans and java.beans.beancontext packages. A bean context is a logical container for several beans, allowing them to be nested in a hierarchy (beans within beans).

Note that the simple definition means just about every existing class is a Java bean automatically! Another advantage is that, unlike all other component architectures, Java beans are not tied to just one platform. Because they are written in Java, they run on all computers. Component software as currently practiced with Visual Basic is limited another way, too. VB components are most often used for GUI controls. Java has taken software components much further. With an architecture known as Enterprise Java Beans (EJB), the beans model has grown up to encompass sophisticated business algorithms completely unrelated to visual pre-sentation. Enterprise Java Beans (EJB) is the recommended approach to server-side Java components. We summarize EJB at the end of this chapter.

The Visual Basic variety of component software (developed by Alan Cooper and purchased by Microsoft) has been very successful. There are many companies that make a living solely from selling VBX (Visual Basic eXtensions) components. They often do pretty well, right up to the time Microsoft decides to bundle that kind of component with VBX. There are some companies selling Java beans, too, but they do not have the volume of VBX today. On the other hand, the Java components are more useful because they can be used on more than one platform, and they have much greater capabilities (network, security, multimedia, threading, etc.).

Although VB components (and the ever-changing framework names of OLE, COM, ActiveX, DNA, and now .NET) are widely used, they have a limited area of best applicability: the creation of small to medium GUI applications that are restricted to Windows platforms. Java beans go way beyond this, bringing the benefits of component software to every tier of an N-tier system, and particularly to server-side programming.

Java beans come in two varieties: visual and non-visual. All visual beans extend the class java.awt.Component or one of its subclasses. Non-visual beans don’t extend the java.awt.Component class and don’t have a GUI element at runtime, but are still manipulated visually at design time. All server-side software components are non-visual beans. An example of a server-side compo-nent would be a bean to access a database. The bean knows how to set up a connection with a database, send in queries, and get back data. Any program to which you add this bean instantly becomes database-capable! IBM gives away a similar bean that connects to an Excel spreadsheet.

Some Commercial Java Beans

You should use beans when you anticipate that the benefits (the amount of code customization and reuse) will more than offset the cost (the extra work involved in coding that flexibility and following the bean protocols).

Properties and Events

Software components must have simple well-defined public interfaces that allow access to everything they do. Most of the Java beans conventions are intended to help with this. Beans have properties that store and let you change characteristics of the bean. A property is any characteristic of a bean that can be given an initial value after the bean is written and before the bean is used. Properties customize the appearance or function of a bean. They are things like what font should be used, what size on the screen it is, and so on. A property of a bean is really just a data field in the bean class, with public getter and setter methods.

Too much literature comes at beans all wrong. It focuses on properties, when it should be focusing on what beans do, namely:

  • Bean A changed one of its field values, and it needs to tell bean B about it.

  • Bean A has a GUI interaction that should cause a method in bean B to be invoked.

  • Bean A wants to change one of its field values, and it needs to ask bean B if it’s OK.

Beans communicate with each other using events. The three tasks above are all implemented by one bean sending an event, and another bean receiving it and reacting to it. Some beans generate events, some beans handle events, and some do both. The bean has no way of knowing at coding time what it will be connected to. All it has to do is generate and handle appropriate events. Beans should be like Lego bricks: you can buy any Lego kit anywhere and be confident that it will be compatible and interoperate with all your other Lego sets.

Coding Time, Design Time, Runtime

There is a very important distinction between coding time (when a skilled programmer writes the bean), design time (when someone uses a visual tool to customize beans and connect them to other beans), and runtime (when the user runs the integrated program containing the components). Visually connecting existing components doesn’t need a lot of programming skill, and the task may be done by web page developers rather than programmers.

Figure 23-2 shows the three stages in the life of a bean.

The life cycle of beans.

Figure 23-2. The life cycle of beans.

It’s important to have a solid appreciation of the three different stages in the life of a bean. Certain tasks can only be done at certain times. The three stages, along with what you do in each, are:

  1. Coding time. During coding time, your best programmers will be writing the java bean software components. They will establish the properties, methods, and events that allow beans to be configured and to pass data to each other. Writing a bean is mostly like writing any program, but you typically want to make far more of the behavior configurable. In addition, you can make things more polished by providing extra classes giving bean information to the design time visual tool.

  2. Design time. Design time is when web programmers, or even knowledgeable users, run some kind of visual component integration tool to “glue” beans together. They will set the initial defaults for bean properties, choose among the configuration possibilities, and draw connections for data, methods, and events for beans. Design time is a mixture of programming and systems integration. You don’t actually write any lines of code, but the visual tool will generate plenty on your behalf, to implement the connections you have made. There’s an example of this later in the chapter. The final output from design time is an assembly of software components in the form of a jar file.

  3. Runtime. At runtime, the users will execute the jar file that contains the finished, customized components. They will see the behavior that was chosen for them at design time, among all the behaviors that were implemented at coding time.

Refresher on Events

You absolutely must have a good understanding of events and event handling to understand how to write beans. Bean events are just like ordinary window system events. As a refresher, we use events to communicate between two different parts of a program. One part of the program has things happening asynchronously (i.e., at irregular and unpredictable intervals), such as a key in a GUI being pressed. The thing that is happening is called the “event,” and the code where it happens is the “event generator.” Pressing a key on the keyboard generates an event. Clicking on a button generates an event. Moving the mouse generates an event. A timer expiring is an event. Another part of the program has some code that needs to hear about the events and handle them.

The operating system calls a routine in the java runtime library when an event happens. How do we get the runtime library to call your event-handling routine? The runtime library is not compiled with your code, and has no knowledge of it. The same problem arises with beans. In general, different beans are not going to be compiled, and should have no knowledge of each other. Yet we need to connect them together somehow. Beans use events to solve this problem (see Figure 23-3).

Problem: How to get them to connect.

Figure 23-3. Problem: How to get them to connect.

The same solution to this problem is used in both cases (window system code and beans code). A piece of your code is interested in being told about each event as soon as it happens, and each time it happens. This piece of code is going to “handle” or process the events. It is called the event handler, and there may be several of them for any event. This code will implement an interface called ZzzzListener, where “ Zzzz ” is a word describing the event generator in some way. AWT has KeyListener, ActionListener, WindowListener, FocusListener, etc. The interface will have a method or methods that say, in effect, “ zzzzHappened().

The event generator will have a method called addZzzzListener(). That method takes a parameter that is a ZzzzListener interface. Anyone that wants to get the events must first register their event handler with the event generator by calling its add listener method (see Figure 23-4). The event generator will save a reference to all the listeners that register. Then, each time the event happens, it will call them back to say “the event just happened.”

Solution: Register your code at runtime.

Figure 23-4. Solution: Register your code at runtime.

In regular event programming, an event handler will register itself with the event generator by calling the generator’s addZzzzListener() method. The handler must pass in an object that implements the methods promised in the ZzzzListener() interface (often itself, or it could be a nested class). With beans, we strive to eliminate knowing the details of any other bean, so the event handlers in one bean don’t add themselves directly to the list of Listeners in the event generator bean. Instead, a designer will use the design tool to connect an event listener bean to an event generator bean. The tool creates some “glue” code that will execute at runtime and call the add listener method.

At runtime, the generator has a collection of listeners that have registered their interest in listening to this event. Each time a Zzzz event occurs, the generator goes through that list and calls the appropriate method in the object that the eehandler sent over as a parameter.

Bean Conventions

The Java Bean architecture and the design tools expect your bean classes to follow the get/set/is conventions for fields and the methods that operate on them. The standard bean naming conventions are best shown by examples:

  • an int property called “myValue” is set (assigned a value) by a method with this signature:

    public void setMyValue(int i) 
  • the value of an int property called “myValue” is obtained by a method with this signature:

    public int getMyValue() 
  • a boolean property called “ moreData ” can also use this form of name in place of getMoreData(), allowing it to read more fluently in if statements and expressions:

    public boolean isMoreData() 

There is a letter case inconsistency here which is defined not to be a problem. Following the rules in the Java Language Specification, class names start with a capital letter, data fields start with a lower case letter, and the first letter of each word in an identifier is capitalized. That means that the property “ myValue ” corresponds to methods “ setMyValue ()” and “ getMyValue() ” even though they actually differ in letter case. The beans specification has a special rule that says, effectively, “yeah, we know, but we’re going to define that these things match.” The alternative would have been to introduce a new keyword or two, and nobody wanted to do that.

All the Swing GUI controls have been written to follow the simple code conventions that allow a class to act as a bean. So all Swing components are beans. The examples above use boolean and int types, but the same naming pattern is used whatever the type of the property. Some of the Sun literature refers to this naming convention as a “design pattern.” It’s a pattern in the sense of a template, applied to method names. But the term “design pattern” has already been taken for something else (pre-packaged algorithms for common situations), so Java beans should have called it something else. As well as this get/set convention, you need to be very careful to choose meaningful names for your methods. The names show up in the bean application builder, and are one of the key ways that bean integrators figure out what the method does.

The next section describes how to install and run the BeanBox, which is a rudimentary design time tool. You don’t create a bean in the beanbox—you connect existing beans. The section will show you how to connect some existing demo beans that come with the beanbox. In the next chapter, we will use this knowledge to connect the beans we develop ourselves.

Install the Beanbox

The next few pages sidetrack from beans in order to introduce the visual tool we will be using at design time. The java.bean package has been part of the JDK since Java 1.1, but you also need some application builder software to experiment with beans. Most Java IDEs, such as Sun’s Forte, Borland’s JBuilder, IBM’s Visual Age for Java, or Symantec’s Visual Cafe, include bean builder software.

Rather than present any one of the dozens of IDEs available, we will download and use the very basic and free “Beanbox” from Sun. The beanbox is a rudimentary design time visual integration tool for beans. It has enough functionality to show the bean concept, but it has not been kept up to date (it does not serialize beans using XML, for example). The beanbox does roughly the same job for Java beans that the appletviewer does for applets. It provides a quick, simple way to see them running. To get started on your first bean, go to

http://java.sun.com/products/javabeans/software/bdk_download.html 

and download the Bean Development Kit version 1.1 (or later). You can download it as a zip file, or as a Windows-only .exe file which can be executed to do the installation automatically. If using Windows, download the .exe file version and install the BDK into disk directory c:dk1.1.

After choosing the installation directory, the installer will prompt you to select which Java runtime environment to use. Any JRE of release JDK 1.2 or greater is fine. If the installer does not offer you any JVMs to choose from, use “find” on your system to find a file called “java.exe” and use the latest version of that.

Some of the advanced IDEs available today make little distinction between coding time and design time. They provide plenty of visual support for both. They offer forms and templates that will automatically generate events and event handlers, and put them in the right place. Once you master an environment like this, you can be very productive. I’ve avoided using such an IDE in this chapter because it would hide what is going on, and you’ll be a better beans programmer if you understand what is going on. Unlike these other IDEs, the beanbox doesn’t help you code beans at all. Its purpose is to let you initialize and connect beans at design time, and provide a basic test environment to run them.

Run a Demo Bean

The next step is to use the beanbox on one of the example beans that accompany it. It is traditional to use the juggler bean. The juggler bean displays several gifs in rapid succession to present an animated demonstration of juggling. Go to the beanbox directory and start the beanbox with these commands:

cd c:dk1.1eanbox

run 

The run.bat script updates your class path to include bean libraries and will bring up the beanbox with its four windows shown in Figure 23-5. There is also a run.sh script for people using Unix.

The beanbox.

Figure 23-5. The beanbox.

The narrow left-hand window labeled “ToolBox” has a list of all the beans the beanbox currently knows of. The largest window, labelled “BeanBox,” is where we will manipulate beans, and make connections between beans. You will click on a bean in the Toolbox window, and then click on the beanbox to transfer the bean to the box and start working on it.

The upper window on the right side, labelled “Properties - BeanBox,” will show a list of the properties (loosely, the public fields) of the bean. When you first start up the beanbox, no other beans are loaded, and it shows four properties of itself: background and foreground color, panel name, and panel font. (That’s right, the beanbox is written in 100% pure Java, runs on all platforms, and is itself a bean!)

The lower window on the right-hand side, labeled “Method Tracer,” is a recent addition to the beanbox. The method tracer is intended to provide a proof of concept of bean debugging support through tracing the flow of control. We don’t use it here, and suggest you move it out of the way by selecting “Services | Hide Method Tracing” from the menu along the top of the beanbox.

Loading a Bean into the Beanbox

When you start the beanbox, it will load all the jar files that it finds in the directory c:dk1.1jars. The beanbox will then display all the beans from those jar files in the lefthand “toolbox” window. The beanbox comes with about one dozen demonstration beans, sadly none of them tutorial in nature. These beans will appear in the toolbox window when you start the beanbox. You transfer a bean to the beanbox by clicking on it in the “toolbox” window. The cursor will change to a crosshair. Move it over to the beanbox, click again, and a copy of the bean will appear in the beanbox.

The new copy of the bean will have a crosshatched border in the beanbox. That indicates which bean has the focus (the active component in a GUI is said to “have the focus,” meaning that user input will be directed to it). This is the bean to which editing operations from the edit menu will be applied. You can drag the highlighted bean around to a new position by click-and-dragging on the cross-hatching. Figure 23-6 shows the “juggler” demo bean after an instance has been dropped on the bean box. There are some other beans in this beanbox, too, but only the juggler has the cross-hatched border.

The cross-hatched border shows the bean with the focus.

Figure 23-6. The cross-hatched border shows the bean with the focus.

Customizing Bean Properties

The beanbox is a design time tool. After coding some beans, put the jar files containing them in a directory known to the bdk, and transfer several of the beans to the beanbox. In the beanbox you can then select the beans one by one, and customize their properties using the properties sheet shown on the right of Figure 23-6.

The property sheet shows that the juggler bean has three properties called “debug,” “name,” and “animation rate.” You can give the highlighted bean new values for these properties by typing them on the property sheet window. These new values will change the appearance or behavior of the bean. The new values that you give to these properties will be carried forward to runtime. The bean will start running with these initial values. Note that you can edit bean properties only when the bean is surrounded by cross-hatching in the beanbox. That’s all there is to customization.

Try it. You’ll see that a small number (less than 100) makes the animated frames fly by. The “animation rate” property represents the number of milliseconds between frames. Speed it up to 1, and then keep an eye on the image. Pauses and discontinuities in the animation represent garbage collection or other work your system is doing. Enough of the fun, let’s get back to work. Set the animation rate at 10,000 so it is less distracting. Next, we will connect a button component to stop the animation entirely. This will be our first example of integrating two beans. Stopping/starting animation is a service that the juggler bean offers, and we just need to find a way to connect a button to it.

Connecting a Button to a Method in Another Bean

This section walks you through the steps to connect a button push event to a method in another bean. After you make this design time connection, each press of that button at run time will cause the method in the other bean to be called. We want to avoid building any knowledge of one bean into the other at coding time. We certainly don’t want the method to be called directly by name from another bean. The whole idea is to keep things as flexible as possible by allowing arbitrary beans to be joined after coding time wherever it makes semantic sense. These beans could be created at different times by different people without any knowledge of each other, and we still expect them to fit together.

The beanbox design tool uses a combination of menu choices and mouse movements (tracked by red lines) to make the connections between beans. The finished integrated beans are delivered from the beanbox in the form of a jar file that can be run as an applet.

The first step is to bring the “OrangeButton” bean from the toolbox into the beanbox, and leave it highlighted by clicking near its border. You can move beans about in the box by clicking and dragging on the cross-hatched border. Next, click on the “Edit” menu at the top of the beanbox. That displays a drop-down menu with a list of things you can do with this bean, including cut, copy, paste, and “Events,” which leads to a pull-right menu, as shown in Figure 23-7.

Connecting an event.

Figure 23-7. Connecting an event.

The Events menu selection lists all the events that the highlighted component has said it can generate. Select the only choice on the button push menu, and the beanbox will now look like Figure 23-8.

Connecting an event.

Figure 23-8. Connecting an event.

The red line represents the event we are trying to connect. It starts at the component that generates the event, and follows the mouse as we move it around. Decide to which component you would like to send this event, and click on its border. If you make a mistake, you can cancel and start again. When you have successfully chosen the destination java bean, you will get a pop-up window as shown in Figure 23-9.

Connecting an event.

Figure 23-9. Connecting an event.

The Event Target Dialog (as this pop-up is known) displays a list of methods that are candidates to be called when the button push event is delivered to the juggler bean. Not all methods are candidates. Only those that have the right signature will be shown in the dialog. And the bean coder better have picked names that suggest clearly what the methods do, because the method names are your only guide to the semantics until you read the documentation for this bean. Here we can see a method called “stopJuggling.” Highlight it and click “ok” to dismiss the dialog.

A new pop-up window will briefly appear to inform you that the beanbox is “generating and compiling an adapter class.” The beanbox is automatically generating some “glue” code to make the connection that will allow an event to be sent between these two beans. The pop-up will disappear within a few seconds and you are free to press the button and stop the picture of the Tooth Fairy from juggling.

After that, highlight the orange button again, and use the property sheet editor to change its label to “stop juggler.” Voila! You have connected two beans by an event from one bean causing a method call in the other. Now add another button, give it a pink color in the property sheet, relabel it as “start,” and connect it to the startJuggling method.

The final step is to choose “File | Make Applet...” to prove that you can save your work and run it outside the beanbox. Accept the default destination that the Make an Applet panel offers you. When it has finished generating and compiling the applet code, you can cd to the destination and run your software components by entering these commands

cd dk1.1eanbox	mpmyapplet
appletviewer myapplet.html 

You should see exactly what you constructed in the beanbox, but running as an applet rather than in a design tool. It is not particularly convenient that the beanbox will turn your components into an applet. A stand-alone executable jar file would be much more useful. An applet output form was chosen for ease and speed of beanbox implementation by the Sun programmers. Applets already have a graphical context within which they execute; for a stand-alone executable, that would have to be specified and provided somehow. Sun doesn’t intend you to use the beanbox for anything except quickly checking that your components can snap together.

You are now a wizard of visual programming.

The beanbox is a crude design time tool, but you can see that visual programming is easy. The next chapter shows the low-level details needed to make it all work well. Specifically, we will look at the bean information classes that accompany your beans, and help provide information to the design time tool. This is a good place to take a break. The remainder of the chapter describes more sophisticated uses of beans that you may later engage with.

Activation Framework and Infobus

There are two software packages that provide additional support for beans: the Java Activation Framework, and the InfoBus. You can write much java bean software without ever needing either of these, but they are available when you want them. The Activation Framework lets your code determine the type of an arbitrary piece of data, discover the operations available on it, and instantiate an appropriate bean to perform those operations. For example, if one of your programs expected an arbitrary data stream and actually got a stream of MPEG data, the activation framework would let your code identify the data as MPEG. From that type, your code could locate and instantiate an object that will play the movie.

Java Activation Framework

The Java Activation Framework is currently packaged as a standard extension to Java, meaning it is not bundled with the JDK. Sun intends to fold this functionality into a future release, probably JDK 1.5. In the meantime, you install it by downloading the file activation.jar from java.sun.com and placing it somewhere in your classpath. The activation framework is part of a larger, improved specification for beans known as the “Glasgow specification.” Glasgow includes three parts in all:

  • the Java Activation Framework

  • runtime containment and services protocol allowing nested beans

  • an interface allowing Java programs to easily tie into native drag ’n drop

There is a specification beyond Glasgow known as Edinburgh. Edinburgh is the next specification of the Java Beans component architecture. It looks like Edinburgh is generally adding more services and more complicated services rather than changing existing practices (good!). The city names Glasgow and Edinburgh were suggested by project leader Larry Cable. Larry noticed that Microsoft was in the habit of naming releases after cities: Win95 was code-named Chicago, NT 4.0 was Daytona, and the infinitely-delayed object-oriented version of NT was called Cairo. Tongue in cheek, Larry proposed that they name the next four EJB releases after cities in the home countries of the four lead developers in the JavaBeans team. For once, marketing listened to engineering, and Larry says he really learned a lesson about making goofy suggestions to marketing. The first EJB release is the Glasgow release, the second the Edinburgh release, and these will be followed by Nice and Barcelona releases. The most recent information on Edinburgh is on the Sun website at java.sun.com.

Infobus

Infobus is a way for beans to communicate data more directly with each other. It was developed by the Lotus folks at IBM and given back to Sun to advance the cause of Java. Infobus classifies beans as “data providers” or “data consumers.” Data providers access data from some native source, such as a DBMS, spreadsheet or flat file, and move the data onto the InfoBus. Data consumers retrieve data from the bus for analysis or visual display. Splitting producers from consumers lets applications be independent of their data. For example, a charting bean need not understand SQL or JDBC in order to access DBMS data. The InfoBus specification gives these beans a set of interfaces to share and exchange data at runtime.

After you have read the next chapter, you may wonder how the Infobus differs from bound properties. After all, bound properties are used to communicate data changes between two beans. The InfoBus adds the features needed for more dynamic data interchange. Bound properties are not really intended for things like sending an entire file from one bean to another. Infobus can step up to that task with ease. Infobus support is bundled with BDK 1.1.

Limitations of Beans

The Java bean model works well, but visual beans have been held back by nagging and seemingly trivial inconsistencies between the native look-and-feel and Swing’s emulation of it. Back in the last century, I filed several bugs with Sun on this topic for things like Java ignoring Windows control panel settings for system-wide font size and color preferences. Most of these bugs are addressed in JDK 1.4, but those incompatibilities, plus the JVM start-up time, has made Java a less attractive choice for GUI applications. And that has delayed the acceptance of beans for visual programming. Fix that JVM start-up time, Sun! It can be done by making the JVM always resident in memory, and threaded to handle multiple Java programs at once.

There are other limitations which Sun is also addressing. Java beans have limited ability to find out about their neighbors in the design tool. Sun added a concept called the “bean context” to allow beans to get more information. This support is placed in a package called java.beans.beancontext, and consists of ten or so classes and as many interfaces. Bean context improves the situation but doesn’t take it all the way yet. You still don’t have any way for beans to tell each other where they are located on the screen relative to each other. You want to know that information when you have a number of similar components (like number entry field) laid out on a panel and communicating with each other (as in a calculator or spreadsheet).

These drawbacks only apply to visual beans. The Java bean model has found more widespread use on the server side, as described in the next section.

Enterprise Java Beans (EJB)

Enterprise Java Beans (EJB) extend the Java bean component architecture to include the services and framework used in large-scale server-side applications. It is not part of the Java 2 Standard Edition, but is distributed with the Java 2 Enterprise Edition. A typical use of EJB appears in Figure 23-10. This shows where EJB components work in a multitier system.

EJB components in a multitier system.

Figure 23-10. EJB components in a multitier system.

So what is EJB all about? EJB is the specification for an industry-standard framework that supports the features common to most multitier systems. Enterprise-level multitier applications usually need system features like transaction support, naming services, and persistence. These features don’t add anything to your application logic, but they are needed to make it run correctly. EJB is a kind of framework that factors out and provides all these services in a standard form which is easy to integrate into your code.

In the past people had to laboriously reimplement these services over and over again as part of each application. Or implementors could fill their code with calls to proprietary libraries, using an application server such as IBM’s WebSphere or BEA’s WebLogic. This has the advantage of moving the system’s programming into a product supported by someone else, but it also has the disadvantage of tying the code to someone else’s API (and different application servers have different APIs).

The EJB specification does the same job as application server middleware, and indeed is usually implemented as a thin layer on top of an existing application server product. The situation is very similar to the way ODBC support mushroomed. Microsoft defined a single library called ODBC that was a C API for database access. Every database vendor in the world quickly provided a library that implemented ODBC access to its own products. If a customer decided to change database vendors, it was (in theory) as simple as relinking the code with the ODBC library from the new vendor. The EJB specification provides the same kind of common interface layer to application servers and services. EJB is middleware, where middleware is defined as “anything that connects a program to its data, such as a TP monitor, a database, or an OLTP (Online Transaction Processing) framework.”

Just as an applet needs a framework in which to execute (either a browser or the applet runner), EJB is run in a framework known as a container. The EJB container runs in an EJB server, and the EJB server is typically part of an application server (omitted from Figure 23-10 for clarity). An application server combines traditional online transaction processing support with the new distributed objects technology. The goal is to let programmers quickly assemble the pieces of code that change and put them in a stable framework that supports the common library services.

The Enterprise Java services form a layer over existing infrastructure services. Enterprise Java Beans technology enhances and simplifies popular systems such as CORBA or DCOM. By accessing the applications server through EJB, organizations can avoid yet another incompatible set of middleware technologies. Clearly, EJB is aimed at the largest kind of web systems with the most demanding requirements. Why not just use servlets? For some systems you can. But as soon as you need full transaction support, servlets can’t help you. You can get transaction support by using JDBC to access a database, which means adding another server tier to your system. EJB components are intended for systems that need to communicate across multitier environments. If you’re not doing this, you don’t need EJB.

Using EJB in an Application Server

An application server provides access to infrastructure services such as naming, directory services, transactions, persistence, and security. The EJB specification can be regarded as a single common, portable, Java interface to all the different application servers. Enterprise Java Beans allow programmers to add their applications logic in component-sized chunks.

Modern large-scale web software designs thus follow these steps:

  1. The only software on the client should be GUI-displaying software. All non-GUI code moves to the server. This ensures that code updates need only be rolled out to 30 servers, rather than 3,000 client desktops.

  2. Write the non-GUI business-logic code as EJB components. That provides the benefits of component software.

  3. Use an Application Server accessed via EJB for common framework services.

The result is portable, scalable, reusable, quickly-deployed web systems. EJB has been through a 1.0 release, a 1.1 release, and has now evolved to version 2.0, which can be downloaded from Sun’s website (see the URL in the Further Reading section). Table 23-1 summarizes details on a few application servers that support EJB at various levels.

Table 23-1. Some EJB Servers

Organization

Product

Website

Comments

JBoss Group

jboss

www.jboss.org

Open source EJB server. Allows technology deployment at zero capital cost.

Allaire Group

JRun

www.allaire.com

Free evaluation. From the company that developed Cold Fusion (ASP). Allows technology evaluation at zero cost.

Orion

Orion App Server

www.orionserver.com

The fastest J2EE-based application server.

IBM

WebSphere

www.ibm.com

One of the biggest supporters of Java, and this is its EJB application server.

BEA

WebLogic

www.bea.com

Software company whose main product line is focused here.

Borland

App Server

www.borland.com

Has an easy-to-use and easy-to-cluster reputation.

Netscape

iPlanet Server

www.netscape.com

Part of a suite of server-side software enablers. Created in partnership with Sun.

Pramati Technologies

Pramati Server

www.pramati.com

Well integrated with many server-side tools.

There are many more companies with application server products; Table 23-1 is to give you an idea of the industry-wide support for EJB. Most of the major vendors—including IBM, Oracle, Sybase, Netscape, and BEA Systems—have participated in specifying the Enterprise JavaBeans standard. These vendors are in the process of upgrading their products to be compatible with the latest revision of the Enterprise Java Beans specfication. When you evaluate these products, you’ll want to compare features like supported platforms, supported browsers, supported databases, EJB revision level, training aids, scalability, and availability of vendor consulting.

The only vendor of any significance that is not adapting its server products to support Enterprise Java Beans is Microsoft. The Microsoft Transaction Server (MTS) could be updated to support Enterprise Java Beans components. That would be useful for Microsoft’s customers, but it would not be useful for Microsoft itself. The Java portability message would undermine Microsoft’s strategy of tight integration to Windows-only. Instead of EJB, Microsoft is offering developers application systems based on its COM+ component model (now rebranded to .NET). MTS will provide a container system for .NET server components, with transactional and security services similar to those provided in Enterprise Java Beans servers but restricted to one platform.

EJB Summary

The first EJB containers have been implemented by mapping the component to the underlying vendor-specific infrastructure. These infrastructure services cover such features as distributed communication services, naming and directory services, transaction services, messaging services, data access and persistence services, and resource-sharing services. EJB provides a common interface to access them. Programs written using EJB can execute using any application server running on any operating system on any hardware.

Further Reading

You can find example beans, many with source, by doing a websearch or by visiting www.javashareware.com.

IBM is encouraging the spread of Java beans by offering a large number of them for free download at the alphaWorks JavaBeans repository www.alphaworks.ibm.com/alphaBeans.

IBM gives away an open source bean to access Excel spreadsheets on Windows only at oss.software.ibm.com/developerworks/opensource/excel/index.html. If you write your own bean to make an RMI connection you can siphon that Excel data from/to anywhere that has a JVM.

The Java Bean and EJB specifications are on Sun’s website at java.sun.com/products/javabeans/docs/. IBM also has some good online presentations on EJB, which you can find at www106.ibm.com/developerworks/java/library/whatareejbs/part1/ and www6.software.ibm.com/developerworks/education/ejb/index.html. Sun has a white paper on EJB for managers at java.sun.com/products/ejb/white/white_paper.html.

Sun has a three-part tutorial on Java beans on the developer part of its website at developer.java.sun.com/developer/onlineTraining/. You need to register with them to access this part of the website, but it is free to register, and you can choose how much spam you want them to send you. Unfortunately, I have yet to find a Java Beans book that I can recommend.

Exercises

  1. Take the “Tooth Fairy” (Duke) juggler bean that comes as a demo with the beanbox and add and connect two more buttons to the beanbox. One button should cause the juggler to hide itself (become invisible) and the other should cause it to become visible again. Visibility is a standard property of JComponent, so it is straightforward to connect button actions to that property of any JComponent in the beanbox.

  2. Connect the juggler bean “stop” and “start” actions to keystrokes in two textfields, instead of two buttons. When a character is typed in one field, the juggler should stop. A character typed in the other field should make the juggler animation resume. Note: You will need to read ahead in Chapter 24 to find the steps for getting an ordinary textfield into the beanbox. You don’t need to add any code to the textfield for this exercise.

Some Light Relief—Furby’s Brain Transplant

The smash hit toy of Christmas 1998 was Furby. Furby was designed by Califor-nian toy inventor Dave Hampton. Part of Dave’s motivation to develop Furby was a reaction against the previous “virtual pet,” the Japanese Tamagotchi. Tamagotchis are bland, inert lumps of plastic. Dave knew he could do better, and he created a fur-covered toy that sings, farts, and wobbles—sometimes all at once. No kid could resist that. In 1998, Furby sold over two million units, and they were actually being rushed by air from mainland China factories to satisfy U.S. market demand! Toys have a limited life. Furby was red hot in 1998, warm in 1999, and by 2000 you could buy one for $9.99 in Target.

Some Light Relief—Furby’s Brain Transplant

Furby is an animated doll about 7 inches high. It looks like a Gremlin from the 1984 movie of that name, and toy distributor Hasbro had to settle an infringement claim from Warner Brothers. Inside, Furby is packed with a rich assortment of devices. It has a microphone, a loud-speaker, infrared transmitter/receiver, light detector, speech generation chip, CPU, EEPROM, and RAM. It has a motor and various cams to animate ears, eyes, body, etc. Obviously, it was imperative to take one of these apart and reprogram it for more useful tasks.

Unfortunately, at some point in the past, Furby architect Dave Hampton had been rudely surprised by “potty-mouth Barney,” and he was determined that no one would pull the same stunt with Furby. There was another reason to make it difficult to reverse-engineer Furby: to prevent other toy companies from copying the technology. The world of children’s toys is (apparently) a cutthroat, rapacious, dog-eat-dog world, where intellectual property is Napstered on a daily basis, and only the strong survive. The main defense against reverse-engineering Furby was a brittle epoxy shell that completely encased Furby’s CPU, ROM, RAM, audio data, and the I/O interfaces such as driver transistors and an analog-digital convertor.

The epoxy made it impossible to clamp a logic analyser onto the CPU, read the bus traffic, and dump out the control program. It is impossible to chip or grind off the epoxy without destroying the components underneath. Certain U.S. government labs are equipped with the right acids and neutralizers to break into equipment like this. But I don’t know anyone at the CIA or NSA, and this didn’t seem like the right project to introduce myself. Furby’s software and sound data is not accessible for reading, writing, disassembly, replacement, or even examination. There are no exposed data/address buses, interrupt lines, or I/O lines other than those that directly drive the peripherals. Conclusion: Reprogramming Furby would require junking the existing CPU and fitting another CPU and memory—effectively, a Furby brain transplant.

So I issued the “Hack Furby” challenge from my website at www.afu.com (where I also keep the Java Programmers FAQ). The Hack Furby challenge offered a cash prize for the first person to reverse-engineer Furby or retrofit it with a different CPU. It was similar to challenges issued in the early days of aviation. Almost all the early aviation milestones—Bleriot’s flight across the channel, Alcock and Brown across the Atlantic, Lindbergh’s solo Atlantic crossing—were in response to a cash challenge, and I felt sure that computer engineers were no less motivated. This was no easy task and almost a year passed by before a winner claimed the prize.

The challenge was finally met by Jeff Gibbons, a talented Canadian computer consultant working for Motorola. Jeff chose the Intel 8051 processor to drive Furby because of the vast amount of free support tools and low cost hardware available. The 8051 is an 8-bit CPU that’s been around for about 20 years, and that fully meets the time-honored Intel processor tradition of “ignore all design suggestions from the software guys.” Jeff architected and built replacement circuit boards that fit into the existing space in Furby, after you junk the epoxy-protected boards. The new circuit boards carry the 8051, EEPROM, 1Mbyte RAM, an RS232 port, a power regulator, an amplifier, a digital-analog converter, and tons of support hardware. This was an incredible achievement on Jeff’s part. He essentially designed and built a complete general-purpose computer system in four months of evenings and weekends.

After Jeff produced the working hardware, I wrote the first draft of the “Furby Programmer’s Reference Manual” which is on the CD with this book, and online at Jeff’s site at www.furbyupgrade.20m.com/. For a while, Jeff was also selling kits from that site. For well under $100 you can convert your Furby into a TV remote controller, a speaking clock, a pocket calculator, or anything else that will run on a 20MHz processor and a little over 1Mbyte of RAM. Furby can be programmed in assembler or in C, and you download the program through a tether cable to the serial port on a PC. Clearly, the next step is to get a JVM running on Furby, and bring up Java 2 Micro Edition on Furby. Put a telnet connection on the serial port, and we’re really cooking.

For legal and policy reasons I can’t show you a picture of a modified Furby in this book. You’ve no idea how easily those toy moguls take offense. But if you hustle over to www.afu.com/furby you can feast your eyes on all the “stripped and re-chipped” Furbypictures that anyone could want.

This whole project was done under GPL, the Gnu Public License, which means we openly published all the schematics, results, software, etc. Some of this material is on the CD, and the rest is on Jeff’s website. The goal is to enable volunteers to carry the project forward. So if you know a lot about embedded systems and are trying think of what to do with all your plentiful spare time, perhaps Java-powered Furby could be in your future.

Some Light Relief—Furby’s Brain Transplant

The last word should come from Furby himself. I did the FCC compliance testing on the Furby prototype “borrowing” some time in one of the hardware labs at work. FCC testing measures the amount of electronic interference that a product generates. It has to be lower than certain limits to comply with FCC rules. In the photo here, Furby is on the lower TV screen, on a table on a large turntable, executing all his motions and new vocabulary. The upper TV screen shows the very sensitive “bow tie” antenna 6 meters away which sweeps for electromagnetic radiation as Furby revolves. The oscilloscope on the right graphs the radio fre-quencies that Furby transmits in every direction. There was a lot of unwanted radio wave leakage, known as noise, coming out of hacked Furby. The chief engineer of the lab came in unexpectedly, listened to Furby chirping and jabbering away, and sized up what I was doing in his lab. Then he glanced at the measurements (Furby failed FCC parts A and B) and grunted, “Noisy little critter, ain’t he?”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.201.47