JavaRanch Newsletter Articles in this issue :
From the editorJohannes de Jong
Printable Version
The Coffee HouseSolveig Haugland
Printable Version
Meet the authors Kathy Sierra & Bert BatesJava Ranch
Printable Version
Generating dynamic output with WebMacroMatthew Phillips
Printable Version
Implementing Business Logic in J2EE Applications Simon Brown
Printable Version
Movin' them doggies on the Cattle DriveMichael Matola
Printable Version
Book Review of the MonthThomas Paul
Printable Version
Book Promotions For MayThomas Paul
Printable Version

From the editor

Johannes de Jong, May 2003

This is the first newsletter with two articles I hope will become regulars.

The first one is an interview with an author of an IT related book. This month Kathy and Bert were kind enough to answer a few questions for me. They are the co-authors of the now legendary, certification book Sun Certified Programmer & Developer for Java 2 Study Guide . Their next book Head First Java will hit the streets at the end of May. As I played a small role in its creation, as a test reader, some of my questions are directed towards their new book. I must say that some of their replies took me by surprise, I wonder if others will have the same reaction.

If there are any authors out there that you would like to have interviewed drop me a line, don't forget to add the questions you want to ask them.

The other new article is by Solveig Haugland, it is called The Coffee House, rumor has it that she does her best work in a real coffee house somewhere in downtown Denver. Though this month she writes about J2EE, she has an open license to write about absolutely anything she wishes. So who knows maybe next month she might explain her reasons for writing about Dating Design Patterns,. Thanks for being prepared to write a monthly column for us Solveig.

If you'd like to see your name in print please drop me a line and please if you like a specific article let the author know, it encourages them to write more, which makes my life soo much easier.

I'd like to end this by thanking all the other contributors to this months newsletter, actually I'd like to thank the contributors to all the previous newsletters as well. My thanks to all of you.


Return to Top
tchmay.htm

Welcome to the Coffee House The Coffee House

by Solveig Haugland


Welcome to the Coffee House

Here at the coffee house, we pride ourselves on being a great place to relax. The Coffee House is the Java Ranch on the weekend.  If you’ve spent a long three months on a cattle drive and you’re exhausted from bit shifting and saddle sores, or if you’re new to the Ranch and want to get started in a slow and friendly manner, we welcome you and urge you to sit down on our big comfy couches with a nice cup o’java. 

We still talk about Java but we don’t have long intense discussions about pass by value or get hot and heavy about whether a pattern is really just a Strategy or Front Controller. We just gab about the real basics of some Java topic or other, just getting at what’s actually important without really doing any code. And taking time to sip our coffee and digest one or two of Curly’s famous baking powder scones.

This Month's Story: What in Tarnation Is J2EE?

Ol' Sid Sid, the cowpoke who ranches that huge spread down south o’ Deadville, and Zeb, the sheriff, and a bunch of other hands from around the county were sittin’ around, sipping their coffee silently in true cowboy fashion and reading the comics. Lacey and Brenda were behind the counter, making a rucus with that new fangled frappulatte machine.

Sid put down his paper and said, “All right. I am going to admit it. I know how to write good solid Java code til the cows come home, and I often do. I write it good, and sometimes the city folks even say it’s elegant. But what the heck is this J2EE thing and why do people want it?”

A few of the other cowboys heard him and snickered. But when he stood up and said, “All right, then one of you explain it to me!” and shot a hole in the roof, they shut up and slunk down a little farther in their chairs.

Zeb snorted. “That’s pretty much the deal, Sid .Everybody talks about J2EE but nobody knows anything about it. You want I should give you the high points?”

“That’d be pretty neighborly of you,” replied Sid. “I love my Java ranch and I don’t want to have to sell out and move down to one of them little NETranches if I can stay and just bring in a little J2EE blood.”

“All righty. And you braggin’ no-account cowpokes can all listen up too, since I can tell you don’t know nothin’ about 2EE neither.” There was silence from the othe end of the room.

Zeb Asks Sid a Couple of Questions

Zeb settled himself a little lower under his hat. “Sid, you remember that project you had the last few years where you had to write that Web application for buying saddles over the Internet?”

Sid winced. “I sure do.It was awful, it took forever, I don’t think I did a very good job, and I was darned lucky to get paid after they went bankrupt. I had to write all sorts of code to deal with making sure people’s credit cards didn’t get stolen from hackers. I had to make sure that all the info about the saddles and saddle bags the customers wanted got to the saddle store, since these guys get pretty mad if they order one of this Big Jim saddles but they don’t get the right saddle blankets to keep their butts from blistering right off.”

“Oh, and that ain’t all. I had a terrible time getting the program to run right during the Saddle Soap festival when everyone and their horse was ordering saddles. I had memory problems and CPUs grinding to a halt when more than a few cowboys were ordering at a time. It was downright humiliating.”

Zeb nodded, grinning. “You were lucky to get out alive. And think about this. What if all those cowboys in China and Utah and England had wanted to order saddles, too? Was your security system and your data integrity system good enough to handle that? We know your resource management system sure wasn’t!”

Sid winced. saying “Don’t rub it in, Zeb. Of course they weren’t good enough for that. But it’s hard to write a good secure online application; security is incredibly complicated. And making sure that the data integrity is there, so people’s orders go through together, and so if  their horse trips over the power line halfway through the order and leaves them all paid up without the message ever getting to the saddle warehouse that they should ship out the order, well, that’s really hard.  And then of course, yes, the third one, resource management to make sure none of them little objects were using memory they shouldn’t and to make sure there’s enough CPU power all the time, well, I admit, that’s just about impossible. And it took me five years and a whole bunch of other ranch hands to do the project.”

Zeb downed the rest of his coffee and got up for more. This explanation was usually about a one-cupper, but Sid had gone on about his project a little longer than usual. “That’s right,” Zeb said as he filled up his cup and added a lot more cinnamon and cocoa than you’d expect from such a grizzly old sheriff. “It’s really hard.”

Sid looked at him and boggled with frustration. “What the heck are you doin’ to me? I ask you to explain J2EE to me, and here you are, just makin’ me go over my failed projects and limitations in public!”

“Calm down,” chuckled Zeb. “It’s OK. You’re not supposed to be able to do it. It is really hard to do security, and data integrity things like transactions, and resource management. So wouldn’t it be nice if you could just buy some software that could do it for you?”

Sid Finds Out That J2EE Gives You Stuff, and You Just Have to Hook Your Application Up to It

Sid stared at him. “You’re not telling me....you are telling me. Is that what J2EE is, a program that takes care of all that really hard stuff?”

“Yep.”

“You’re telling me that instead of going through hell in a handbasket for five years and losing all that money, I could have just gone out and bought a J2EE—a J2EE— ”

“Server,” Zeb supplied.

“A J2EE server, and I could just tell it, OK, you J2EE server, when this order starts, you make sure it’s a transaction so that everything that goes together stays together? And if the order gets interrupted, you just pretend it all never happened?”

“Yep.”

scarecrow “And you’re telling me I can write a little code for this J2EE server just saying, what, Make this little ol’ application secure? Like a big scary robust extensible scarecrow all around the edge of the cornfield of my application?” He had gotten up on the bar in his excitement and was walking around, waving his hands and splashing his coffee in his excitement.”

“Yep.”

“And you are telling me,” Sid stopped for breath and stood up as straight as he could, “that I can just tell this J2EE server, hey you, manage my resources so my application doesn’t grind to a halt every time there’s a bunch of people who want to order saddles all at the same time?”

“You know the answer to that,” Zeb grinned. “Yep!”

Sid was already in a dead faint, though, slumped over Lacey and Brenda, and didn’t hear him.

Sid Wakes Up and Finds Out About Beans and Other Things

They slapped ol' Sid for a while until he woke up, then they slapped him a little more just to be sure they'd done it enough.

"Just one more thing," said Sid. "How does it all work? Do I just write my normal program like I normally would and then say, Hiyo server, away?"

"Well, not quite," Zeb told him. "You usually use beans. Not like those charcoal black hard thing Curly serves for dinner, but special little J2EE  pieces of code. It's still Java, you just write them according to a few Enterprise JavaBean rules. That's the core part of your application. Then you stick it next to your J2EE server, you put a kind of a to-do list or address book deployment descriptor file in with it to help the server figure out what to do with those beans, and it all runs. All the people ordering saddles, for instance, get sent to the server first. The server says, say, hey Bean42, you go do such and such. And when all the beans are done doing their business, then the server stores the results in the database, or tells the customer something."

"Just to be clear, most of the time you call this server thing a container. The server's what you ask your storekeeper for, but the container is what does all this management for the beans."


"Dang," said one of the scruffy lookin' cowboys in the back. "Sounds like this container thing is kind of like Ella down at the Massage Parlor. She's the one who manages what goes on, and you don't do anything with them young ladies if you don't talk to her."


"Well, Zeek," said Zeb, "I might not describe it that way but you're pretty much right."

"I would like to add, though, that there's actually two kind of Ellas in this picture. You got your beans doing your core important business stuff like calculations and making sure credit cards are good, and they've got an Ella. But what about all this ruckus going back and forth across the Internet from your customers, up to the beans? What about all the stuff you have to do to show your customers pretty pictures and lists of your saddles and get their orders all collected and sent to your beans to do their processing? Well, you use a couple things called JSPs and servlets. JSPs are the pretty up front pieces of code that mostly do HTML but a little Java too, and servlets can do a little HTML but mostly they do some harder core stuff, either processing them JSP requests or sending info on to the beans, or both. And just so they don't feel left out, the JSPs and servlets have a container that takes care of them too. Another Ella from the Massage Parlor."

"So you got a customer saying Send me that rawhide saddle, and that request just goes to the Web server which is kind of dumb and just does simple things. Kind of like Red who sits on the edge of town and says Hi, welcome to town, the Massage Parlor is north and the coffee house is south. Then the web server passes the request for the rawhide saddle to the web container, who does all sorts of handling and managing, messing around with the JSPs and servlets. Then for really hard core processing it goes, whoop, one more step on to the EJB container, the beans get into the action, and then finally the order gets sent, and a message comes out the same way it went in saying thank you very much, we hope you enjoy your saddle."

The Cowboys in the Back Find Out About How J2EE Prevents Vendor Lockin

One of the lame ol’ cowboys in back piped up. “But I heard J2EE was really hard. This sounds real easy. You sure you’re givin’ us the straight story?”

“Well, who’d you hear sayin’ that J2EE was hard?”

“Heard it from a weaselly little fellow who came through last week selling patent medicine. Said his name was William Door.”

“Yeah, well, we’ve seen him around these parts branding our cattle with his mark and doing all sorts of other stuff that woulda gotten a guy strung up twenty years ago. Now think about it. Why do you think Sid here fainted? Was he afeared of writing J2EE stuff or was he just so mad and amazed that he did stuff by hand, badly, that he coulda just bought? It’s cuz of the second one. Writing the stuff that J2EE does for you is one heck of a lot easier than hooking up your application to J2EE servers.”

“And yep, it’s true you need to write your online application a certain way to make sure your J2EE server can grab onto your application at the right points and give it security, data integrity, and resource management. Kinda like cuttin’ the right holes in your house for the windows at just the right spot, or settin’ you and your cowboys up just right so the cows head straight into the corral. But you know, ain’t nothin’ easy in life and you know that if you use your J2EE server, all those services are done right. All you gotta do is write good code to let it all happen.

“J2EE ain’t the only server, by the way, that can do these kind o’services. But think about this. You gotta buy your server from somebody. What if the server turns out bad? What if your storekeeper who’s selling you your J2EE server heads out to Alaska for the gold rush or just starts being a real nasty sort o’guy, you can go get yourself a whole nother J2EE server and it’ll work pretty much the same way. Ol’ Willam Door can’t say that.”

“You can get a bunch of servers that will do these things for you, but if you’re the kind of cowboy that doesn’t want to be fenced in, you want a J2EE server.”

And the Whole Thing Ends on a Musical Note

At that point, the Sons of the Pioneers came in and invited us all to join them in a rousing chorus of  “Don’t Fence Me In,” and we cheered and sang and waved our coffee cups around. And then we carried Sid back to his house, left him with a few links to J2EE servers like WebLogic and SunOne, and went home to sleep off the caffeine before dinner.

A few of the cowboys eventually tracked down Zeb, and he told them that if they wanted to lasso a better handle on how to do J2EE, they should walk down to the corral and see Simon "Lefty" Brown, check out the article he wrote this month, or go to his Introduction to the Java 2 Platform, Enterprise Edition (J2EE) article in the October 2002 newsletter.


Solveig Haugland is an independent writer and trainer based in Colorado. She is currently developing books of key Java and J2EE concepts and technologies, and her existing books include the “StarOffice 6.0 Companion” and the “OpenOffice.org Resource Kit” user’s guide and CD. You can contact her through her web site, www.getopenoffice.org, or at solveig@getopenoffice.org.



Return to Top

Meet the authors Kathy Sierra & Bert Bates

Java Ranch, May 2003
 

Java Ranch: When I read a book I often wonder what the author is like "outside" his/her book, the things he/she likes. So to start of I'd like you to tell me what is your favourite:-

Book:
Kathy: Sun Certified Programmer for Java 2 Study Guide, oh, and Lord of the Rings
Bert: Hyperion
Kathy & Bert: Most Recent books for both of us (we both read the same books at the same time): Down and Out in the Magic Kingdom (Cory Doctorow), Pattern Matching (William Gibson)

Movie:
Kathy: Fifth Element, Donny Darko, Mind Walk
Bert: Indiana Jones (first one), 2001, A Shot in the Dark Recent favorites: Amelie, About a Boy, The Orchid Thief
Both : X-men 2, and Con-air (yes they actually admit liking Con-air. editor)

Type of music:
Kathy: space age bachelor pad, British indie
Bert: bluegrass, Grateful Dead, Beethoven

Java Ranch: What motivates you both to write a book?, To me as an outsider it seems like a lot of very hard work, for very little financial gain, so why are you punishing yourself.
Kathy & Bert: We like the dress code. That's the main thing. After that, two things motivate us:
A) Freedom and flexibility. We like to be able to work wherever we want, whenever we want. For example, Solveig Haugland (another writer), Bert and I rented a house next to the ski resort so that we could work and ski. We were all on deadlines, but it was just nice to have that flexibility, even if we could ski only 3 or 4 hours a day. Then we'd come back and work at night. Bert and I both want to not be tied down to any particular city (or country), even though we live in one of the most beautiful places (Boulder Colorado).
B) The same reason I started javaranch. Bert and I have both done a lot of teaching, but sending a book out into the world lets you help a LOT more people! With the cert book, we love getting emails from people all over the world telling us they passed the test. And we have a special mail filter that can detect emails from readers who don't like the book. So we don't have to read those.
C) OK, three reasons -- we've planted subliminal messages throughout the book, and we're slowly brainwashing an entire community of techies, one certification candidate at a time. Bending them to our will.

Java Ranch: How did the winning team "Kathy & Bert" get started? What made the two of you decide to write books together?
Kathy & Bert: We both have a background in AI; we both spent a lot of time studying cognitive science, knowledge engineering, learning theory. We both have a passion for trying to make things more understandable. And honestly, we both have been frustrated with how many badly-written programming books are out there. Peter van der Linden, author of the "Just Java" books, calls what so many authors do the "clear only if known syndrome". In other words, the book is technically accurate, and makes sense, but only *after* you've already learned it. How do you get your foot in the door? So Bert and I were always complaining about so many Java books and course materials, so finally we decided we better do it our selves or shut up.

Java Ranch: Most authors have a regular job and write at night and on weekends. Is this the case with you? Tell us a bit about a typical day in your lives. How do the two of you write as a team, together in a room or virtually?
Kathy & Bert: We both left our day jobs shortly before the certification book came out. When O'Reilly offered us a new series, that required a big commitment. So now we are both part-time contractors for Sun, mainly with certification, to help us stay alive. The romance and charm of the whole 'starving writer' thing just doesn't work for us, so we both work on other paid projects about 25% of the time. As I'm writing this, Bert is about 8 feet away, under his desk. I'm sitting in this huge -- and I mean HUGE -- bean-bag chair, which is where I usually work. We both have Apple G4 Titanium laptops (they rock, we even run J2EE on them). Sometimes we work at a cafe, meeting up with Solveig, so we can all share ideas or rip each other's latest chapter to shreds.

Java Ranch: What role does each of you play in your "team"? Who is the creative whiz and who the programming wonder.
Kathy & Bert: Bert is my personal writing slave. So, I actually don't need to *do* anything. But when he breaks out of his restraints, we're pretty much equal. We both do everything: brainstorming ideas, writing content, writing code.

Java Ranch: Your next book, Head First Java, is totally different to anything I've ever seen in a computer book. What made you decide to break new ground with its format / style?
Kathy & Bert: This gets back to our background. We both know too much about how the brain works to be satisfied with a traditional text-based book. We did the best we could with the certification book, but the publisher constrained us to a strict, text-only (almost) format with no control over the page layouts. So with O'Reilly, we said, "What if there were no constraints about what goes inside the book and we could do *anything*?" And that's what happened. We took every scrap of brain/learning research we could find and applied it to the format of a book. Fortunately, Tim O'Reilly was a real fan from the moment we sent him a few sample pages, so he encouraged us to go all the way. The editor was skeptical at first, as a lot of people are, but we gave it to some key people in many fields. The book has an endorsement from Ken Arnold, who co-wrote the "Java Programming Language" (with James Gosling). And we have a few other alpha geeks and learning gurus including the Director of User Experience at IBM, a professor at Standford teaching AI, and a guy who used to run a division of Xerox Parc (the guys who created Smalltalk).

Most text-based books are based on a model of learning that's several hundred years out of date -- the notion that the learner is a passive receiver of words. Some books claim to duplicate the classroom experience, but they don't, and most classroom instruction suffers from the same bad model anyway. The bottom line is that the brain learns and remembers most that which causes you to *feel* something. If a large tiger jumps out at you from behind a rock, it takes just one time for your brain to remember it. Why? Neurobiology. Because your body is pumping out chemicals, and those chemicals are part of what tells your brain, "This is REALLY important!". On the other hand, when you read a dry, dull text book, even if the subject truly interests you, your brain doesn't know that. You register nothing of interest on the emotional scale, so your brain says, "Obviously THIS is NOT important. So I won't bother processing it deeply or storing it since there are more important things out there, like tigers." There are ways to *trick* your brain into thinking that the content IS important, but they're tedious. For example, if you keep \ studying the same thing repeated times, your brain says, "OK, there's no chemistry here, but he keeps reading the same thing again and again, so I guess it must be important." Who has time for that? So we take the other approach, to work with what your brain is tuned for. To turn up the dials enough to keep your brain interested. It's still not the ideal way to learn, but it is far, far better than a traditional dry text book. And we use almost 50% visuals, because humans are also tuned to get information visually, and can understand and process pictures much more quickly and deeply than words alone. The picture is worth a thousand words is really true, as far as your brain is concerned.

Java Ranch: What most people would like to know after they read Head First Java, at least I think they would, is how much more work is a book in the new "Head First" format as apposed to the "normal" format. And where do you guys get the pictures for your book. Heck I'd be very scared if I saw the two of you with a digital camera.
Kathy & Bert: Yes, be afraid. Yes, a Head First book does take more work to produce, because every single page is hand-crafted. No two pages are the same, and there are graphics of some sort on nearly every page. The graphics come from three sources: a) custom art (the hand-painted things for the Java-specific content, kind of like whiteboard drawings on steroids) b) photos that we take, and process in Photoshop c) stock photography and art libraries (where you can purchase art, for commercial use, that is royalty-free)

We are working on bringing other authors up to speed, so that it isn't just US making them. The first book is not even out, and people at O'Reilly are asking where are the other Head First books? They want as many as possible, as quickly as possible, but it is REALLY hard to find people who can -- or even want -- to attempt this. For a Head First book, O'Reilly calls it an "audition" rather than a "proposal" that prospective authors must go through. But if anyone is interested in possibly working on a Head First book, with us or with someone else, write to me and Bert! Right now, we're doing a book for the new EJB Certification that comes out in August (the exam and the book). And at least two others are in the works or being discussed.


Return to Top

Generating dynamic output with WebMacro

by Matthew Phillips

I've been thinking about writing an article on WebMacro for a few months now, but I wanted to do something different from the typical web application. I've always hated writing JavaBeans, so when I read Paul Wheaton's request for a bean generator I decided to prototype one with WebMacro. The article is about the prototype, but I've been working on the generator since then.

WebMacro is a templating engine. Simply put, you create a template that combines static output with accessors to java objects. In your Java code you can combine the objects and template to create your output. It's almost too easy. The first thing I need for a JavaBean generator is a template. Since different companies use different style guides, having the template externally defined is a big help.

The template

Figure 1 is the template I decided on for my coding style. The first thing you might notice are the way variables are defined. Anytime WebMacro sees a $ followed by a word, it treats it as a variable. It checks the context, which maps variables to values, for the variable and replaces it in the template with the value from the context. Dot notation can be used to access properties of Java objects, so property.Name is the same as if your java code were calling property.getName().

Figure 1 also shows how loops can be used to access each member of an array. I could have used curly braces instead of #begin and #end to show the beginning and ending of the loop. Since I am outputting Java code, I chose to use the latter so that it would not be confused with the braces you expect to see in the output. Since curly braces can be used for loops, I had to escape them where I wanted the template to write them out.

The bean generation code

Figure 2 shows the beginnings of my code generator. For simplicity, I hard coded the objects that I would use in the template, but these could have come from an external file or database.

WM is the class that manages just about everything WebMacro does in stand alone mode. If you were working on a web application, you could extend WMServlet which would do most of the work for you. After instantiating my manager(webmacro), I can create the context that I will use to hold the information needed to populate my template. The key for each item I place in the context matches a template variable name in Figure 1.

After I finish populating my context, I use my manager to instantiate my template. WebMacro will search the classpath for the template. FastWriter is an output class packaged with WebMacro that is used to write the template to output. In this case, I am writing out to a file called Account.java. I then pass the writer and the context to the template to write it out. If you have the template and WebMacro in your classpath, then you should end up with a file called Appointment.java that you can compile and use as a JavaBean.

The primary use for WebMacro is in web applications. To download WebMacro or to find more information, check out WebMacro.org.


Return to Top

Implementing Business Logic in J2EE Applications

Simon Brown, April 2003

Introduction

My previous two articles in this series have provided a general overview of the Java 2 Platform, Enterprise Edition (J2EE) and a more detailed look at the technologies contained within the web-tier of the J2EE platform. Using these technologies allows us to build scalable web-based interfaces for our applications but one question still remains. Where should the business logic reside? This is the subject of this article.

What is business logic?

Business logic is an often overused term that can be used to describe many things and the definitions are typically very verbose. However, a general definition is that business logic is logic that is related to and can be described in terms of the domain in which the application is operating. Of course, this is a rather idealistic definition, but essentially what this says is that business logic is related to the information being manipulated within the application rather than, for example, the logic associated with any of the external interfaces such as the user, the database, etc.

As an example, consider an e-commerce site such as Amazon. The domain in which the site operates is the online sale of products such as books, CDs, DVDs, and so on, while the business domain includes concepts such as products, customers, addresses, etc. Here, business logic might involve the process of a customer buying a product, applying discount rules and so on.

How and where is business logic implemented?

Before the introduction of J2EE and, specifically, Enterprise JavaBeans, business logic was implemented in several ways. The first of these was that business logic was embedded within the user interface code, alongside any logic required to present information to the user. While this worked and still works, it does lead to systems that are fragile when it comes to modifying the way that the system works. Also, changes to the user interface code can easily affect the way that the system behaves. At the other end of the architecture, business logic is often tied to the database being used, perhaps being implemented within stored procedures or triggers. Wherever it is located, mixing business logic with application specific code is not good for aspects such as reusability and maintainability.

A natural progression from here is to encapsulate business logic inside reusable classes or components. With Java, a possibility is to build JavaBeans - reusable software components that can run within any Java virtual machine. The benefit that this provides over embedding business logic alongside the application specific code is that the application is much easier to maintain. Any changes to the business processes realized by the system are easy to find and easy to change. In addition to this, business logic is now reusable both within the application and within other applications that operate within the same business domain. In other words, more than a single development team within the same company or business area can take the same code to reuse in their application. However, with the introduction of J2EE, a new mechanism for wrapping up business logic is available - Enterprise JavaBeans.

What are Enterprise JavaBeans?

Enterprise JavaBeans (EJBs) are reusable, serverside components that are designed to be executed within a J2EE application server. Unlike classes that you instantiate to use, EJBs are remote components that live inside the application server.

There are three flavours of EJB ? session, entity and message-driven beans. As we saw in my first article, session beans are used to wrap up business logic, entity beans are used to represent persistent information and message-driven beans are used to provide an asynchronous interface into the functionality provided by an application. From the various flavours of EJB, we can see that session beans are suited to encapsulating business logic but why is this so?

Wrapping up business logic in Enterprise JavaBeans

Essentially, session beans are simply reusable components that can be used to contain logic rather than data. Of course, this doesn't mean that session beans can't contain data, it's just that the usage pattern associated with session beans is that an instance is obtained and methods are invoked. This is similar to the way in which JavaBeans are used. You create a new instance and then invoke its methods.

What makes EJBs different from regular JavaBeans?

This is one of those questions that keep coming up time and time again. After all, both JavaBeans and Enterprise JavaBeans are reusable software components that can be used to wrap up data and any code that operates on that data. However, the key difference is that EJBs are an enterprise, serverside technology.

Okay, because regular JavaBeans are written in Java, they can be and are used on the server and within J2EE application servers. After all, JavaBeans can be used anywhere there is Java. But, with JavaBeans, you have to create a new instance before using it. Enterprise JavaBeans on the other hand are components that live inside the application server meaning that you can't just instantiate them to use them. Instead, you must look up a reference to an EJB through a directory service called the Java Naming and Directory Interface (JNDI) that gives you a reference to a live component running inside the server.

What benefits do EJB provide?

Since EJBs are remote components, there are several characteristics that can be beneficial, depending on the circumstances and the application being developed. First of all, EJB makes it easy to build distributed, component-based systems. This means that any code written inside EJB will be executed on the server rather than on the calling client, taking advantage of the power that is available on the server. In addition to this, having a central place for executing business logic again improves the reusability and maintainability of that logic. In any organization, there may be many applications that provide implementations of the processes operated by the business. Adopting EJB means that each application can simply make use of that centralized business logic. Now you have the ability to reuse deployed components rather than just reusing code.

From a more technical perspective, EJB provides an architecture from which to help build scalable applications. Although you write your business logic as usual, at runtime the J2EE application server can choose to provide a pool of EJB instances to service incoming requests rather than a single instance. Also, EJBs can be clustered across multiple J2EE application servers for truly a truly distributed and failsafe deployment.

Finally, another important benefit is that of transactions. Transactions are an integral part of most business systems and the ability to mark a batch of work to be a transaction is vitally important for the integrity of business data. These ensure that all of the work is done and committed or it is not done and the transaction is rolled back. Encapsulating business logic inside EJBs makes it very easy to provide visible transaction boundaries, allowing complex business processes to be implemented correctly.

Are there any disadvantages to using EJB?

With every benefit there is a disadvantage. We've already said that EJBs are remote components that live inside a J2EE application server and this itself can be seen as a disadvantage. Traditionally J2EE application servers were complex and expensive, although with open source efforts such as JBoss and the commoditization of the application server market, this is not seen as such a big issue anymore. However, the lifecycle of EJB instances is managed by the application server and therefore there is always going to be a slight overhead to account for this. However, for this overhead you do get free transaction management, failover, pooling, clustering and so on.

Are EJBs complicated to build?

To be honest, I've never found the Java code for EJBs to be complicated to write. What I, and many people, do have a problem with are the deployment descriptors for EJBs. These are just XML files that describe the way in which that EJB component is deployed and how it operates when running inside the J2EE application server. Admittedly, it's not a very complicated process, but it's very easy to make errors and the deployment descriptors themselves can become quite large and unwieldy.

For this reason, there are now many tools available (open source and commercial) to help with building EJBs. For example, many integrated development environments (IDEs) such as IntelliJ and JBuilder provide support for EJBs in the form of wizards and EJB specific help. Also, other tools such as XDoclet allow you to define some of the deployment characteristics inside the Java code and the XML deployment descriptors are then automatically generated for you.

When should I use EJBs?

This is another one of those frequently asked questions and unfortunately there is no right or wrong answer. There are, however, some guidelines that are generally considered best practice around the usage of EJBs.

Probably the most important, technical, deciding factory is your deployment environment and whether you can actually use EJB. For example, if your hosting environment only supports J2EE web technologies such as JSPs and servlets, then using EJB is probably a bad idea. Second, although probably not that important is whether your team has experience in building EJBs as there is a slight learning curve involved with the process around building and using them.

What many decisions about whether to use EJB come down to are based around the size and complexity of the application you are building. EJB is seen as a fairly heavyweight technology in terms of processing power required to run EJBs and the development effort involved. Actually, this isn't strictly true because EJBs really aren't that heavyweight. However, they are in relation to building the same logic inside plain old Java objects (POJOs) such as JavaBeans. This is the point at which many people ask themselves whether they actually do need EJB.

What you need to do here is ask yourself a few questions. Apart from getting real world experience with EJB, what benefit does adopting it give you? Will you be able to take advantage of the facilities provided by EJB such as transaction support, failover, clustering, etc? Are your EJBs likely to be used by other clients? Are you likely to be able to take advantage of any of these benefits further down the line?

Many small systems simply don't need the added complexity of EJB, including for example, many web-based data entry applications. In fact, many high traffic web-based applications don't need the added complexity of EJB. Where EJB provides benefits are for high volume, transactional systems and those systems where you really do need to take advantage of distributed processing such as where you have clients installed across an enterprise. Using EJB to represent your business logic is often a tough decision to take, but hopefully this article has given you some insight into the type of questions that you should be asking yourself before adopting it.

Summary

In this article we've looked at what business logic is and how it can be wrapped up within reusable components when building J2EE applications. Depending on the size and complexity of your application, only you can decide whether the additional, overhead of building and deploying EJBs is right for you, taking into account the potential benefits of greater reusability and maintainability of your mission critical business logic.

Now that we understand a little more on how to write the business, next time we'll take a look at how information within a J2EE application is persisted with entity beans.


Return to Top
Movin' them doggies on the Cattle Drive

It's where you come to learn Java, and just like the cattle drivers of the old west, you're expected to pull your weight along the way.

The Cattle Drive forum is where the drivers get together to complain, uh rather, discuss their assignments and encourage each other. Thanks to the enthusiastic initiative of Johannes de Jong, you can keep track of your progress on the drive with the Assignment Log. If you're tough enough to get through the nitpicking, you'll start collecting moose heads at the Cattle Drive Hall of Fame.

Gettin' them doggies...
We got 'round about a good dozen ranchers drivin' along the trail, most of 'em in rasslin' good ol' Java-4 Say and Servlets-4 assignments.

Fresh riders on the Drive...
Got two new Cattle Drivers signed up on the assignment log, Rachel Andrew and Amy Phillips. These cowgirls will be larnin' the menfolk a thing or two about ridin' and ropin' and codin'.

Another moose on the wall for...
Yep, that's right, you make it through, you get yerself a nice little moose to hang on the wall. Well, OK, so it's a virtual moose on a virtual wall, but you can be right proud of 'em! Thanks to the efforts of Marilyn deQueiroz, you can now proudly admire your codin' accomplishments at the Cattle Drive Hall of Fame. Check it out, pardner, it's worth a wink.

Cattle Drive bartender and Old Fart Barry Gaunt has bagged another moose. This time it's on the Servlets trail of the drive. He's a mighty fast driver, that 'un. John Hembree splits his time between the ridin' the open range and his farm (basement server farm) in the Ohio territory. John just bagged his first moose on the Cattle Drive Basics trail.

Back in the saddle
Cowboy Daniel Dunleavy spent a spell out on the open range. But now's he's back in town, huntin' down that no-good varmint called "Say-4b."

Wanted in five counties: master of disguise
The law's one step closer to tracking down that outlaw known all over the 'Ranch as "Doco Mastadon." Or will the Cattle Drive make an honest man out of Donald Cossitt?

Nearin' the end of the trail
Old-timer Carol Murphy is rasslin' the last assignment to the ground. Maybe them XML assignments are right around the bend.

Nitpicking is hard work too...
We know they're workin' reeeeeally hard, after all, we've seen what those assignments look like once the nitpickers have combed through 'em. Hats off to Marilyn deQueiroz, Pauline McNamara, and Jason Adam for their dedication and patience with the pesky vermin that always manage to make their way into those assignments.

Those gentlemen behind the bar...
Notice the fellas wipin' the bar and shinin' up the sarsparila glasses? Updating that assignment log is tough work too. Big thanks to Michael Matola and Barry Gaunt. Mosey up and place yer orders. Rumor has it Michael keeps some special stuff under the bar, if you know what to ask fer.

Michael Matola


Return to Top
Book Review of the Month

Cocoon: Developer's Handbook
Lajos Moczar and Jeremy Aston
Cocoon is a Java-based open source XML content manager and publishing engine from the Apache project. This book was written as an introduction to Cocoon for the developer with a good background in XML and Java but with no background in Cocoon. Part I of the book is an introduction to Cocoon. I found this part of the book to be very difficult and confusing. There was a lot of writing on Generators, Transformers, and Serializers, but the overall discussion was hard to follow. Fortunately, this was only the first 65 pages of the book. Starting with Part II, the book takes on a whole new and much better flavor. After a chapter describing how to install Cocoon, the authors go right into some real examples of how to use Cocoon. Suddenly all the information from Part I which felt incomplete started making sense. The examples and sample code (which need to be downloaded) are excellent in explaining how to use Cocoon. This section goes through example after example, each demonstrating more of the functionality of Cocoon. All the examples worked exactly as advertised and were well designed to demonstrate the many capabilities of Cocoon. Part III of the book discusses advanced topics such as database connectivity, web services, and integrating Cocoon with EJBs. Part IV covers design factors, administration, etc. The last two parts of the book are reference tools. Overall, I thought the authors did a good job of making Cocoon easy to understand.
(Thomas Paul - Sheriff, April 2003)
More info at Amazon.com || More info at Amazon.co.uk


Return to Top
May Scheduled Book Promotions:
Starting
Date
Book Author(s) Publisher JavaRanch Forum Status
May 6 Developing Java Web Services Ramesh Nagappan, Robert Skoczylas John Wiley & Sons Web Services/SOAP confirmed
May 13 Java Extreme Programming Cookbook Eric M. Burke and Brian M. Coyner O'Reilly Process: UP, RUP, DRUP, XP confirmed
May 20 Sun Certified Enterprise Architect for J2EE Study Guide (Exam 310-051) Paul Allen, Joseph J. Bambara McGraw-Hill Osborne Media Architect Certification confirmed
May 27 The Struts Framework: Practical Guide for Programmers Sue Spielman Morgan Kaufmann Java Frameworks confirmed

Return to Top
Managing Editor: Johannes de Jong

Comments or suggestions for JavaRanch's NewsLetter can be sent to the NewsLetter Staff

For advertising opportunities contact NewsLetter Advertising Staff