Mastering Enterprise JavaBeans Third Edition - … · CORBA, Third Edition(Wiley). ... Mastering...

841
Mastering Enterprise JavaBeans Third Edition Ed Roman Rima Patel Sriganesh Gerald Brose

Transcript of Mastering Enterprise JavaBeans Third Edition - … · CORBA, Third Edition(Wiley). ... Mastering...

  • MasteringEnterpriseJavaBeans

    Wiley Technology Publishing Timely. Practical. Reliable.

    The bestselling classic is backand covers the new EJB 2.1 specification!

    Serving as the ultimate resource thatboasts the most up-to-date informationon EJB, this edition begins with thefundamentals of building an EJB systemand gradually moves on to a discussionof programming with EJB. Youll learnabout advanced EJB concepts and bestpractices that you wont find anywhereelse, such as transactions, persistence,clustering, integration, performancemonitoring, security, and choosing anEJB server. Along the way, youll get in-depth coverage of:

    EJB security mechanisms

    Best practices for EJB applicationdevelopment, deployment, andtesting

    Tips for selecting appropriate Webframeworks and EJB containers

    EJB integration with back-endenterprise information systemsusing J2EE Connector technology

    Performance optimizations forvarious types of EJB

    Ed Roman is an independent consultant, a leading authority on EJB, and the author of the first two bestselling editions ofMastering Enterprise JavaBeans(Wiley).

    Rima Patel Sriganesh is a memberof Technical Staff in theTechnology Outreach group atSun Microsystems, Inc., and is a coauthor of Developing Java Web Services (Wiley).

    Gerald Brose is a SecuritySoftware Architect at XtradyneTechnologies. He is an expert inEJB and CORBA and the authorof Java Programming withCORBA, Third Edition (Wiley).

    The companion Web site includessample code, updates to the book,and links to useful software usedin the book.

    Building on the overwhelming successof his previous two editions, renownedauthor Ed Roman has returnedalongwith Enterprise JavaBeans (EJB) gurusGerald Brose and Rima Patel Sriganeshto offer you the inside scoop on theEJB 2.1 specification and relatedenhancements in J2EE 1.4. Continuingthe tradition of providing you with anunparalleled EJB tutorial, this expertteam of authors has revised more than30 percent of the book and added newchapters that explore the dramaticchanges in the way EJB is now used forbuilding applications.

    Visit our companion Web site at www.wiley.com/compbooks/romanAlso visit www.TheServerSide.com

    Mastering Enterprise JavaBeans

    RomanSriganesh

    Brose

    ,!7IA7G4-fhgicj!:p;o;p;K;KISBN: 0-7645-7682-8

    Programming Languages/Java $45.00 USA/$64.99 CAN/29.99 UK

    *85555-IJDJEi

    Third Edition

    Third Edition

    Ed RomanRima Patel SriganeshGerald Brose

    576828 Cover 10/26/04 9:37 AM Page 1

  • Ed RomanRima Patel Sriganesh

    Gerald Brose

    Mastering Enterprise JavaBeans

    Third Edition

    01_576828 ffirs.qxd 11/3/04 11:36 AM Page i

    cmaloneMasteringEJB

    cmaloneText BoxClick here to purchase this book.

    http://www.amazon.com/exec/obidos/ASIN/0764576828/qid%3D1100533352/sr%3D11-1/ref%3Dsr%5F11%5F1/102-1797734-3651315cmaloneMasteringEJB

  • Mastering Enterprise JavaBeans, Third EditionPublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright 2005 by Ed Roman, Gerald Brose, and Rima Patel SriganeshPublished by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaISBN: 0-7645-7682-8Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1

    3B/RX/RR/QU/IN

    No part of this publication may be reproduced, stored in a retrieval system or transmitted in anyform or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise,except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, withouteither the prior written permission of the Publisher, or authorization through payment of theappropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should beaddressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis,IN 46256, (317) 572-3447, fax (317) 572-4355, e-mail: [email protected].

    Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representationsor warranties with respect to the accuracy or completeness of the contents of this work and specif-ically disclaim all warranties, including without limitation warranties of fitness for a particularpurpose. No warranty may be created or extended by sales or promotional materials. The adviceand strategies contained herein may not be suitable for every situation. This work is sold with theunderstanding that the publisher is not engaged in rendering legal, accounting, or other profes-sional services. If professional assistance is required, the services of a competent professional per-son should be sought. Neither the publisher nor the author shall be liable for damages arisingherefrom. The fact that an organization or Website is referred to in this work as a citation and/or apotential source of further information does not mean that the author or the publisher endorses theinformation the organization or Website may provide or recommendations it may make. Further,readers should be aware that Internet Websites listed in this work may have changed or disap-peared between when this work was written and when it is read.

    IN NO EVENT SHALL THE AUTHOR OR PUBLISHER BE LIABLE TO ANY PERSON FOR ANYINCIDENTAL, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, INCLUDING WITHOUTLIMITATION TO, LOSS OF PROFITS, LOSS OF DATA, BUSINESS INTERRUPTION OR ANY ANDALL OTHER SIMILAR DAMAGES OR LOSS, EVEN IF AUTHOR OR PUBLISHER OR THEIR SUP-PLIERS OR THEIR AGENTS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

    For general information on our other products and services or to obtain technical support, pleasecontact our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317)572-3993 or fax (317) 572-4002.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in printmay not be available in electronic books.

    Library of Congress Control Number: 2004114268

    Trademarks: Wiley, the Wiley Publishing logo and related trade dress are trademarks or registeredtrademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries,and may not be used without written permission. Enterprise JavaBeans is a trademark of SunMicrosystems, Inc. in the U.S. or other countries. All other trademarks are the property of theirrespective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentionedin this book.

    01_576828 ffirs.qxd 11/3/04 11:36 AM Page ii

  • To my wonderful wife, Christine, and to our boys, Johannes and Julius.

    Rima wishes to dedicate this book to her dearest and loving husbandSriganesh, and her most wonderful parents.

    01_576828 ffirs.qxd 11/3/04 11:36 AM Page iii

  • Credits

    iv

    Acquisitions EditorRobert M. Elliott

    Development EditorSydney Jones

    Technical EditorFloyd Marinescu

    Copy EditorMichael Koch

    Editorial ManagerKathryn Malm Bourgoine

    Vice President & Executive Group PublisherRichard Swadley

    Vice President and PublisherJoseph B. Wikert

    Project CoordinatorErin Smith

    Graphics and Production SpecialistsSean DeckerKelly EmkowJennifer Heleine

    Quality Control TechnicianBrian H. Walls

    Proofreading and IndexingTECHBOOKS Production Services

    01_576828 ffirs.qxd 11/3/04 11:36 AM Page iv

    cmaloneRectangle

    cmaloneText BoxClick here to purchase this book.

    http://www.amazon.com/exec/obidos/ASIN/0764576828/qid%3D1100533352/sr%3D11-1/ref%3Dsr%5F11%5F1/102-1797734-3651315cmaloneMasteringEJB

  • Acknowledgments xvi

    Introduction xvii

    Part One Overview 1

    Chapter 1 Overview 3The Motivation for Enterprise JavaBeans 4Component Architectures 7

    Service-Oriented Architectures 8Divide and Conquer to the Extreme with Reusable Services 9Introducing Enterprise JavaBeans 11

    Why Java? 12EJB as a Business Tier Component 13

    The EJB Ecosystem 15The Bean Provider 16The Application Assembler 16The EJB Deployer 17The System Administrator 17The Container and Server Provider 18The Tool Vendors 18Summary of Roles 19

    The Java 2 Platform, Enterprise Edition (J2EE) 21The J2EE Technologies 22

    Summary 26

    Chapter 2 EJB Fundamentals 27Enterprise Beans 27

    Types of Beans 28Distributed Objects: The Foundation for EJB 30Distributed Objects and Middleware 32

    Contents

    v

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page v

    cmaloneRectangle

    cmaloneMasteringEJB

    cmaloneText BoxClick here to purchase this book.

    http://www.amazon.com/exec/obidos/ASIN/0764576828/qid%3D1100533352/sr%3D11-1/ref%3Dsr%5F11%5F1/102-1797734-3651315cmaloneMasteringEJB

  • Explicit Middleware 33Implicit Middleware 34

    What Constitutes an Enterprise Bean? 36The Enterprise Bean Class 36The EJB Object 37The Home Object 42The Local Interfaces 44Deployment Descriptors 48Vendor-Specific Files 49Ejb-jar File 49Summary of Terms 50

    Summary 52

    Chapter 3 Writing Your First Bean 53How to Develop an EJB Component 54The Remote Interface 55The Local Interface 56The Home Interface 57The Local Home Interface 59The Bean Class 61The Deployment Descriptor 64The Vendor-Specific Files 65The Ejb-jar File 65Deploying the Bean 66The Optional EJB Client JAR File 67Understanding How to Call Beans 68

    Looking up a Home Object 68Running the System 72

    The Server-Side Output 73The Client-Side Output 73

    Implementing Component Interfaces 73A Solution 74

    Summary 75

    Part Two The Triad of Beans 77

    Chapter 4 Introduction to Session Beans 79Session Bean Lifetime 79Session Bean Subtypes 80

    Stateful Session Beans 80Stateless Session Beans 81

    Special Characteristics of Stateful Session Beans 83Achieving the Effect of Pooling with Stateful Beans 83The Rules Governing Conversational State 84Activation and Passivation Callbacks 85Method Implementation Summary 88A Simple Stateful Session Bean 88Life Cycle Diagrams for Session Beans 98

    Summary 102

    vi Contents

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page vi

  • Chapter 5 Writing Session Bean Web Services 103Web Services Concepts 103

    Web Services Standards 106XML Artifacts and Platform Independence 109

    Implementing a Web Service 110The JAX-RPC Service Endpoint Interface 111WSDL and the XML/Java Mapping 113Packaging and Deploying a Web Service Session Bean 113

    Implementing a Web Service Client 114Summary 117

    Chapter 6 Introduction to Entity Beans 119Persistence Concepts 119

    Object-Relational Mapping 120What Is an Entity Bean? 122

    About the Files That Make Up an Entity Bean 124Features of Entity Beans 125

    Entity Beans Survive Failures 125Entity Bean Instances Are a View into a Database 126Several Entity Bean Instances May Represent the Same

    Underlying Data 127Entity Bean Instances Can Be Pooled 128There Are Two Ways to Persist Entity Beans 131Creation and Removal of Entity Beans 132Entity Beans Can Be Found 136You Can Modify Entity Bean Data without Using EJB 136

    Entity Contexts 137getEJBLocalObject() / getEJBObject() 138getPrimaryKey() 138

    Summary 139

    Chapter 7 Writing Bean-Managed Persistent Entity Beans 141Entity Bean Coding Basics 141

    Finding Existing Entity Beans: Finder Methods 143Bean-Managed Persistence Example: A Bank Account 150

    Account.java 151AccountLocal.java 152AccountHome.java 153AccountLocalHome.java 155AccountPK.java 156AccountBean.java 158AccountException.java 170Client.java 171The Deployment Descriptor 173The Container-Specific Deployment Descriptor 175Setting up the Database 175

    Running the Client Program 175Server-Side Output 175Client-Side Output 177

    Contents vii

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page vii

  • Putting It All Together: Walking through a BMP Entity Beans Life Cycle 177

    Summary 180

    Chapter 8 Writing Container-Managed Persistent Entity Beans 181Features of CMP Entity Beans 181

    CMP Entity Beans Are Subclassed 181CMP Entity Beans Have No Declared Persistent Fields 182CMP Get/Set Methods Are Defined in the Subclass 184CMP Entity Beans Have an Abstract Persistence Schema 186CMP Entity Beans Have a Query Language 187CMP Entity Beans Can Have ejbSelect() Methods 189

    Implementation Guidelines for Container-Managed Persistence 191Container-Managed Persistence Example: A Product Line 196

    Product.java 197ProductLocal.java 198ProductHome.java 198ProductLocalHome.java 200ProductPK.java 201ProductBean.java 203The Deployment Descriptor 207The Container-Specific Deployment Descriptor 210Client.java 212

    Running the Client Program 214The Life Cycle of a CMP Entity Bean 214Summary 216

    Chapter 9 Introduction to Message-Driven Beans 217Motivation to Use Message-Driven Beans 217The Java Message Service 219

    Messaging Domains 220The JMS API 222

    Integrating JMS with EJB 226What Is a Message-Driven Bean? 227

    Developing Message-Driven Beans 231The Semantics 231A Simple Example 234

    Advanced Concepts 241JMS Message-Driven Bean Gotchas 244

    Message Ordering 245Missed ejbRemove() Calls 245Poison Messages 246How to Return Results Back to Message Producers 249The Future: Asynchronous Method Invocations 254

    Summary 254

    Chapter 10 Adding Functionality to Your Beans 255Calling Beans from Other Beans 255

    Default JNDI Lookups 256Understanding EJB References 257

    viii Contents

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page viii

  • Resource Factories 259Environment Properties 262Understanding Handles 263

    Home Handles 264Summary 265

    Part Three Advanced Enterprise JavaBeans Concepts 267

    Chapter 11 EJB Best Practices 269When to Use EJB 270How to Choose a Web Application Framework to Work with EJB 272Applying Model Driven Development in EJB Projects 275Applying Extreme Programming in EJB Projects 277Testing EJB 279

    EJB Unit Testing 279Use Frameworks for EJB Unit Testing 280

    Implementing Client-Side Callback Functionality in EJB 282JMS 282Remote Method Invocation 283Web Service 283

    Choosing Between Servlets and Stateless Session Beans as Service Endpoints 284

    Considering the Use of Aspect-Oriented Programming Techniques in EJB Projects 284

    Aspect-Oriented Programming 285When to Use AOP in EJB Applications 285

    Reflection, Dynamic Proxy, and EJB 287Deploying EJB Applications to Various Application Servers 288Debugging EJB 290Inheritance and Code Reuse in EJB 291Writing Singletons in EJB 293When to Use XML with EJB 293When to Use Messaging Versus RMI-IIOP 294Summary 297

    Chapter 12 Transactions 299Motivation for Transactions 300

    Atomic Operations 300Network or Machine Failure 301Multiple Users Sharing Data 302

    Benefits of Transactions 303The ACID Properties 304

    Transactional Models 306Flat Transactions 306Nested Transactions 308Other Transactional Models 310

    Enlisting in Transactions with Enterprise JavaBeans 310Underlying Transaction System Abstraction 310Declarative, Programmatic, and Client-Initiated Transactions 310Choosing a Transaction Style 314

    Contents ix

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page ix

  • Container-Managed Transactions 317EJB Transaction Attribute Values 318

    Programmatic Transactions in EJB 324CORBA Object Transaction Service 324The Java Transaction Service 325The Java Transaction API 325Declarative versus Programmatic Transactions Example 328

    Transactions from Client Code 330Transactional Isolation 331

    The Need for Concurrency Control 332The Dirty Read Problem 334The Unrepeatable Read Problem 336The Phantom Problem 336Transaction Isolation Summary 337Isolation and EJB 338Pessimistic and Optimistic Concurrency Control 339

    Distributed Transactions 340Durability and the Two-Phase Commit Protocol 340The Transactional Communications Protocol

    and Transaction Contexts 342Designing Transactional Conversations in EJB 343J2EE Transaction Service and Extended Transactions 346Summary 348

    Chapter 13 Security 349Introduction 350

    Violations, Vulnerabilities, and Risk 351Controls 351

    Web Application Security 353Authentication in Web Applications 354Authorization 355Confidentiality and Integrity 356

    Understanding EJB Security 357Authentication in EJB 357Authorization in EJB 368Security Propagation 377

    Secure Interoperability 378IIOP/SSL 379CSIv2 379

    Web Services Security 381End-to-End Security 382XML Digital Signature and XML Encryption 383SAML 386WS-Security 387

    Summary 389

    Chapter 14 EJB Timers 391Scheduling 391EJB and Scheduling 392

    x Contents

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page x

  • The EJB Timer Service 394Timer Service API 395Interaction between the EJB and the Timer Service 398

    Timer Example: CleanDayLimitOrdersEJB 399The CleanDayLimitOrders EJB Remote Interface 400The CleanDayLimitOrders EJB Bean Class 400The CleanDayLimitOrders EJB Home Interface 403The CleanDayLimitOrders EJB Deployment Descriptor 403The CleanDayLimitOrders EJB Client 404Running the Client 405

    Strengths and Limitations of EJB Timer Service 406Summary 408

    Chapter 15 BMP and CMP Relationships 409The CMP and BMP Difference 410Cardinality 411

    1:1 Relationships 4121:N Relationships 416M:N Relationships 421

    Directionality 428Implementing Directionality with BMP 429Implementing Directionality with CMP 430Directionality May Not Map to Database Schemas 431Bidirectional or Unidirectional? 433

    Lazy Loading 433Aggregation Versus Composition and Cascading Deletes 434Relationships and EJB-QL 436Recursive Relationships 437Circular Relationships 438Referential Integrity 439

    Relationships, Referential Integrity, and Client Code 441Summary 444

    Chapter 16 Persistence Best Practices 445Comparing Entity Beans with Other Persistence Approaches 446

    Control 446Data retrieval 446Procedural versus Object-Oriented 447Caching 448Enforcement of Schema Independence 448Migration 449Rapid Application Development 449

    Choosing Between CMP and BMP 450Code Reduction and Rapid Application Development 450Performance 450Bugs 451Control 451Application Server and Database Independence 451Relationships 452Learning Curve and Cost 452

    Contents xi

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page xi

  • Choosing the Right Granularity for Entity Beans 453Persistence Tips and Tricks 454

    Beware the Object-Relational Impedance Mismatch 454Hard-Coded versus Soft-Coded SQL 454When to Use Stored Procedures 455Normalizing and Denormalizing 457Use Your EJB Object Model to Drive Your Data Model 459Follow a Good Data Design Process 459Use Surrogate Keys 460Understand the Impacts of Database Updates 461Versioning EJB Components 461Living with a Legacy Database Design 463Handling Large Result Sets 474

    Summary 475

    Chapter 17 EJB Integration 477Why Does Integration Matter? 477

    Integration Styles 478EJB and Integration 479J2EE Connector Architecture 480

    Why J2EE Connectors? 480Resource Adapter Interaction with J2EE Components 483Resource Adapter Interaction with Application Server 484

    The J2EE Connector API 486The javax.resource Package 486The javax.resource.cci Package 487The javax.resource.spi Package 490The javax.resource.spi.endpoint Package 492The javax.resource.spi.security Package 493The javax.resource.spi.work Package 493

    System Contracts 494Lifecycle Management 494Connection Management 495Security Management 498Transaction Management 501Work Management 504Message In-flow 506

    Connector Example: OutboundLoanRA 508Example Architecture 508JavaLoanApp.java 509LoanApp.dll 510OutboundLoanRA 511LoanRatesEJB 535LoanRatesClient 538Running the Client 539Extending OutboundLoanRA 541

    xii Contents

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page xii

  • Integration Best Practice: When to Use Which Technology 541When to Use JMS and JMS-Based MDB 542When to Use J2EE Connectors 542When to Use Java Web Services 543

    Summary 543

    Chapter 18 EJB Performance Optimizations 545It Pays to Be Proactive! 545The Stateful Versus Stateless Debate from a

    Performance Point of View 547How to Guarantee a Response Time with Capacity Planning 549Use Session Faade for Better Performance 550Choosing Between Local Interfaces and Remote Interfaces 552Partitioning Your Resources 553Tuning Stateless Session Beans 554Tuning Stateful Session Beans 555Tuning Entity Beans 556Tuning Message-Driven Beans 563Tuning Java Virtual Machine 563Miscellaneous Tuning Tips 565Choosing the Right EJB Server 567Summary 568

    Chapter 19 Clustering 569Overview of Large-Scale Systems 569

    What Is a Large-Scale System? 570Basic Terminology 572Partitioning Your Clusters 573

    Instrumenting Clustered EJBs 578How EJBs Can Be Clustered 578The Concept of Idempotence 579Stateless Session Bean Clustering 581Stateful Session Bean Clustering 583Entity Bean Clustering 584Message-Driven Bean Clustering 588

    Other EJB Clustering Issues 589First Contact 589Initial Access Logic 590

    Summary 591

    Chapter 20 Starting Your EJB Project on the Right Foot 593Get the Business Requirements Down 593Decide Whether J2EE Is the Right Choice 594Staff Your Project 598Design Your Complete Object Model 600Implement a Single Vertical Slice 601Choose an Application Server 603Divide Your Team 604

    Contents xiii

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page xiii

  • Invest in Tools 606Invest in a Standard Build Process 607Next Steps 607Summary 608

    Chapter 21 Choosing an EJB Server 609J2EE Standard Compliance 610Pluggable JRE 610Conversion Tools 610Complex Mappings 611Third-Party JDBC Driver Support 611Lazy Loading 611Deferred Database Writes 611Pluggable Persistence Providers 611In-Memory Data Cache 612Integrated Tier Support 612Scalability 612High Availability 613Security 613IDE Integration 614UML Editor Integration 615Intelligent Load Balancing 615Stateless Transparent Fail-over 615Clustering 616Java Management Extension (JMX) 616Administrative Support 616Hot Deployment 617Instance Pooling 617Automatic EJB Generation 617Clean Shutdown 617Real-Time Deployment 618Distributed Transactions 618Superior Messaging Architecture 618Provided EJB Components 619Web Services 619Workflow 619Open Source 620Specialized Services 620Nontechnical Criteria 621Summary 621

    Chapter 22 EJB-J2EE Integration: Building a Complete Application 623The Business Problem 623A Preview of the Final Web Site 624Scoping the Technical Requirements 630

    The Business Logic Tier 631The Presentation Tier 637

    Example Code 643Summary 651

    xiv Contents

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page xiv

  • Appendix A RMI-IIOP and JNDI Tutorial 653

    Appendix B CORBA Interoperability 683

    Appendix C Deployment Descriptor Reference 705

    Appendix D The EJB Query Language (EJB-QL) 739

    Appendix E EJB Quick Reference Guide 757

    Index 801

    Contents xv

    02_576828 ftoc.qxd 11/3/04 11:36 AM Page xv

  • This book has been a project spanning several years. Many have commentedthat the first edition was one of the best technical books they ever read. Whatsmade this book a reality are the many people who aided in its development.

    As a special thanks, wed like to acknowledge the great folks at John Wiley& Sons. They have been absolutely outstanding throughout this books evolu-tion. In particular, we thank Bob Elliott, Sydney Jones, and Kathryn Malm fortheir incredible efforts. We also thank Floyd Marinescu of The MiddlewareCompany for his insightful technical reviews, and Jrg Bartholdt of XtradyneTechnologies for technical discussions. Finally, we thank Theserverside.comcommunity for providing us with their very helpful reviews.

    Acknowledgments

    xvi

    03_576828 flast.qxd 11/3/04 11:37 AM Page xvi

    cmaloneRectangle

    cmaloneRectangle

    cmaloneMasteringEJB

    cmaloneText BoxClick here to purchase this book.

    http://www.amazon.com/exec/obidos/ASIN/0764576828/qid%3D1100533352/sr%3D11-1/ref%3Dsr%5F11%5F1/102-1797734-3651315cmaloneMasteringEJB

  • This book is a tutorial on Enterprise JavaBeans (EJB). Its about EJB concepts,methodology, and development. This book also contains a number ofadvanced EJB topics, giving you a practical and real-world understanding ofthe subject. By reading this book, you will acquire a deep understanding of EJB.

    Make no mistake about itwhat you are about to read is not easy. EJB incor-porates concepts from a wealth of areas, including distributed computing, data-bases, security, component-driven software, and more. Combining them is amagnificent stride forward for the Java community, but with that comes a myr-iad of concepts to learn and understand. This book will teach you the conceptsand techniques for authoring reusable components in Java, and it will do sofrom the ground up. You need only to understand Java to understand this book.

    While youre reading this book, you may want to download the EJB specifi-cation, available at http://java.sun.com/products/ejb/docs.html.

    Goals for This Edition

    The first edition of this book came out in 1999, and the second edition in 2002.We had to make some tough calls when writing the second and third editions,and we are confident youll like them. Here were our goals:

    To update the book for EJB 2.1. EJB 2.1 has many new useful featuresthat we detail throughout the book.

    To be broad and also deep. We do not regurgitate the complete EJBspecification in this book, nor do we cover every last detail of EJB.Rather, we cover the most important parts of EJB, leaving room to dis-cuss advanced issues. For a complete reference while you are coding,

    Introduction

    xvii

    03_576828 flast.qxd 11/3/04 11:37 AM Page xvii

    cmaloneRectangle

    cmaloneMasteringEJB

    cmaloneText BoxClick here to purchase this book.

    http://www.amazon.com/exec/obidos/ASIN/0764576828/qid%3D1100533352/sr%3D11-1/ref%3Dsr%5F11%5F1/102-1797734-3651315cmaloneMasteringEJB

  • search through the EJB specification using Adobe Acrobat. Readers whoare looking for a well-written book that is interactive and fun to readand covers the basics through advanced subjects have come to the rightplace.

    To be concise. Your time as a reader is extremely valuable, and yourelikely waiting to read a stack of books besides this one. Given that mostpeople dont have time to read 1,000-pluspage books, we actuallywanted to reduce the size of this book as much as possible. So wevetightened things up and eliminated redundant examples. This way, youcan get to actually program with EJB, rather than read a book formonths on end. The irony of this story is that it was harder for us towrite a shorter book than a long book!

    To be a book for developers. This book is not intended for high-levelbusinesspeople. This is a technical book for a technical audience.

    To write a book the right way. This books primary author, Ed Roman,has taken his skills in training and knowledge transfer and appliedthem to this book. Thus, weve infused this book with the followingattributes:

    A conversational style. When you read this book, sometimes youllfeel like youre almost having a discussion with us. We think this isfar superior to spending eons trying to re-read a formal writing styleover and over again.

    Use of diagrams and bulleted lists. The adage a picture is worth athousand words applies here. These tactics are great for breakingup blocks of text. They keep things varied and make the book amuch faster read.

    A consistent voice. Even though several co-authors wrote this book,youll hear one voice. This was done to combine best-of-breedknowledge from several expert co-authors while maintaining a uni-form look and feel throughout the book.

    To be an introductory book, but also to get quickly into advanced topics. We figured that the average developer has had enough of booksthat merely skim the surface. We wanted to write a book that pushedbeyond the basics. Our approach when writing this book was always toerr on the side of being advanced. To achieve this, we did an immenseamount of research. We participated in the mailing lists, performedmany real-world projects, attended conferences and seminars, and net-worked with the top experts throughout the world.

    To be vendor-neutral. All vendor-specific deployment steps are exter-nalized to the books accompanying source code. This makes this bookuseful for any EJB server.

    xviii Introduction

    03_576828 flast.qxd 11/3/04 11:37 AM Page xviii

  • To add useful EJB information garnered from our instructor-led train-ing classes. Having taught EJB/J2EE for years, we have learned signifi-cantly from our students. We have interlaced this book with many ofour own students questions and answers in relevant sections.

    To take all the source code and make it available online. Because wevemade the code available on the Web, you know its the latest version.This will ensure that the code you receive works right the first time.

    Organization of the Book

    The text is organized into the following five parts:

    Part One is a whirlwind introduction to EJB programming. Part Oneserves as a great overview for people in a hurry. While Part One isessential information to EJB newcomers, veterans will also find nuggetsof useful knowledge. The following chapters are covered:

    Chapter 1 is a tour of enterprise computing. Well talk about compo-nents, service-oriented architectures, distributed computing frame-works, and containers. In this regard, well introduce EJB and J2EE.

    Chapter 2 moves on to the fundamentals of building an EJB system,including the tricky concept of request interception. Well also lookat the various source code files that make up an enterprise bean.

    Chapter 3 shows you how to put together a simple enterprise bean.Well also learn how JNDI is used in EJB and see how to call thatbean from a client.

    Part Two devotes exclusive attention to programming with EJB. Wellsee how to use the triad of beans: entity beans, session beans, and mes-sage-driven beans. Well cover the basics of writing each type of bean,including an example as well as detailed lifecycle diagrams.

    Chapter 4 introduces session beans. Well look at the differencebetween stateful and stateless session beans, how to code a sessionbean, and whats going on behind the scenes with session beans.

    Chapter 5 shows how Web services can be implemented using EJB.In particular, we show how a stateless session bean can be madeavailable as a Web service.

    Chapter 6 is a conceptual introduction to entity beans. Well look atpersistence concepts, what makes entity beans unique, and the filesinvolved when building entity beans.

    Introduction xix

    03_576828 flast.qxd 11/3/04 11:37 AM Page xix

  • Chapter 7 covers bean-managed persistent (BMP) entity beans. Wellsee how to program a BMP entity bean, and also look at whats hap-pening behind the scenes with BMP.

    Chapter 8 covers container-managed persistent (CMP) entity beans.Well focus on the exciting features of EJB 2.x CMP, learn how to pro-gram a CMP entity bean, and look at whats happening behind thescenes with CMP.

    Chapter 9 covers message-driven beans. Well first review the JavaMessage Service (JMS), which is the messaging framework usedmostly with message-driven beans. Well then dive in and under-stand how to program with message-driven beans.

    Chapter 10 discusses the EJB environment, along with services pro-vided by the container. This includes environment properties,resource factories, references between beans, and handles.

    Part Three, the most exciting part of the book, covers advanced EJBconcepts. The following chapters are included:

    Chapter 11 explains guidelines for using various Web applicationframeworks, model-driven development tools, and so on, in EJBapplications. It also presents proven best practices for EJB design,development, and testing.

    Chapter 12 tackles transactions. Transactions are a crucial topic foranyone building an EJB application that involves state. Well discusstransactions at a conceptual level followed by a discussion on howto apply them to EJB. Well also learn about the Java Transaction API(JTA) as well as J2EE Extended Transaction concepts.

    Chapter 13 provides an in-depth treatment of EJB security and cov-ers Java Authentication and Authorization Service (JAAS), secure inter-operability, and Web Services security.

    Chapter 14 introduces the new EJB timer service that lets you sched-ule tasks for automatic execution.

    Chapter 15 covers relationships between entity beans. This is a criti-cal concept for anyone performing complex persistence. Wellunderstand the concepts of cardinality, directionality, referentialintegrity, and cascading deletes. Well also see how to code relation-ships for both CMP and BMP entity beans.

    Chapter 16 covers persistence best practices. Youll learn excitingconcepts such as how to choose between entity beans and other per-sistence techniques, how to choose between BMP and CMP, andyoull survey a collection of persistence best practices that weveassembled from our knowledge and experience.

    xx Introduction

    03_576828 flast.qxd 11/3/04 11:37 AM Page xx

  • Chapter 17 covers integration to and from EJB platform in-depth. Itprovides introduction to the various styles of integration, followedby a discussion of various techniques for integrating EJB with theoutside world. It explains the J2EE Connector Architecture, a pre-dominant framework for integrating EJB with back-end enterpriseapplications, and discusses a connector example.

    Chapter 18 covers EJB tips and techniques for designing anddeploying EJB for better performance. Youll learn about designstrategies that will help you make decisions such as when to choosebetween stateful versus stateless session beans, when to choosebetween local and remote interfaces, and so on. The chapter alsofocuses a great deal on providing performance tuning tips for differ-ent types of beans.

    Chapter 19 discusses clustering in large-scale EJB systems. Youlllearn about how clustering works behind the scenes and learn a fewstrategies for how containers might achieve clustering. This is a criti-cal topic for anyone building a system that involves severalmachines working together.

    Chapter 20 covers EJB project management. Well talk about how toget your project started on the right foot. This includes guidelines onchoosing between J2EE and .NET frameworks for your projects,building a first pass of your system, dividing your developmentteam, and many such concepts.

    Chapter 21 provides guidelines for choosing the right EJB server foryour needs. Well describe our methodology for how an organiza-tion can compare and contrast different vendors offerings. Wellalso list our set of criteria for what we would want in an EJB server.

    Chapter 22 shows how to build a real-world J2EE system using EJBcomponents. Well see how the EJB components should be usedtogether in an enterprise, as well as how to connect them with clientsusing Java servlets and JavaServer Pages (JSP) technology. Well alsodemonstrate how to design an EJB object model using UML.

    The Appendixes are a collection of ancillary EJB topics. Some develop-ers may want to read the appendices, while some may not need to do so.

    Appendix A teaches you Java Remote Method Invocation over theInternet Inter-ORB Protocol (RMI-IIOP) and the Java Naming andDirectory Interface (JNDI). These technologies are prerequisites forusing EJB. If youre just starting down the EJB road, you must readthis appendix first.

    Appendix B discusses how to integrate EJB and CORBA systems.Well learn about how EJB and CORBA are interoperable through

    Introduction xxi

    03_576828 flast.qxd 11/3/04 11:37 AM Page xxi

  • RMI-IIOP and see sample code for calling an EJB component from aCORBA client.

    Appendix C is a deployment descriptor reference guide. This will beuseful for you later, when youre working with deployment descrip-tors and need a guide.

    Appendix D covers the EJB query language (EJB-QL) in detail.

    Appendix E is an API and diagram reference guide. This is usefulwhen you need to look up the purpose of a method or class in EJB.

    Throughout the book, this icon will signal a tip, note, or other helpful adviceon EJB programming.

    In a similar paradigm to our training courses, the content of this book isvery interactive. We have taken our knowledge of adult learning andscattered boxes like this throughout the book. Each box asks you a questionto get you thinking. The answers to the questions are posted on the booksaccompanying Web site. What do you think are the benefits of thisparadigm?

    Illustrations in the Text

    Almost all of the illustrations in this book are written in the Unified ModelingLanguage (UML). UML is the de facto standard methodology for illustratingsoftware engineering concepts in an unambiguous way. If you dont knowUML, pick up a copy of The Unified Modeling Language User Guide (Addison-Wesley, ISBN 0201571684), which illustrates how to effectively use UML inyour everyday software. UML is a highly important achievement in object-ori-ented methodology. Its a common mechanism for engineers to communicateand design with, and it forces you to abstract your object model prior to imple-mentation. We cannot stress its use enough.

    The Accompanying Web Site

    This book would not be complete without a way to keep you in touch after itwas published. A Web site is available for resources related to this book. Thereyoull find:

    All of the source code you see in this book. The code comes completewith Ant scripts, ready to build and run. It should be deployed on anyapplication server that is J2EE 1.4compliant.

    Updates to the source code examples.

    xxii Introduction

    03_576828 flast.qxd 11/3/04 11:37 AM Page xxii

  • Error corrections from the text.

    A PDF copy of this book

    The Web site is at www.wiley.com/compbooks/roman.

    Feedback

    When you begin your EJB programming, were sure youll have many experi-ences to share with other readers. Feel free to e-mail examples, case studies,horror stories, or tips that youve found helpful in your experiences, and wellpost them on the Web site.

    Send bug reports to [email protected].

    From Here

    Now that weve gotten the logistics out of the way, lets begin our explorationof Enterprise JavaBeans.

    About the Authors

    Ed Roman is one of the worlds leading authorities on high-end middlewaretechnologies. He has been heavily involved with Sun Microsystems enterpriseJava solutions from their inception and has designed, built, and deployed avariety of enterprise applications, including architecting and developing com-plete application server products. He devotes a significant amount of time toinfluencing and refining Suns enterprise specifications, contributes regularlyto middleware interest mailing lists, and regularly speaks at middleware-related conferences.

    Ed is the founder of The Middleware Company (which can be found on theWeb at www.middleware-company.com). The Middleware Company offers theworlds leading knowledge network for middleware professionals. The Mid-dleware Company enables developers, technology vendors, and enterprises toimplement, innovate, and communicate emerging technology offerings. TheMiddleware Company solutions include TheServerSide Communities, Mid-dlewareREACH, and MiddlewarePRO. TheServerSide Communities informover half a million professionals monthly using an open forum to discuss andsolve the most challenging middleware issues. Clients of The MiddlewareCompany include the worlds top software organizations including BEA Sys-tems, Compuware, HP, IBM, Microsoft, Oracle, Sun Microsystems, and VERI-TAS Software. Ed also is the founder of TheServerSide.com, which is the defacto J2EE community Web site. Every day, thousands of developers get

    Introduction xxiii

    03_576828 flast.qxd 11/3/04 11:37 AM Page xxiii

  • together on TheServerSide.com to share EJB design patterns, hear about thelatest EJB news, ask and answer EJB development questions, and read articles.After youve read this book, visit TheServerSide.com to catch up on the latestEJB information. TheServerSide.com is a completely free service and isintended to help the community.

    Rima Patel Sriganesh is a Member of Technical Staff presently working inthe Technology Outreach group at Sun Microsystems, Inc. She specializes inJava, XML, and Integration platforms. Her areas of technology passion includeDistributed Computing Models, Security and Trust Computing, Semanticweb, Grid Computing, and Quantum Physics. She speaks regularly at pre-miere industry conferences such as JavaOne, Web Services Edge, SIGS 101,Sun Technology Days, and others. She also represents Sun at various security,choreography, and financial services technology standards.

    Rima is a co-author of Developing Java Web Services (Wiley, 2002). She fre-quently publishes her take on technology and industry in the form of papersand blogs.

    Rima graduated in Mathematics from M. S. University, Gujarat, India. Shecurrently lives with her husband in the Greater Boston area.

    To find out more about her work, use the Google queries Rima Patel SunMicrosystems or Rima Patel Sriganesh.

    Gerald Brose works as Security Software Architect at Xtradyne Technolo-gies. Gerald is an expert in middleware security, including CORBA, J2EE, andWeb Services. He is a regular speaker at international conventions and theauthor of several publications on middleware security and related issues. Ger-ald is a co-author of Java Programming with CORBA (Wiley, 2001).

    As a member of the open source community, Gerald maintains JacORB, themost widely used Open Source ORB for Java, which is also part of the JBossJ2EE application server. Gerald holds a Ph.D. in computer science from FreieUniversity, Berlin. He lives with his wife and two sons in Berlin, Germany.

    xxiv Introduction

    03_576828 flast.qxd 11/3/04 11:37 AM Page xxiv

  • PA R T

    Overview

    In Part One, we introduce the server-side development platform, the Java 2Platform, Enterprise Edition (J2EE), of which the Enterprise JavaBeans (EJB)component architecture is a vital piece. J2EE is a conglomeration of con-cepts, programming standards, and innovationsall written in the Javaprogramming language. With J2EE, you can rapidly construct distributed,scalable, reliable, and portable secure server-side deployments.

    Chapter 1 begins by exploring the need for server-side componentarchitecture such as EJB. Youll see the rich needs of server-side com-puting, such as scalability, high availability, resource management,and security. Well discuss how EJB architecture relates to the Service-oriented Architecture (SOA) paradigm. Well also take a look at theJ2EE server-side development platform.

    Chapter 2 moves on to the fundamentals of Enterprise JavaBeans.Well look at the concept of request interception, which is crucial forunderstanding how EJB works. Well also look at the different filesthat go into a bean and how they work together.

    Chapter 3 gets down and dirty with EJB programming. Here, wellwrite our first simple bean. Well explain how to code each of the filesthat compose the bean, and well also look at how to call that beanfrom clients.

    One

    04_576828 pt01.qxd 11/3/04 11:37 AM Page 1

    cmaloneRectangle

    cmaloneMasteringEJB

    cmaloneText BoxClick here to purchase this book.

    http://www.amazon.com/exec/obidos/ASIN/0764576828/qid%3D1100533352/sr%3D11-1/ref%3Dsr%5F11%5F1/102-1797734-3651315cmaloneMasteringEJB

  • 04_576828 pt01.qxd 11/3/04 11:37 AM Page 2

  • 3

    Enterprise JavaBeans (EJB) is a server-side component architecture that sim-plifies the process of building enterprise-class distributed component applica-tions in Java. By using EJB, you can write scalable, reliable, and secureapplications without writing your own complex distributed componentframework. EJB is about rapid application development for the server side;you can quickly and easily construct server-side components in Java by lever-aging a prewritten distributed infrastructure provided by the industry. EJB isdesigned to support application portability and reusability across any ven-dors enterprise middleware services.

    If you are new to enterprise computing, these concepts will be clarifiedshortly. EJB is a complicated subject and thus deserves a thorough explanation.In this chapter, well introduce EJB by answering the following questions:

    What plumbing do you need to build a robust distributed objectdeployment?

    What is EJB, and what value does it add?

    How does EJB relate to SOA?

    Who are the players in an EJB ecosystem?

    Lets kick things off with a brainstorming session.

    Overview

    C H A P T E R

    1

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 3

  • The Motivation for Enterprise JavaBeans

    Figure 1.1 shows a typical business application. This application could exist inany vertical industry and could solve any business problem. Here are someexamples:

    A stock trading system

    A banking application

    A customer call center

    A procurement system

    An insurance risk analysis application

    Notice that this application is a distributed system. We broke up what wouldnormally be a large, monolithic application and divorced each layer of theapplication from the others, so that each layer is completely independent anddistinct.

    Take a look at this picture, and ask yourself the following question basedpurely on your personal experience and intuition: If we take a monolithic appli-cation and break it up into a distributed system with multiple clients connecting tomultiple servers and databases over a network, what do we need to worry about now(as shown in Figure 1.1)?

    Take a moment to think of as many issues as you can. Then turn the pageand compare your list to ours. Dont cheat!

    Figure 1.1 Standard multitier-only deployment.

    Database

    Client Client Client

    Server Server

    4 Chapter 1

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 4

  • In the past, most companies built their own middleware. For example, afinancial services firm might build some of the middleware services above tohelp them put together a stock trading system.

    These days, companies that build their own middleware risk setting them-selves up for failure. High-end middleware is hideously complicated to buildand maintain, requires expert-level knowledge, and is completely orthogonalto most companies core business. Why not buy instead of build?

    The application server was born to let you buy these middleware services,rather than build them yourself. Application servers provide you with com-mon middleware services, such as resource pooling, networking, and more.Application servers enable you to focus on your application and not worryabout the middleware you need for a robust server-side deployment. Youwrite the code specific to your vertical industry and deploy that code into theruntime environment of an application server. Youve just solved your busi-ness problem by dividing and conquering.

    Overview 5

    THINGS TO CONSIDER WHEN BUILDING LARGE BUSINESS SYSTEMS

    By now you should have a decent list of things youd have to worry about whenbuilding large business systems. Heres a short list of the big things we cameup with. Dont worry if you dont understand all of them yet you will.

    Remote method invocations. We need logic that connects a client andserver via a network connection. This includes dispatching method re-quests, brokering parameters, and more.

    Load balancing. Clients must be directed to the server with the lightestload. If a server is overloaded, a different server should be chosen.

    Transparent fail-over. If a server crashes, or if the network crashes, canclients be rerouted to other servers without interruption of service? If so,how fast does fail-over happen? Seconds? Minutes? What is acceptablefor your business problem?

    Back-end integration. Code needs to be written to persist business datainto databases as well as integrate with legacy systems that may alreadyexist.

    Transactions. What if two clients access the same row of the database si-multaneously? Or what if the database crashes? Transactions protect youfrom these issues.

    Clustering. What if the server contains state when it crashes? Is that statereplicated across all servers, so that clients can use a different server?

    Dynamic redeployment. How do you perform software upgrades whilethe site is running? Do you need to take a machine down, or can youkeep it running?

    (continued)

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 5

  • 6 Chapter 1

    THINGS TO CONSIDER WHEN BUILDING LARGE BUSINESS SYSTEMS (continued)

    Clean shutdown. If you need to shut down a server, can you do it in asmooth, clean manner so that you dont interrupt service to clients whoare currently using the server?

    Logging and auditing. If something goes wrong, is there a log that youcan consult to determine the cause of the problem? A log would help youdebug the problem so it doesnt happen again.

    Systems management. In the event of a catastrophic failure, who is mon-itoring your system? You want monitoring software that paged a systemadministrator if a catastrophe occurred.

    Threading. Now that you have many clients connecting to a server, thatserver is going to need the capability of processing multiple client re-quests simultaneously. This means the server must be coded to be multi-threaded.

    Message-oriented middleware. Certain types of requests should bemessage-based where the clients and servers are very loosely coupled.You need infrastructure to accommodate messaging.

    Object life cycle. The objects that live within the server need to be cre-ated or destroyed when client traffic increases or decreases, respectively.

    Resource pooling. If a client is not currently using a server, that serversprecious resources can be returned to a pool to be reused when otherclients connect. This includes sockets (such as database connections) aswell as objects that live within the server.

    Security. The servers and databases need to be shielded from saboteurs.Known users must be allowed to perform only operations that they haverights to perform.

    Caching. Lets assume there is some database data that all clients shareand make use of, such as a common product catalog. Why should yourservers retrieve that same catalog data from the database over and overagain? You could keep that data around in the servers memory andavoid costly network roundtrips and database hits.

    And much, much, much more.

    Each of these issues is a separate service that needs to be addressed forserious server-side computing. These services are needed in any businessproblem and in any vertical industry. And each of these services requires a lotof thought and a lot of plumbing to resolve. Together, these services are calledmiddleware.

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 6

  • Component Architectures

    It has been a number of years since the idea of multitier server-side deploy-ments surfaced. Since then, more than 50 application servers have appeared onthe market. At first, each application server provided component services in anonstandard, proprietary way. This occurred because there was no agreed def-inition of what a component should be or how it should be provided with ser-vices or how should it interact with the application server. The result? Onceyou bet on an application server, your code was locked into that vendors solu-tion. This greatly reduced portability and was an especially tough pill to swal-low in the Java world, which promotes openness and portability.

    What we need is an agreement, or set of interfaces, between applicationservers and components. This agreement will enable any component to runwithin any application server. This will allow components to be switched inand out of various application servers without having to change code orpotentially even recompile the components themselves. Such an agreement iscalled component architecture and is shown in Figure 1.2.

    If youre trying to explain components to a nontechie, try these analogies:

    Any CD player can play any compact disc because of the CD standard.Think of an application server as a CD player and components ascompact discs.

    In the United States, any TV set can tune into any broadcast because ofthe NTSC standard. Think of an application server as a TV set andcomponents as television broadcasts.

    Figure 1.2 A component architecture.

    Application Server

    agreed-uponinterfacesspecified bycomponentarchitecture

    Components

    Overview 7

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 7

  • Service-Oriented Architectures At the core of a service-oriented architecture lies the concept of service. A sim-plistic definition of service is a group of related components that carry out agiven business process function, for example transferring funds betweenbanks or booking an itinerary. A service-oriented architecture (SOA) thus is a par-adigm focusing on development of services rather than piecemeal compo-nents such that these services provide a higher level of abstraction from afunctional standpoint. Of course, there are more properties to SOA than merecoarse-granularity. One such characteristic property of SOA is that they areautonomous in nature. These independent entities can interact with others inspite of differences in the way they have been implemented or the platformthey have been deployed on. The notion of putting together (integrating) suchautonomous and loosely coupled services to address the changing businessneeds has a huge value proposition and it is well on its way to realization withthe emergence of various choreography, orchestration and collaboration tech-nologies such as WS-BPEL, EbXML BPSS, and WS Choreography.

    SOA and Web Services

    The terms Web Services and SOA are often used interchangeably and wronglyso. SOA is a paradigm. There are many possible ways of building software sothat it implements salient features of SOA, mainly coarse granularity and loosecoupling. One such way is Web services. Web Services are a group of XMLtechnologies, which can be used for implementing SOA. Core Web servicetechnologiesmainly SOAP and WSDLform the basis of most of these Webservice implementations today.

    Simple Object Access Protocol (SOAP) is an XML-based application-levelprotocol intended for exchanging information in a distributed network. SOAPsupports both the models of distributed computing: RPC as well as document-style messaging. RPC style SOAP allows remote invocation of operations.Parameters and return in/out values of these operations are serialized in XML.Whereas, in document-style SOAP because an operations input and outputare XML, serialization of parameters and return value to XML is not needed.Although most of the Web service applications use SOAP over HTTP today,the standard does not preclude using SOAP over other IP protocols, such asSMTP. SOAP 1.2 is a W3C recommendation at the time of this writing.

    Web Service Description Language (WSDL) is an XML-based metadata stan-dard that is used to describe the service interfacein terms of the operations itsupports, the parameters that the operations accept, and their return values incase of SOAP RPC, the XML schema that the input and output messages to theoperations in case of document-style SOAPas well as service binding infor-mationin terms of the communication protocols, ports, service URL, and so

    8 Chapter 1

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 8

  • on. At the time of this writing, WSDL 2.0 is well on its way to becoming a W3Cstandard.

    Thus, Web Services present a powerful solution for distributed but looselycoupled, coarse-grained SOA wherein services are described using WSDL andaccessed via SOAP. In fact, one of the main reasons for using Web Services torealize SOA is the ubiquitous support for XML, SOAP, and WSDL technologieson disparate platforms, ranging from mainframes to mobile devices. This isthe main reason why Web Services provide a true solution for interoperabilitybetween applications deployed on these disparate platforms.

    We will spend some more time explaining fundamental concepts in Chapter5; however, explaining Web Services and related technologies in their entiretyis outside the scope of this book. If you are new to Web Services, there aremany books and online papers that you can refer to get started with Web Ser-vices conceptually. Given the solid adoption of this stack by the industry, wesuggest that you familiarize yourself properly with Web services.

    SOA and Component Architectures

    SOA is not a replacement for component architecture; rather it neatly comple-ments the component architecture. While component architectures enhancereusability at a finer grain level, SOA can enhance reusability at a coarsergrained level. Hence, from an implementation standpoint, a given servicemight very well be developed using well-defined component frameworkssuch as EJB. The latest EJB standard, therefore, has in-built support for WebServices, the most popular stack for building SOA. So EJB is still very much indemand!

    Chapter 5 covers Web Services support in EJB framework in detail.

    Divide and Conquer to the Extreme with Reusable Services

    We have been seeing a slow but steady shift in the build-from-scratch trend,for years now. More and more businesses want CIOs to stretch their IT dollarsto the maximum. Naturally, this has led the IT departments to think of reuse;reuse in terms of systems as well as software. What better candidate thanhighly functional and autonomous services to fulfill this promise of reuse?SOA offers maximum reuse, especially when implemented using ubiquitousprotocols such as those supported by Web services. Architects want to designtheir software as a composition of services such that these services can be usedfrom any platform through well-defined service interfaces.

    Overview 9

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 9

  • Why just stop at corporate ITs? Even ISVs are thinking of providing theirsoftware as services. Prime examples of software as a service include Sales-force.com and Siebel. Both these companies have made their enterprise soft-ware available to customers as hosted services. Many other businesses such asAmazon.com and Google provide their core business services, E-commerce,and Web searching, as reusable services to customers and end-users.

    Reusable services are a very powerful concept, because:

    Businesses can focus on strategic software development. In caseswhere software functionality is horizontal and cuts across multiplebusiness domains, it should be treated as commodity and hence pro-cured from a specialized ISV in the form of services. For example, eachbusiness requires a corporate treasury management and cash manage-ment system. For such a commodity business need, it is best to acquiresoftware from an outside vendor than to build it. This will relieve the ITstaff from having to deal with complex treasury functions involvingmillions of regulations; it anyway does not have direct relevance to thebusinesss core function.

    The business processes can be assembled faster. The autonomous andloosely coupled nature of services makes it easy to assemble them intobusiness processes. This strength makes services the chosen paradigmfor encapsulating business logic.

    There is a lower total cost of ownership. Businesses that build theirsoftware as services end up with a lower total cost of ownership in thelong term because they are building software such that it can be easilyreusable and assembled into business processes. This is a definite pluswhen businesses are required to adapt business processes to addressthe changing market demands or when they are required to supportnew customers and their IT systems. Businesses that sell software asservices, on the other hand, can benefit their customers by offering flex-ible software licensing options, such as per-month billing or per-yearbilling, thereby enabling their customers to lower total cost of owner-ship.

    Remember that these services can and should be built using components.Therefore, the component architectures are very much here to stay. Figure 1.3depicts such a Treasury management service built using EJB components.

    With this introduction to SOA and their relevance to EJB, let us furtherexplore the EJB technology.

    10 Chapter 1

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 10

  • Figure 1.3 Reusable services built using EJB.

    Introducing Enterprise JavaBeans

    EJB is a standard for building server-side components in Java. It defines anagreement (contract) between components and application servers thatenables any component to run in any application server. EJB components(called enterprise beans) are deployable, and can be imported and loaded intoan application server, which hosts those components.

    The top three propositions of EJB are as follows:

    It is agreed upon by the industry. Those who use EJB will benefit fromits widespread use. Because everyone will be on the same page, in thefuture it will be easier to hire employees who understand your systems(since they may have prior EJB experience), learn best practices toimprove your system (by reading books like this one), partner withbusinesses (since technology will be compatible), and sell software(since customers will accept your solution). The concept of train once,code anywhere applies.

    Portability is easier. The EJB specification is published and availablefreely to all. Since EJB is a standard, you do not need to gamble on asingle, proprietary vendors architecture. And although portability willnever be free, it is cheaper than without a standard.

    A corporate financepersonnel uses treasury

    management system throughcompany portal

    Rather than building atreasury management

    application fromscratch, the business

    buys treasurymanagement system,built as a service, from

    outside.

    All company employees use a central company portal application

    to access various services

    HTTP

    SOAP/HTTP

    CompanyPortal Application

    Corporate IT

    RMI/IIOP

    CorporateTreasury ManagementWeb Service Wrapper

    EJBs providing treasurymanagement logic

    Overview 11

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 11

  • Rapid application development. Your application can be constructedfaster because you get middleware infrastructure services such as trans-actions, pooling, security, and so on from the application server. Theresalso less of a mess to maintain.

    Note that while EJB does have these virtues, there are also scenarios inwhich EJB is overkill. See Chapters 11 and 16 for best practices and discussionsurrounding the issue of when to (and when not to) use EJB.

    Physically, EJB is actually two things in one:

    A specification. This is a 640-plus-page Adobe Acrobat PDF file, freelydownloadable from http://java.sun.com/products/ejb/docs.html. Thisspecification lays out the rules of engagement between componentsand application servers. It constricts how you code enterprise beans toenable write once, run anywhere behavior for your EJB application.

    A set of Java interfaces. Components and application servers mustconform to these interfaces. Since all components are written to thesame interfaces, they all look the same to the application server. Theapplication server therefore can manage anyones components.

    Why Java?EJB architecture has supported only the Java language thus far. Though thissounds a bit restrictive, the good news is that Java is one of the best-suited lan-guages for building components for the following reasons.

    Interface/implementation separation. We need a language that sup-ports clean separation between the interface and implementationmainly to keep the component upgrades and maintenance to minimum.Java supports this separation at a syntactic level through the interfaceand class keywords.

    Safe and secure. The Java architecture is much safer than traditionalprogramming languages. In Java, if a thread dies, the application staysup. Pointers are no longer an issue. Memory leaks occur much lessoften. Java also has a rich library set, so that Java is not just the syntaxof a language but a whole set of prewritten, debugged libraries thatenable developers to avoid reinventing the wheel in a buggy way. Thissafety is extremely important for mission-critical applications. Sure, theoverhead required to achieve this level of safety might make yourapplication slower, but 90 percent of all business programs are glorifiedgraphical user interfaces (GUIs) to databases. That database is going tobe your number one bottleneck, not Java.

    12 Chapter 1

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 12

  • Cross-platform. Java runs on any platform. Since EJB is an applicationof Java, this means EJB should also easily run on any platform. This isvaluable for customers who have invested in a variety of powerfulhardware, such as Win32, UNIX, and mainframes. They do not want tothrow away these investments.

    If you dont want to go the EJB route, you have two other choices:

    Lightweight open source Java frameworks such as Spring. In Chapter 11we discuss when to use EJB versus such non-standard frameworks.

    Microsoft .NETmanaged components, part of the Microsoft .NETplatform

    EJB as a Business Tier ComponentThe real difference between presentation tier components such as thick clients,dynamically generated Web pages, or Web Service clients and enterprise beansis the domain in which they operate. Presentation components are well suitedto handle client-side operations, such as rendering GUIs, executing client-sidevalidations, constructing appropriate SOAP messages to send them to WebService, and so on. They deal directly with the end user or business partner.

    Enterprise beans, on the other hand, are not intended for the client side; theyare server-side components. They are meant to perform server-side operations,such as executing complex algorithms or performing high-volume businesstransactions. The server side has different kinds of needs than GUI clients do.Server-side components need to run in a highly available (24/7), fault-tolerant,transactional, and multiuser secure environment. The application server pro-vides this high-end server-side environment for the enterprise beans, and itprovides the runtime containment necessary to manage enterprise beans.

    Specifically, EJB is used to help write logic that solves business problems. Typ-ically, EJB components (enterprise beans) can perform any of the followingtasks:

    Perform business logic. Examples include computing the taxes on theshopping cart, ensuring that the manager has authority to approve thepurchase order, or sending an order confirmation e-mail using the Java-Mail API.

    Access a database. Examples include submitting an order for books,transferring money between two bank accounts, or calling a stored pro-cedure to retrieve a trouble ticket in a customer support system. Enter-prise beans can achieve database access using the Java DatabaseConnectivity (JDBC) API.

    Overview 13

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 13

  • Access another system. Examples include calling a high-performingCICS legacy system written in COBOL that computes the risk factor fora new insurance account, calling a legacy VSAM data store, or callingSAP R/3. Enterprise beans can integrate with an existing applicationthrough the J2EE Connector Architecture (JCA), which we will talk aboutin detail in Chapter 17.

    Thus, EJB components are not presentation tier components; rather, they sitbehind the presentation tier components (or clients) and do all the hard work.Examples of the clients that can connect to enterprise beans include the following:

    Thick clients. Thick clients execute on a users desktop. They couldconnect through the network with EJB components that live on a server.These EJB components may perform any of the tasks listed previously(business logic, database logic, or accessing other systems). Thickclients in Java include applets and applications.

    Dynamically generated Web pages. Web sites that are transactionaland personalized in nature need their Web pages generated specificallyfor each request. For example, the home page for Amazon.com is com-pletely different for each user, depending on the users profile. Coretechnologies such as Java servlets and JavaServer Pages (JSP) are usedto dynamically generate such specific pages. Both servlets and JSPs livewithin a Web server and can connect to EJB components, generatingpages differently based upon the values returned from the EJB layer.

    Web Service clients. Some business applications require no user inter-face at all. They exist to interconnect with other business partnersapplications that may provide their own user interface. For example,consider a scenario where Dell Computer Corporation needs to procureIntel chips to assemble and distribute desktop computers. Here, Intelcould expose an Order Parts Web Service that enables the Dell Web Ser-vice client to order chips. In this case, the Intel system does not providea graphical user interface per se, but rather provides a Web Serviceinterface. This scenario is shown in Figure 1.4.

    14 Chapter 1

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 14

  • Figure 1.4 EJBs as Web Service clients.

    The EJB Ecosystem

    To get an EJB deployment up and running successfully, you need more thanjust an application server and components. In fact, EJB encourages collabora-tion of more than six different parties. Each of these parties is an expert in itsown field and is responsible for a key part of a successful EJB deployment.Because each party is a specialist, the total time required to build an enterprise-class deployment is significantly reduced. Together, these players form the EJBEcosystem.

    Lets discuss who the players are in the EJB Ecosystem. As you read on,think about your companys business model to determine which role you fill.If youre not sure, ask yourself what the core competency of your business is.Also think about what roles you might play in upcoming projects.

    The EJB Ecosystem is not for everyone. At my company, weve heard ghastlystories of businesses choosing EJB because everyone else is using it, orbecause it is new and exciting. Those are the wrong reasons to use EJB andcan result in disappointing results. For best practices and a discussionsurrounding the issue of when and when not to use EJB, see Chapters 11and 16.

    A Dell customerorders 100 computerson dell.com

    Dell.com Web application findsout that chips needs to beprocured for fulfilling the order.It submits the request for the sameto its internal procurement application.

    Dells procurement applicationcommunicates with Intels orderparts Web service.

    HTTP

    RMI/IIOP

    Dell.com

    EJB ProcurementApplication

    EJB acts asWeb serviceclient

    Intel Order PartsApplication

    EJB as Webservice

    Web serviceWrapper

    RMI/IIOP

    SOAP/HTTP

    Overview 15

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 15

  • The Bean ProviderThe bean provider supplies business components, or enterprise beans. Enter-prise beans are not complete applications, but rather are deployable compo-nents that can be assembled into complete solutions. The bean provider couldbe an internal department providing components to other departments.

    The Application AssemblerThe application assembler is the overall application architect. This party isresponsible for understanding how various components fit together and writ-ing the applications that combine components. An application assembler mayeven author a few components along the way. His or her job is to build anapplication from those components that can be deployed in a number of set-tings. The application assembler is the consumer of the beans supplied by thebean provider.

    The application assembler could perform any or all of the following tasks:

    From knowledge of the business problem, decide which combination ofexisting components and new enterprise beans are needed to providean effective solution; in essence, plan the application assembly.

    Supply a user interface (perhaps Swing, servlet or JSP, application orapplet) or a Web Service.

    Write new enterprise beans to solve some problems specific to yourbusiness problem.

    16 Chapter 1

    JAVABEANS VERSUS ENTERPRISE JAVABEANS

    You may have heard of another standard called JavaBeans. JavaBeans arecompletely different from Enterprise JavaBeans.

    In a nutshell, JavaBeans are Java classes that have get/set methods on them.They are reusable Java components with properties, events, and methods(similar to Microsoft ActiveX controls) that can be easily wired together tocreate (often visual) Java applications.

    The JavaBeans framework is lightweight compared to Enterprise JavaBeans.You can use JavaBeans to assemble larger components or to build entireapplications. JavaBeans, however, are development components and are notdeployable components. You typically do not deploy a JavaBean; rather,JavaBeans help you construct larger software that is deployable. And becausethey cannot be deployed, JavaBeans do not need to live in a runtimeenvironment and hence, in a container. Since JavaBeans are just Java classes,they do not need an application server to instantiate them, to destroy them,and to provide other services to them. An EJB application can use JavaBeans,especially when marshalling data from EJB layer to another, say to componentsbelonging to a presentation tier or to a non-J2EE application written in Java.

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 16

  • Write the code that calls on components supplied by bean providers.

    Write integration code that maps data between components suppliedby different bean providers. After all, components wont magicallywork together to solve a business problem, especially if different partieswrite the components.

    An example of an application assembler is a systems integrator, a consultingfirm, or an in-house programmer.

    The EJB DeployerAfter the application assembler builds the application, the application must bedeployed (and go live) in a running operational environment. Some challengesfaced here include the following:

    Securing the deployment with a hardware or software firewall andother protective measures.

    Integrating with enterprise security and policy repositories, whichoftentimes is an LDAP server such as Sun Java System Directory Server(formerly Netscape Directory Server), Novell Directory Server, orMicrosoft Active Directory.

    Choosing hardware that provides the required level of quality of ser-vice.

    Providing redundant hardware and other resources for reliability andfault tolerance.

    Performance-tuning the system.

    Frequently the application assembler (who is usually a developer or sys-tems analyst) is not familiar with these issues. This is where the EJB deployercomes into play. EJB deployers are aware of specific operational requirementsand perform the tasks above. They understand how to deploy beans withinservers and how to customize the beans for a specific environment. The EJBdeployer has the freedom to adapt the beans, as well as the server, to the envi-ronment in which the beans are to be deployed.

    An EJB deployer can be a staff person, an outside consultant, or a vendor.

    The System AdministratorOnce the deployment goes live, the system administrator steps in to overseethe stability of the operational solution. The system administrator is responsi-ble for the upkeep and monitoring of the deployed system and may make useof runtime monitoring and management tools that the EJB server provides.

    Overview 17

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 17

  • For example, a sophisticated EJB server might page a system administratorif a serious error occurs that requires immediate attention. Some EJB serversachieve this by developing hooks into professional monitoring products, suchas Tivoli and Computer Associates. Others like JBoss are providing their ownsystems management by supporting the Java Management Extension (JMX)technology.

    The Container and Server ProviderThe container provider supplies an EJB container (the application server). Thisis the runtime environment in which beans live. The container supplies mid-dleware services to the beans and manages them. There are about 20 SunMicrosystemscertified J2EE application servers. Although a complete list canbe obtained from http://java.sun.com/j2ee/licensees.html, some of the popu-lar J2EE application servers include BEA WebLogic, Sun Java System Applica-tion Server (formerly, Sun ONE Application Server), IBM WebSphere, OracleApplication Server, and of course JBoss open source application server.

    The server provider is the same as the container provider. Sun has not yetdifferentiated these (and may never do so). We will use the terms EJB containerand EJB server interchangeably in this book.

    The Tool VendorsTo facilitate the component development process, there should be a standard-ized way to build, manage, and maintain components. In the EJB Ecosystem,there are several integrated development environments (IDEs) that assist you inrapidly building and debugging components. Some of the popular closed

    18 Chapter 1

    QUALITIES OF SERVICE IN EJB

    The monitoring of EJB deployments is not specified in the EJB specification. It isan optional service that advanced EJB users can provide. This means that eachEJB server could provide the service differently.

    At first blush you might think this hampers application portability. However,in reality, this service should be provided transparently behind the scenes, andshould not affect your application code. It is a quality of service that liesbeneath the application level and exists at the systems level. Changingapplication servers should not affect your EJB code.

    Other transparent qualities of service not specified in the EJB specificationinclude load balancing, transparent fail-over, caching, clustering, andconnection pooling algorithms.

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 18

  • source and open source EJB development IDEs include Borland JBuilder, Ora-cle JDeveloper, BEA WebLogic Workshop, IBM WebSphere Studio ApplicationDeveloper, Sun Microsystems Java Studio (formerly Forte for Java), NetBeans,and last but not least, Eclipse.

    Most of these tools enable you to model components using unified model-ing language (UML), which is the diagram style used in this book. You can alsogenerate EJB code from these UML models. Some of the examples of special-ized closed source products in this space include Borland Together and IBMRational line of products. Also there are a bunch of open source code utilitiesand tools, which we discuss in Chapter 11, that can be used for UML modelingand code generation.

    There are other tools as well, which you will need to develop your EJB appli-cations rapidly and successfully. The categories mainly include testing tools(JUnit), build tools (Ant/XDoclet), and profilers (Borland OptimizeIt or QuestSoftware JProbe).

    Summary of RolesFigure 1.5 summarizes the interaction of the different parties in EJB.

    You may be wondering why so many different participants are needed toprovide an EJB deployment. The answer is that EJB enables companies or indi-viduals to become experts in certain roles, and division of labor leads to best-of-breed deployments.

    The EJB specification makes each role clear and distinct, enabling experts indifferent areas to participate in a deployment without loss of interoperability.Note that some of these roles could be combined as well. For example, the EJBserver and EJB container today come from the same vendor. Or at a smallstartup company, the bean provider, application assembler, and deployercould all be the same person, who is trying to build a business solution usingEJB from scratch. What roles do you see yourself playing?

    For some of the parties EJB merely suggests possible duties, such as the sys-tem administrator overseeing the well being of a deployed system. For otherparties, such as the bean provider and container provider, EJB defines a set ofstrict interfaces and guidelines that must be followed or the entire ecosystemwill break down. By clearly defining the roles of each party, EJB lays a founda-tion for a distributed, scalable component architecture where multiple ven-dors products can interoperate.

    Overview 19

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 19

  • Figu

    re 1

    .5Th

    e pa

    rtie

    s of

    EJB

    .

    Bea

    n P

    rovi

    der

    EJB

    Co

    nta

    iner

    /Ser

    ver

    Pro

    vid

    er

    Dep

    loye

    rS

    yste

    m A

    dm

    inis

    trat

    or

    (Mai

    nta

    ins

    Dep

    loym

    ent)

    Ap

    plic

    atio

    nA

    ssem

    ble

    rC

    onst

    ruct

    Ent

    erpr

    ise

    Bea

    ns

    Bui

    ld A

    pplic

    atio

    nD

    eplo

    y S

    yste

    m

    Sup

    ply

    EJB

    Con

    tain

    er/S

    erve

    r

    Too

    l Pro

    vid

    er

    Sup

    ply

    Tool

    s

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 20

  • The Java 2 Platform, Enterprise Edition (J2EE)

    EJB is only a portion of a larger offering from the Java Community Process(a.k.a. JCPa Java industry standards body) called the Java 2 Platform, Enter-prise Edition (J2EE). The mission of J2EE is to provide a platform-indepen-dent, portable, multiuser, secure, and standard enterprise-class platform forserver-side deployments written in the Java language.

    J2EE is a specification, not a product. J2EE specifies the rules of engagementthat people must agree on when writing enterprise software. Vendors thenimplement the J2EE specifications with their J2EE-compliant products.

    Because J2EE is a specification (meant to address the needs of many compa-nies), it is inherently not tied to one vendor; it also supports cross-platformdevelopment. This encourages vendors to compete, yielding best-of-breedproducts. It also has its downside, which is that incompatibilities between ven-dor products will arisesome problems due to ambiguities with specifica-tions, other problems due to the human nature of competition.

    J2EE is one of three different Java platforms. Each platform is a conceptualsuperset of the next smaller platform.

    The Java 2 Platform, Micro Edition (J2ME) is a development platformfor applications running on mobile Java-enabled devices, such asPhones, Palm Pilots, Pagers, set-top TV boxes, and so on. This is arestricted form of the Java language due to the inherent performanceand capacity limitations of small-form-factor wireless devices.

    The Java 2 Platform, Standard Edition (J2SE) defines a standard forcore libraries that can be used by applets, applications, J2EE applica-tions, mobile applications, and such. These core libraries span a muchwider spectrum including input/output, graphical user interface facili-ties, networking, and so on. This platform contains what most peopleuse in standard Java programming.

    The Java 2 Platform, Enterprise Edition (J2EE) is an umbrella standardfor Javas enterprise computing facilities. It basically bundles togethertechnologies for a complete enterprise-class server-side developmentand deployment platform in Java.

    J2EE is significant because it creates a unified platform for server-side Javadevelopment. The J2EE stack consists of the following:

    Specifications. Each enterprise API within J2EE has its own specifica-tion, which is a PDF file downloadable from www.jcp.org. Each timethere is a new version of J2EE, the J2EE Expert Group at JCP locksdown the versions of each Enterprise API specification and bundlesthem together as the de facto versions to use when developing withJ2EE. This increases code portability across vendors products, because

    Overview 21

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 21

  • each vendor supports exactly the same API revision. This is analogousto a company such as Microsoft releasing a new version of Windowsevery few years: Every time a new version of Windows comes out,Microsoft locks down the versions of the technologies bundled withWindows and releases them together.

    Test suite. Sun provides a test suite (a.k.a. Test Compatibility Kit orTCK) for J2EE server vendors to test their implementations against. If aserver passes the tests, Sun issues a J2EE compliance brand, alertingcustomers that the vendors product is indeed J2EE-compliant. Thereare numerous J2EE-certified vendors, and you can read reviews of theirproducts for free on TheServerSide.com.

    Reference implementation. To enable developers to write code againstJ2EE Sun provides its own free reference implementation for each ver-sion of J2EE. Sun is positioning it as a low-end reference platform,because it is not intended for commercial use. You can download thereference implementation for J2EE 1.4, the latest version of J2EE plat-form that includes EJB 2.1, the technology of focus in this book, fromhttp://java.sun.com/j2ee/download.html.

    The J2EE TechnologiesJ2EE is a robust suite of middleware services that make life very easy forserver-side application developers. J2EE builds on the existing technologies inthe J2SE. J2SE includes support for core Java language semantics as well asvarious libraries (.awt, .net, .io, and so on). Because J2EE builds on J2SE, aJ2EE-compliant product must not only implement all of J2EE, but must alsoimplement all of J2SE. This means that building a J2EE product is anabsolutely huge undertaking. This barrier to entry has resulted in significantindustry consolidation in the Enterprise Java space, with a few players emerg-ing from the pack as leaders.

    In this book, we will discuss EJB 2.1, an integral part of J2EE 1.4. Some of themajor J2EE technologies are shown working together in Figure 1.6.

    To understand more about the real value of J2EE, here are some of theimportant technologies and APIs that a J2EE 1.4-compliant implementationwill support for you.

    Enterprise JavaBeans (EJB). EJB defines how server-side componentsare written and provides a standard contract between components andthe application servers that manage them. EJB is the cornerstone forJ2EE and uses several other J2EE technologies.

    22 Chapter 1

    05_576828 ch01.qxd 11/3/04 11:37 AM Page 22

  • Figure 1.6 A J2EE deployment.

    Java API for XML RPC (JAX-RPC). JAX-RPC is the main technologythat provides support for developing Web Services on the J2EE plat-form. It defines two Web Service endpoint modelsone based onservlet technology and another based on EJB. It also specifies a lot ofruntime requirements regarding the way Web Services should be sup-ported in a J2EE runtime. Another specification called Web Services forJ2EE defines deployment requirements for Web Services and uses theJAX-RPC programming model. Chapter 5 discusses support of WebServices provided by both these specifications for EJB applications.

    Java Remote Method Invocation (RMI) and RMI-IIOP. RMI is the Javalanguages native way to communicate between distributed objects,such as two different objects running on different machines. RMI-IIOP

    Firewall

    EJBs

    Existing SystemLegacy System

    ERP System

    IIOP

    Client Tier

    J2EE Server

    Back-EndSystems

    BusinessPartner

    or Other System

    Servlets

    Business Partneror Other System

    Applets,Applications,

    CORBA Clients

    IIOPWeb services technologies(SOA