Home > Store

Applied Enterprise JavaBeans Technology

Register your product to gain access to bonus material or receive a coupon.

Applied Enterprise JavaBeans Technology

Book

  • This product currently is not for sale.
Not for Sale

Description

  • Copyright 2003
  • Dimensions: 7 x 9 1/4
  • Pages: 743
  • Edition: 1st
  • Book
  • ISBN-10: 0-13-044915-6
  • ISBN-13: 978-0-13-044915-3

The definitive guide to industrial-strength EJB 2.0 development.

  • A comprehensive guide to enterprise-class EJB 2.0 development
  • In-depth coverage of transactions, security, performance, and Web services
  • Features a full-scale, real-world case study

Applied Enterprise JavaBeans Technology takes you under the hood of EJB 2.0, offering unprecedented insight into how EJB really works-and shows you how to leverage its full power to build industrial-strength distributed applications. EJB expert Kevin Boone starts from first principles and progresses to state-of-the-art approaches for building Java applications that are distributed, transactional, and secure. Along the way, Boone reveals aspects of the EJB architecture that are normally hidden but offer even more power to developers who understand them.

Applied Enterprise JavaBeans Technology offers all this and more:

  • Demonstrates powerful techniques for maximizing distributed application security
  • Introduces high-performance resource pooling and optimization strategies
  • Helps developers choose and implement the best approach to distributed transaction processing
  • Presents in-depth coverage of integration with related technologies, including servlets, Web services, messaging, directories, and CORBA
  • Includes extensive cross-references to the official EJB 2.0 specifications

From EJB "first principles" to the state of the art

  • Emphasizes accuracy, depth, and comprehensiveness: never oversimplifies!
  • Focuses on mission-critical development techniques that other books ignore
  • Illuminates powerful capabilities typically left "transparent" to the programmer
  • Shows how to use EJB to implement comprehensive security policies
  • Contains in-depth coverage of automatically generated EJB proxies

Sample Content

Online Sample Chapters

An Overview of EJB Technology

Enterprise JavaBeans™ in Context

Table of Contents



Author's Note.


About the Author.


Preface.
(NOTE: Each Chapter ends with Summary.)

Author 's Note.


About the Author.


Preface.


1. Enterprise Javabeans in Context.

Enterprise JavaBeans: What Are They, and What Do They Do? EJBs in the Enterprise. Why Use EJBs? The EJB Philosophy. EJB Roles. EJB Products. Summary.



2. Distributed Objects and RMI.

What are Distributed Objects? How Objects Can Communicate. Java RMI. Stubs. RMI Protocols. Security. Enterprise JavaBean RMI. Summary.



3. An Overview of EJB Technology.

The Client 's View. Fundamentals of the EJB Architecture. Types of EJB. Distributed and Local EJB Semantics. Anatomy of an EJB. Principle of Operation: Session and Entity EJBs. Principle of Operation: Message-driven EJBs. The EJB Container and Its Proxies. Overview of the EJB API. EJB Rules, Standards and Limitations. Assembly and Deployment. Configuration. Summary.



4. Creating and Deploying A Simple EJB.

Setting Up the Source Tree. Coding the EJB and Test Client. Compiling the EJB and Test Client. Starting the J2EE Reference Implementation Server. Assembling and Deploying the EJB. Testing the EJB. Troubleshooting. Summary.



5. Introducing the Case Study.

About the Case Study. About the 'Business '. Goals of the Application. Design Architecture. Design Philosophy. EJB Design. Sneak Preview. Summary.



6. Session EJBs.

Types and Applications of Session EJBs. What Is 'State '? Stateful Session EJBs. Stateless Session EJBs. Some Notes On the Meaning of an 'EJB Instance '. Session EJBs as Interfaces to Entity EJBs. Transaction Issues in Session EJBs. Analyzing the 'Interest 'EJB. An Example. Summary.



7. Naming and JNDI.

Naming and Directory Servers. What Is JNDI? JNDI Terms and Concepts. Using JNDI. Examining A Typical EJB Server Namespace. JNDI and EJB. JNDI in More Detail. JNDI Configuration. JNDI Lookups Across Servers. Further Reading.



8. JDBC and Databases.

What is JDBC? SQL. The JDBC API. JDBC drivers. JDBC and JNDI. EJB and JDBC example. Connection Management and Pooling. Transactions. Practical JDBC usage in EJBs. What 's New in JDBC 3.0? Summary.



9. Transactions.

Introductory Note. Transactions Described. The EJB Transaction Model. Container-managed Transaction Demarcation. Bean-managed Transaction Demarcation. Client-demarcated Transactions. Handling Transaction Isolation in EJBs. Distributed Transactions and Two-phase Commit. Summary.



10. Messaging and Message-Driven EJBs.

Overview of enterprise messaging. The JMS API. JMS and EJBs. Interlude: Messaging in the Prestige Bike Hire application. Sending messages from EJBs. Message-driven EJBs. Testing messaging EJBs. Summary.



11. Entity EJBs.

What Is An Entity EJB? Principle of Operation. Associations Between Entities. Persistence Management. Developer's Responsibilities in General. Handling Data Sets with No Natural Primary Key. Summary.



12. Bean-Managed Persistence.

Developer's Responsibilities. Optimizing Data Base Access. Example: A Directory-server Mapping EJB. Entity EJBs and Nonflat Data Structures. Many-valued Associations in BMP. Summary.



13. Container-Managed Persistence.

Persistence Management Overview. CMP in EJB 1.1. The EJB 2.0 CMP Philosophy. Developer Responsibilities with EJB 2.0 CMP. EJB QL Overview. Example: The Bikemodel EJB. EJB QL Examples. Persistence Strategies Compared. Summary.



14. Practicalities of EJB Development.

Debugging Hints. Packaging and Assembly of Applications. Portability and Interoperability. Utility Classes and the Server CLASSPATH. Summary.



15. Design, Patterns, and Good Practice.

Architectural and Structural Issues. Exception Handling: Philosophy and Practice. The 'This 'Reference and Loop-Back Calls. Thread Management. Garbage Collection Issues. Using Value Objects with EJBs. Handles. Summary.



16. Security.

Security Concepts. J2EE/EJB Security Architecture. The EJB Security API. Security Concepts Example. EJB Security in the Enterprise. Summary.



17. EJBs and the Web Tier.

Web Technology and Application Servers. JSP/Servlet-EJB Connectivity. Using Separate JSP/Servlet Engine and EJB Servers. Summary.



18. Connectors and Resource Adapters.

The Need for Connectivity. Simple Connectivity Techniques. JCA Resource Adapters: Rationale and Principles. A Simple Resource Adapter. Common Client Interface (CCI). Transaction Management. Security Management. Summary.



Appendix A. New Features in EJB 2.1.

Overview. EJB QL Enhancements. Web Services Integration. Messaging Enhancements. Timer Services. What 's Missing.



Appendix B. Overview of the EJB Deployment Descriptor.

Vendor-independent and Vendor-specific Deployment Descriptors. General Structure. Enterprise-beans Element. Relationships Element. Assembly-descriptor Element. Summary.



Appendix C. Installing and Testing the Case Study.

Installing the Application. Testing the Application.



Appendix D. Reflection and Dynamic Instantiation.

The Importance of Reflection. Using Reflection. Dynamic Instantiation.



Appendix E. Java Serialization.

The Purpose of Serialization. Serialization Strategies. Using the Serialization API. Controlling Serialization. Non-Java Serialization.



Appendix F. Obtaining and Configuring the J2EERI.

Getting the Reference Implementation. Setting Up: Unix. Setting Up: Windows. Usage Hints.



Appendix G. Overview of Public Key Cryptography.

Basic Principles. Combining Symmetric and Asymmetric Techniques. Detecting Tampering. Identifying the Communicating Parties.



Appendix H. Glossary of Terms.


Appendix I. Bibliography.


Index.

Preface

Preface

About this book

This book has two main purposes. First, it provides Java developers with all the information they need to author robust, powerful, secure EJB applications. Second, it provides guidance on, and interpretation of, the EJB Specification, focusing particularly on Version 2.0. It also describes some of the more important technologies that are associated with EJBs: JNDI, JDBC, JMS, and Web components.

My experience teaching EJB technology and advising on EJB projects has shown that it is relatively easy for an experienced developer to gain the skills necessary to begin working with EJBs. There are many courses, textbooks, and tutorials that provide support at this introductory level. The problem is that they don't provide the developer with sufficient information to make a success of demanding, critical applications. Failure of EJB projects to manifest the benefits that are claimed for the technology is often the result of an incomplete understanding of the more subtle aspects of the technology. These include such matters as the behaviour of an EJB server under load, the use of transaction boundaries to drive synchronization between the EJB and a database, and the impact of different database administration strategies on the EJB server's resource management systems. The experience necessary to overcome these problems can be gained by practice, of course, but a better approach, I believe, is to develop a really comprehensive grasp of the underlying technology before beginning work on expensive projects.

This is where this book comes in:~It describes EJB technology and the development of EJB applications in detail, starting from first principles and continuing to systems supporting distributed database transactions and a comprehensive security policy. The emphasis throughout is on accuracy, depth, and comprehensiveness, rather than on simplification. Where it is necessary for developers to gain the full benefit of using EJBs, the book even describes aspects of the EJB technology that are normally said to be `transparent' to the developer. These include---among other things---the generation and operation of the automatically generated EJB proxies and how these interact with the developer's code; how database connection pooling works (and therefore how to optimize database connection efficiency); how to handle transaction rollbacks in session beans; how the container deals with name resolution and cross-references; and the operation of bean-instance pooling systems. All these topics are crucial to the development of mission-critical applications, but are covered superficially, if at all, in other books.

Despite its technical depth, this book assumes no initial knowledge of EJBs or related technologies. It begins with very simple examples, and explains step-by-step how to code, compile, assemble, deploy, and test them using the J2EE Reference Implementation. To illustrate more sophisticated EJB features, the book uses a substantial, real-world application, for which complete source code is provided.

At the time of writing, the EJB community is being stirred by the introduction of the first products to support Version 2.0 of the EJB Specification. This version includes a number of substantial enhancements: message-driven EJBs, a new query language and persistence management scheme, and numerous smaller improvements. All these features are covered in depth in this book.

Intended readership

This book is written for professional software developers who expect to work extensively with Enterprise JavaBeans, or are already doing so. Although it assumes no prior knowledge of the subject, it goes into the technology in considerable depth. In order to make full use of the book, the reader will need to have

  • a high degree of familiarity with the Java programming language,
  • a working knowledge of networking, TCP/IP, and the Java sockets
  • abstraction,
  • sufficient familiarity with UML to understand basic class,
  • collaboration, and use-case diagrams,
  • a working knowledge of relational database management, particularly SQL,
  • and an understanding of the need for transaction management,
  • a sound foundation in object-oriented software engineering
  • concepts,
  • some familiarity with the XML language, and
  • a willingness to come to grips with a variety of rather
  • complex software tools that will be initially unfamiliar.

Although I assume that the reader is familiar with the Java language, I have included appendices that describe important, less well-known features of the language, such as reflection and serialization. These are key technologies that underlie the operation of EJB systems. In addition, while assuming basic familiarity with database technology, this book describes in detail more advanced features like distributed transaction management, as these are subjects with which many Java developers have little experience.

This book is part textbook and part reference book. Like a textbook, material is presented---as far as possible---so that each new topic builds on earlier topics. I say, `as far as possible,' because some compromises have been necessary. This is an EJB book, and readers will doubtless want to see examples of EJBs fairly early in the text. However, there is a great deal of background and related material that the developer must master to be able to develop EJB applications. This includes JDBC, JNDI, and transaction management. Ideally these subjects would be introduced first, but I felt this would not be appreciated by readers. However, I have resisted the temptation to hide these things in appendices, or in `advanced topics' chapters, and placed them as early in the text as I felt readers could stand. These topics are all vital to a full understanding of EJB technology. If you study the EJB Specification, you will see that it contains references to databases and transactions on almost every page. Therefore, like a reference book, I have anticipated that the reader will not want to read every chapter word for word before going on to the next chapter. Some of the material presented will probably only become meaningful when the reader has begun authoring EJB applications.

How to read this book

At risk of sounding glib, I recommend reading this book from start to finish. As has been discussed, the material of each chapter builds on preceding chapters. However, because each chapter covers its topic in considerable depth, you may prefer to skim some chapters rather than studying them in detail before going on. This is fine, but bear in mind that the chapters were not written to be self-contained, and you may find it necessary to flip back and forth to support this approach. I recommend that you do not skip the chapters on JNDI, JDBC, and transactions, however eager you may be for more EJB material. While it is possible---at a pinch---to master session EJBs without a detailed understanding of databases and transactions, this will be difficult for message-driven EJBs and impossible for entity EJBs.

Ten common EJB myths debunked

A number of commonly held misconceptions about EJBs sometimes deter software developers and project managers from making the transition to EJB-based application development. This is a shame because, although EJBs won't be suitable for all applications, it will be suitable for many, and one should not reject a strategy for the wrong reasons. Similarly, companies often adopt the use of EJB technology in haste, because their staff do not understand the full implications of such a decision. I should like to take the opportunity to dispell some of the myths about EJB technology early in this book.

Myth 1: EJB is just an extention of JavaBeans It is often said that Enterprise JavaBeans is an extension of JavaBeans technology. Despite the similar names, these technologies actually have very little in common, at least as far as the practicalities of development are concerned. There are philosophical similarities, but this is little consolation to a developer who has to move from one technology to another.

The similarities center on the notion of 'properties'---a Java class has a property if it exposes methods that allow some data to be read or written. For example, if a Java class exposes the methods

  • public void setName() {...}
  • public String getName() {...}

then it can be said to have a property 'name.' Whether the class itself internalizes the representation of the {\tt String} name is irrelevant for these purposes. This is much is true for EJB and JavaBeans, but not much more.

I have often heard developers say that they would like to become involved in EJB projects, but think they should 'work up to it gradually' by way of JavaBeans development. This is unfortunate because---apart from an increased familiarity with Java programming in general---experience with JavaBeans will probably not make it easier to develop EJB applications. There simply isn't enough common ground. To learn to develop EJB applications, start by writing EJBs.

Myth 2: EJB development is trivial, as the container does all the work The EJB container provides services to the EJBs which greatly simplify the development of enterprise applications---of particular importance are transaction management and security. However, it is still possible to develop EJB applications that are unreliable and offer poor performance if the underlying technology is poorly understood. The interaction between the EJB container and the developer's code is complex and subtle, and takes some time and practice to understand.

Myth 3: EJB applications are inherently portable EJB applications are more portable than those based on most other application development frameworks. In particular, being based on open standards means that there is good cross-vendor compatibility. There are, however, three problems with the assertion as it stands.

First, it is only true if the developer follows the guidance of the EJB Specification quite closely. It is possible to write nonportable EJBs either by ignorance or design.

Second, the EJB Specification recognizes that vendor products will probably offer facilities beyond the demands of the Specification, and that these facilities will have to be configured somehow. Vendors are allowed to have their EJB assembly tools include vendor-specific information in the deployable JAR and EAR packages. Many products will not function without this information, which won't be available if the package has come from a different product.

Third, not all EJB servers are equally fastidious about enforcing the restrictions imposed on EJBs by the EJB Specification. Some servers, for example, permit EJBs to read and write local files. It is difficult to move an application from a product that takes a tolerant line on these things to one that is strict.

In summary, the provisions of the EJB Specification mean that it will nearly always be possible to port an EJB application from one server to another. However, it may take a good degree of skill, and familiarity with both products, to accomplish this.

Myth 4: CORBA can do the same things as EJBs CORBA is an infrastructure for distributed objects, which has some overlap with EJB technology. However, CORBA is not an application framework. It does not remove the developer's need to get involved in the mechanics of transaction management and security. It does specify how transaction context and security context is to be propagated in method calls between servers, but does not stipulate how this information is to be used by applications. EJB servers can be based on CORBA standards, and offer services which extend the CORBA paradigm, rather than competing with it.

Myth 5: Java is slow Java applications are slow to start up, compared with native-code applications, because of the overhead of initializing the JVM (Java virtual machine). When just-in-time compilation is used, Java code is not significantly slower in execution than native code in the kinds of applications to which EJBs are suited. Of course, if one has an axe to grind, it is always possible to find some piece of code that shows a particular language in a bad light. C++ enthusiasts, for example, may assert---correctly---that C++ code outperforms Java in standard performance benchmarks. This is of little interest to EJB developers, because the standard benchmarks tend to involve operations such as matrix multiplication, that are unlikely to be implemented in EJBs. An EJB server may be relatively slow to start up, but once it has started, the EJBs are executed essentially as native code.

Myth 6: EJB applications are slow Badly written EJB applications are slow. Common sense and an understanding of EJB-container interaction should allow good performance to be achieved. There are, it is true, substantial overheads involved in method calls on EJBs. But it is not sensible to compare a piece of software written using EJBs with one written to run entirely in a single process. The latter may well be more efficient under light load, but the inherent scalability of EJB applications allows much better performance under heavy load (as the single-process solution probably won't scale at all).

Myth 7: EJBs support XML As we shall see, the EJB Specification has little to say about the use of XML with EJBs. It only mandates the use of XML for deployment descriptors (configuration files). EJBs are being used ingeniously with XML, but only by dint of the efforts of developers. There is an increased interest in the use of XML for passing data between EJBs, and a number of general-purpose implementations of systems that automate this are available, but it is not intrinsic to the EJB Specification. It is possible to expose EJB functionality as Web services, and use XML-RPC to make the method calls. However, this is part of the Web services development model, not the EJB model.

Myth 8: The EJB Specificationis opaque and impenetrable; EJB servers operate by smoke and mirrors The Specification is certainly not light reading, but neither is it incomprehensible, and it is essential for serious developers to have a copy handy. One of the goals of this book is to assist in the interpretation of the Specification, and you will see frequent references in the text to sections of that document.

Similarly, although the operation of an EJB server is complex, there is no black magic involved. Indeed, creating efficient EJB application requires a detailed understanding of the interaction between the EJB server and its EJBs.

Myth 9: EJBs are general-purpose, and can be used for any kind of application While not strictly incorrect, it is probably fair to say that EJBs excel in certain areas, rather than in others. EJBs are well-suited to distributed, datacentric business applications. They would be inappropriate for real-time systems or for applications where the advantages of scalability and security are not significant enough to outweigh the overheads of the distributed infrastructure.

Myth 10: It is possible to develop EJBs without knowing much Java On the contrary, I wouldn't recommend even starting EJB development unless you have a good background in Java. For the classroom courses that I teach, I normally recommend that participants have two years of Java development experience. People with extensive C++ experience can usually pick up EJB development quite easily as well, because many of the object-oriented concepts of Java and C++ are similar.

Chapter overview

Here is a summary of the material covered in this book.

EJBs in context

This introductory chapter describes the goals and requirements of EJB technology and what you---the developer---can expect to gain by using it.It explains how EJBs fit into other distributed programming paradigms (like CORBA), and into the wider 'J2EE' model of application development.The chapter includes an outline of the other services that a J2EE-compliant application server is expected to provide and which EJBs can use (e.g., Java-Mail, JMS).There is a brief discussion of the development philosophy that underlies the EJB Specification,including the roles of the developer, assembler, and deployer, and how the EJB model---appropriately used---can enhance code reuse and improve reliability.

Distributed objects

This chapter describes the principles that underlie distributed programming in Java and form the technological foundation for the EJB architecture.We begin by describing the process of Remote Method Invocation (RMI)and how we could,if we wished,develop an RMI framework from the ground up.This will be illustrated using outline source code for such a system.This discussion will highlight some of the challenges that face the developer of an RMI framework,and how these have been tackled in the standard Java RMI scheme (and,indirectly,in the EJB architecture).Again,we will use source code examples to demonstrate how these things work in practice.Finally,we will discuss the overlap between Java RMI and EJB RMI,with particular emphasis on protocols (like IIOP)that allow interoperability between these systems and others.

Overview of EJB technology

This chapter describes EJB technology in outline and provides an overview of the interaction between the EJB,the client,and the EJB container.It also describes the EJB objects and home objects ,and explains why the use of these constructs---although perhaps somewhat confusing at first--- ultimately simplifies the development of substantial software projects. We begin by examining how an EJB is seen by its clients,which may be synchronous,using RMI,or asynchronous,using messaging. We then discuss the Java entities that make up an EJB, the home interfaces, local interface, remote interface, and implementation class, and how they are packaged with a deployment descriptor to make a complete EJB. The chapter concludes with a discussion of the techniques that commercial EJB products may use to optimize performance and increase reliability. As it is an overview,this chapter does not provide any complete examples of EJBs, and could lead readers into thinking that the subject is more complicated than it really is. Moreover,to avoid fragmenting the text, I have included material in this chapter that, although part of an outline of the technology, is rather more complex than you may wish to see on a first reading. If you are impatient to see an EJB working and look at some real code, you may prefer to read Chapter 4 First.Y ou may find that this helps to put some of the more complicated parts of this chapter into perspective.

A first EJB

This chapter will describe the practical details of writing, compiling,deploying, and testing EJBs. We start with the simplest of simple EJBs: The example in this chapter is a stateless session bean, with only two methods accessible to clients. For purposes of illustration, we will describe this process for the J2EE Reference Implementation Version 1.3. For other products,the assembly and deployment process will be different,but the coding will be the same.

Introducing the case study

This chapter introduces a case study---the Prestige Bike Hire application--- that will form the basis for many of the examples used throughout the rest of this book. The case study is of a system for managing the business of a motorcycle rental firm. The system maintains bookings for rental vehicles, calculates hire costs, and maintains customer accounts. The chapter presents the client's requirements and outlines the architecture of the system that will be constructed.This case study has been chosen because it is complex enough to require the use of a number of EJBs of different types and demonstrate security and transaction management, but is not so large that we can't present most of the relevant source code. Subsequent chapters of the book will examine different EJBs from this case study in detail.

Session EJBs

In this chapter,we will examine the session EJB in much more detail. We start with stateful session EJBs, as their life cycles are conceptually simpler.We will discuss, in particular, issues relating to instance management: activation, passivation, and timeout. We then move on to stateless session EJBs, explaining how the EJB container can optimize performance by pooling instances and the implications that such pooling has for the developer. We will see these principles at work by analyzing the behaviour of the session EJB from Chapter 4 in detail. Finally, we present a more realistic session EJB example and give some practical guidelines on using session beans in applications.

Developer's guide to naming and JNDI

This chapter describes the JNDI system in more detail.We start with an outline of the JNDI architecture,and describe some of the key terms and concepts used in JNDI programming. This is followed by a description of the use of JNDI by EJBs and their clients, including the distinction between the server-wide namespace and the 'local' namespace provided for each EJB. This will lead to a discussion of the use of the 'java:comp/env'prefix in name lookups; this is an issue about which many developers and, sadly, some container vendors are unclear. Finally, to provide a detailed description of the JNDI architecture, there is a complete implementation of a JNDI interface to a set of objects stored in a file. This is provided for those readers who need a very thorough understanding of JNDI,perhaps to support EJB container extensions. It is easy for an EJB developer to forget that JNDI was designed not as a support service for EJBs, but to simplify access from Java programs to naming and directory servers (rather as JDBC is used for database access). Much of JNDI is intended to support this more general usage and is not directly used in EJB development. However, EJB developers are increasingly being called on to use the more general features of JNDI in their applications to support such features as user and group management.

JDBC and databases

This chapter presents an overview of the JDBC specification, particularly as it applies to EJB development. Readers who are already familiar with JDBC in other environments will find its use within EJBs similar to their previous experience;however, there are some small technical differences that have profound practical consequences,a s we shall see. We will discuss how the container provides Data source objects that allow clients to open and close database connections, and how the database connections are,in fact, container-supplied proxies for real connections. This will lead to a discussion of connection management and connection pooling, and how to author EJBs to take advantage of thesefacilities. Finally,we look at some practical techniques for improving the modularity and manageability of database access procedures in EJBs.

Transactions

This chapter explains how to make use of the transaction management features offerred by the EJB architecture. It describes the basic principles of transactions and the standard features that are supported by the EJB architecture. We then discuss the appropriate uses of bean-managed and container-managed transactions including the Session synchronization interface in stateful session EJBs.The concepts of this chapter will be demonstrated using both simple test EJBs and a practical example from the Prestige Bike Hire application. Finally, for readers with an interest in the underlying technology, there is a description of the roles of the transaction manager and resource managers, and the protocols by which these components communicate with one another and with the EJB container.

Message-driven EJBs

Message-driven EJBs are new in Version 2.0 of the EJB Specification. This chapter begins with a discussion of enterprise messaging in general, with a particular focus on the practical bene fits of this technology. We then discuss the JMS specification and the general procedures for sending mes-sages using the JMS API.This leads to a discussion of the problems of asynchronous communicaton in the EJB architecture, which is essentially a request-response system, and how the use of message-driven EJBs can help in development of asynchronous services.We then discuss the development and use of message-driven EJBs themselves, illustrated by examples from the Prestige Bike Hire application.

Entity EJBs

This chapter analyzes entity EJBs in more detail. It starts by describing the life cycle of an entity EJB and how the container manages the instance pool to handle database tables of arbitrary size. This will include a discussion of the container's manipulation of primary keys, including cases where the primary key is not a simple database field and has to be modelled as a class. We then discuss methods that the container can use to keep the instance variables in sync with the database tables, and the implications these techniques will have on the efficiency of the EJB. This chapter covers those aspects of entity EJB development that are relevant to both bean-managed and container-managed persistence. Later chapters will deal with each of these techniques in depth.

Bean-managed persistence

When using bean-managed persistence,the developer writes the Java code that synchronizes the EJB's internal state with the underlying database. This chapter describes in detail how to accomplish this.We begin by summarizing the developer's responsibilities,then describe step-by-step how to code, compile, assemble,d eploy, and test a fully featured entity EJB, which supports reads, writes, insertions, and deletions, single-object finders,multiobject finders, and home methods.T he example also presents the use of data access objects (DAOs) to decouple the EJB implementation from the data store. Finally,the chapter provides some advice on how more complex constructs like persistent associations can be handled using bean-managed persistence.

Container-managed persistence

Container-managed persistence (CMP) is a technique for allowing the EJB container to handle all the synchronization between the entity EJB and the underlying persistent storage device, usually a relational database. This chapter describes how to make use of CMP in both the EJB 1.1 and EJB 2.0 models. The chapter starts with a description of some of the issues that any persistence management scheme must address. It then describes how these issues were tackled in the EJB 1.1 scheme. Examination of some of the problems with the EJB 1.1 model allows an insight into the way in which the EJB 2.0 CMP model, although complex, solves many of the problems that prevented a wide uptake of CMP in EJB 1.1. We finish with a description of some practical examples from the Prestige Bike Hire application.

EJB practicalities

This chapter discusses some practical matters that may be of interest to the EJB developer, such as the use of remote debugging tools,I DE capabilities, problems with EJB server configuration, and portability.

Design, patterns, and good practice

This chapter discusses higher-level design issues in the EJB architecture and provides general guidance on building efficient, maintainable EJB applications. Some of the matters it describes are fairly technical,s uch as the effect on the application when exceptions are thrown from one EJB to another, while others are more pragmatic, like the use of design patterns.

Security

This chapter describes how to secure EJB applications,and the implications that EJB technology has for enterprise-level security.It explains how to make use of the security features offered by the EJB server and how EJB security is integrated with authentication features offered by Web-based applications and application containers. We start by describing the philosophy behind the J2EE security architecture and the EJB security model. We then discuss the use of declarative security, which allows security policies to be implemented in the deployment descriptor without coding. Declarative security will not always be sufficient on its own, and the developer will have to put some security procedures into code. We discuss the bene fits and implications of doing this. As an illustration of these concepts, we will see how different types of authentication and encryption can be applied to a simple EJB application. Finally,there is a discussion of how EJB security fits into the widerscope of enterprise security and of recent developments in secure, interoperable RMI protocols.

EJBs and the Web layer

This chapter describes in outline how to implement a Web-based user interface to an EJB application,focusing specification specifically on the issues of integrating EJBs to servlets and JSP pages.The chapter begins with a brief overview of the techniques that are available for server-side generation of dynamic content, particularly servlets and JSPs. It then describes how servlets and JSPs can initialize, locate, and use EJBs. Where stateful session EJBs are used, this requires synchronizing EJB instances to the servlet session; this technique is described in detail. Finally, we discuss the additional complexities involved in building an application in which the Web components are not hosted in a application server, but in a stand alone JSP/servlet engine.

Connectors and resource adapters

This chapter provides a brief introduction to resource adapters and the J2EE connector architecture (JCA).This architecture allows the developer to integrate support for arbitrary external resources into the EJB container. We begin with an example of an application that would benefit from the use of a connector. We then describe the JCA API in outline. Most of this chapter is concerned with the implementation and analysis of a specification resource adapter, which provides EJBs with access to a stock quote server; the API is described in detail with reference to this example. We then move on to a discussion of the proposed 'commonclient interface.' Finally,there is a brief explanation of the principles of transaction management and security management within resource adapters.

In addition, there are appendices on installing and testing the case study application, Java techniques that may not be familiar (such as serialization and reflection), the J2EE Reference Implementation, and the fundamentals of public key cryptography and SSL.

Getting started with EJB development

To develop, compile, package, deploy, and test EJB applications, you are going to need at least the following software:

  • Standard Java development tools. The ones you use already will almost certainly be adequate, although there are an increasing number of products that have additional support for EJB development (e.g., tools for synchronizing the content of the various Java classes and interfaces that make up an EJB).
  • An EJB server or application server. This book refers to the J2EE Reference Implementation, but any product with full EJB 2.0 compliance will run the examples. If the product you normally use does not offer full compliance, there is no reason why you should not run the Reference Implementation as well. It is free of charge, after all.
  • Tools for packaging EJBs and generating the XML deployment descriptors. These may be supplied with the EJB server, or you could use a general-purpose XML editor and the {\tt jar} utility in conjunction with make files or Ant scripts.
  • The EJB API documentation and Specification (which may be supplied with the EJB server, or you can download from java.sun.com/products/ejb).

I don't recommend that readers begin to learn EJB development using one of the heavy-duty, commercial application servers, for the same reason that novice pilots do not train in jet airliners. Commercial-grade application servers are optimized for supporting large client bases with short response times and high availability. These products do not sell on the basis of their ease of use or their powerful development tools (yet). In addition, they tend to be quirky, and slow to start up and shut down. Instead, I suggest using the J2EE Reference Implementation from Sun Microsystems (guidelines for obtaining and installing this latter product may be found in Appendix F). The reason I recommend this particular EJB implementation---apart from the obvious one that it is free---is that being a reference implementation, it should comply fully with the EJB Specification. It has a powerful specification checker that tests the compliance of the developer's code, making it a very useful educational tool. In addition, this is almost the only product currently available that is guaranteed to support all the new EJB 2.0 features, such as message-driven EJBs, the new connector API, and the extended container-managed persistence model. Moreover, the Reference Implementation is available for many hardware and operating system platforms. I have used Linux and Solaris for creating and testing the examples in this book, but instructions for operating the Windows version of the Reference Implementation are also given where there are differences. There should, of course, be no differences in the EJB code itself. All the examples in this book were tested with the J2EE Reference Implementation, Version 1.3.1.

The Reference Implementation is supplied with a simple SQL database engine called \textit{Cloudscape} (supplied by Informix, Inc.), and this has been used for all the examples that require database support, in preference to a commercial database, for the same reasons as discussed above.

This book does not advocate the use of particular interactive development environments (IDEs) and illustrates all compilation and execution operations using a command line and Ant build scripts. If you normally use an IDE, it will almost certainly be fine for EJB work. However, while I accept that many developers like to use IDEs, I feel that they conceal from the developer certain complexities which must be fully understood for EJB work. A case in point is the use of the class search path and the relationship between package names and directory structures. EJBs run in a different environment from the one in which they were compiled, and therefore incomplete understanding of these issues is a major cause of frustration for new EJB developers.

The state of the art

At the time of writing, there were at least 14 vendors offering EJB servers or application servers with EJB support. These vendors range in size from small specialist firms to global giants like Oracle. This number will almost certainly increase; there is very broad industry support for EJB. This book is based on `final release 2' of Version 2.0 of the EJB Specification, which was current at the time of writing. The fact that there has been a second `final release,' means, we assume, that further `final releases' are not ruled out. Should such changes impact the material or the source code in this book, updates will be posted on the supporting Web site: www.kevinboone.com/ejb_book.

At the time of writing, the first draft of the proposed Version 2.1 of the EJB Specification had just been published. At present, no EJB product supports any of the new features, and there was no settled date by which the new specification would be ratified. As a result, I have decided not to include EJB 2.1 features in the text; the specification is almost certain to change by the time you read this. Instead, I have included a brief discussion of the EJB 2.1 proposals in Appendix A.

What's new in EJB Version 2.0?

For readers who are already familiar with Version 1.1 of the \EJBS, here is a summary of the features that are substantially different in the new version, and where they are described in this book.

  • A new type of EJB, the message-driven EJB, has been introduced. These EJBs have neither home nor remote interfaces; their methods are called in response to the arrival of messages from an asynchronous messaging service. See Chapter 10.
  • EJBs can now interact in a nondistributed way, to avoid the overheads of remote method invocation. To support this, the EJB developer must provide two additional interfaces, the `local interface' and the `local home interface.' These are analogues of the traditional remote interface and home interface, and are used to generated intra-JVM calling proxies rather than distributable proxies. For more information, see page 57.
  • Entity EJBs can now make use of an entirely new container-managed persistence strategy, which improves significantly on the EJB 1.1 model. This new strategy specifies how persistent associations are managed, as well as persistent properties, and separates properties from instance variables. See page 408.
  • The new CMP scheme is supported by a new query language EJB~QL, whose job is to decouple the EJB logic from the database implementation. See page 408.
  • Entity EJBs can now expose methods to clients that do not rely on a specific EJB being created or located. They are called through the home interface (local or remote), and are therefore called home methods. See page 351.
  • The mechanism of principal delegation is now clearly defined in the EJB Specification. The deployment descriptor can now be used to specify the security role and principal that will be propagated from one EJB to another. See page .
  • The mechanisms for interoperability are now more rigidly defined. A whole chapter of the new EJB Specification (Chapter 18) is dedicated to these new requirements, which mandate techniques for naming, transaction context propagation, and security context propagation, among other things.

Notes on the text

In this book, I have used the following typographical and notational conventions.

  • Names of programming entities (classes, variables, keywords) that appear
  • in the text are given in a typewriter font, like this.
  • SQL statements use capital letters with Roman font for the keywords, and ordinary lower case for table and column names: ``SELECT * FROM ORDERS WHERE id=100''.
  • Source code listings are shown with light grey background with line numbers and with Java keywords highlighted, like this: for (int i = 0; i < 10); i++) print(this);
  • The line numbers are, of course, not part of the listing but are provided for ease of reference in the text.
  • User interface actions are given in abbreviated form, in quotation marks; for example: `File-Deploy' means ``select the `File' menu (or button) and hen the `Deploy' submenu (or button)''.
  • Where a command to be entered on the command line, or in a script or batch file, is too long to display on one line, I have used the backslash symbol to represent a continuation onto the next line, like this: This is really\ one line
  • Most Unix systems will let you use the backslash symbol in this way on the command line or in shell scripts; some Windows systems will not. If your system does not, you will need to concatenate all the lines displayed into one long line.
  • References to specifications are given like this: EJB2.0 x.x, where `x.x' is the section number. The term `EJB Specification' on its own should be taken to refer to Version 2.0, unless otherwise stated.
  • EJB 2.0 introduces the ability to specify intra-JVM method calling and defines new interfaces and proxies to support this. For brevity, in this book I will not distinguish the different types unless it is crucial to an understanding of the matter at hand. Therefore, the term `home interface' will refer to both local and remote home interfaces, `EJB object' will refer to the (remote) EJB object and the EJB local object, and `remote interface' will apply to both the remote interface and the local interface. This is because the EJB Specification does not provide a term that refers collectively to the local and remote interfaces. In practice, there should be no confusion, because the different types of interface and proxy are used in the same way.

Source code

Full source code for all the examples in this book can be found on the accompanying Web site, www.kevinboone.com/ejb_book. In the same place, you will find details of the sources available, information about the structure of the source trees, and hints on compiling and deploying using the Ant build tool.

Updates

Submit Errata

More Information

Unlimited one-month access with your purchase
Free Safari Membership