Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Getting All Your Beans From One Bag
Getting All Your Beans From One Bag

Imagine this scenario: you've written all the appropriate interfaces and implementations for an EJB and now it's time to use it in client code. First you get a bean reference. Everything is simple enough: use JNDI to get the home interface, call a create method on it and catch all the possible exceptions. Voilá, a usable EJB reference. No big deal. However, after creating the bean and looking at the number of beans you want to use, you realize you'll be doing the same thing over and over again. You shake your head and say, "There has to be a better way to create these objects."

Fortunately, there is. Polymorphism and the reflection API provide a powerful and flexible mechanism for obtaining EJB references.

Without using reflection or polymorphism, you'd obtain references something like this:

try {
// Use a helper method to get the JNDI context to use for lookups...
//
InitialContext context = getJNDIContext();

// Then lookup the bean home interface and create the bean
//
String jndiName = "com/zefer/util/MyBeanHome";
MyBeanHome myHome = (MyBeanHome) context.lookup(jdniName);
IMyBean myBean = (myBean) myHome.create();

} catch (...){
// Catch all the exceptions...
}

Granted, this isn't the most complicated code in the world, but it can lead to problems with code management. What happens when you want references for several different beans? If you use casting, as in the example above, your code would be different for each bean since you have to hard-code the objects you're casting to. And what does the code look like if you want to use several different create methods? Again, you'd need separate code segments for each situation. The upshot is, you'd have similar-looking code. No matter how simple the code is, large amounts of duplicate code can be extremely difficult to manage.

This particular situation rings a bell for OO analysts – it's similar to a specialization relationship or creational operation that's most likely covered by a design pattern. Indeed, several design patterns directly address this situation: Strategy, Builder and Factory, to name a few. Some patterns, such as the Builder pattern, appear to be overkill as the differences in code are so slight and the number of situations so varied that the application of this pattern implies a large number of trivial classes. This large number effectively changes the nature of the problem to one of object management rather than code management, so it doesn't really improve the situation. Other techniques, such as delegation, provide an easier way to manage the code. Using delegation, every single procedure that gets a reference would be hard-coded in; therefore it's not very flexible in its application.

Even a strict application of the Factory pattern may leave a lot to be desired in terms of reducing the complexity of the code and the design. Thus the straightforward application of classic designs needs to be rethought in order to streamline the design and code for obtaining EJB references.

Luckily, the power of polymorphism and the Java reflection API come to the rescue. The latter provides the ability to invoke arbitrary method calls on arbitrary objects (as long as that method exists for that object, of course!). In our situation we want to invoke arbitrary create methods for enterprise beans. The concept of polymorphism comes into play in the client code after we've created EJB objects and want to cast them to an appropriate bean type. With these two items in hand it's possible to write a single class with a few methods that can handle every single creation scenario for any bean.

For this article I've constructed a class named EJBFactory using Netscape Application Server 4.0 and its EJB 1.0 implementation. The responsibility of the EJBFactory class is to return EJBObject references (see Listing 1). This class contains three fairly straightforward methods:

  1. setJNDIFinder(): Sets a reference to an object that provides a wrapper around JNDI contexts and lookup services
  2. getHomeInterface(): Gets a reference to a particular home interface for a bean
  3. createBean(): Creates an EJBObject reference
The first two methods are simple, containing little (if anything) that's surprising. The third method, createBean(), does the bulk of the work despite its deceptively diminutive size.

The createBean() method creates beans using the same process outlined above, namely, the method first obtains the home interface from JNDI, then calls the appropriate create() method on the home interface. For this method the first parameter to the method specifies the particular home interface to retrieve from JNDI. The appropriate create method is defined as the one that matches the signature of the objects in the Vector parameter to the method. To get the proper create method for the EJB home interface, the createBean() method first reflects the Vector parameter to get the classes of the object it contains, then reflects the home interface returned from JNDI to get a reference to the proper create method. After getting this reference, invoking the method to create the bean is a trivial task.

Using reflection in this manner allows the createBean() method to create any type of bean using any type of create method. After creating the bean, the method still has to return it. To work with disparate types of beans, the createBean() method relies on the fact that all the remote stubs for EJBs inherit from the EJBObject class. This allows the client code to use the object normally after either downcasting the returned object (for EJB 1.0) or calling the javax.rmi.PortableRemoteObject.narrow(...) method (per section 5.9 of the EJB 1.1 specification) on the object. Thus, by exploiting polymorphism, the client code can access the returned bean just as if it had been created using a more verbose method.

There are three main objections with this approach:

  1. Reflection may be an expensive operation, so we have the classic flexibility versus performance trade-off. This trade-off is something that may be answered only on a situational basis.
  2. The createBean() method throws a number of exceptions, thereby begging the question of whether this method of creating beans reduces duplicate code. However, the creation of a small wrapper class to handle these exceptions and throw application-defined exceptions solves this problem (see Listing 2).
  3. Creating beans in this manner doesn't handle inheritance in the bean-create calls. In other words, if you try to use a create method that has a parent class as its signature, with a child class as the actual parameter, the bean won't be created appropriately. Unfortunately, I haven't found an elegant way around this final objection as it appears to be a limitation in the reflection API.
In spite of these objections, the EJBFactory class brings a number of benefits. It greatly reduces code duplication, making code more compact and easier to maintain, extend and debug. Creating beans is extraordinarily easy since the code consists of a single method call and an associated catch block (see Listing 3). Furthermore, the flexibility of the EJBFactory allows you to easily extend an EJB-based system to include new beans without having to modify any code. Now that's a scenario worth imagining!
About Nathan Cuka
Nathan Cuka is a senior software engineer for Zefer Corp.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Enterprise Open Source Magazine Latest Stories . . .
Apache Deltacloud, the Red Hat-contributed ReSTful API that abstracts differences between clouds so services on any cloud can be managed – provided of course there’s a driver – has graduated from the Apache Foundation’s incubator and is now a full-fledged Top-Level Project (TLP). The...
With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON Featured Whitepapers
ADS BY GOOGLE