she speaks frequently at major cover the latest features ...mastering enterprise javabeans ™ 3.0...

721
T IMELY. P RACTICAL. R ELIABLE. Rima Patel Sriganesh Gerald Brose Micah Silverman Mastering Enterprise JavaBeans 3.0

Upload: others

Post on 12-Feb-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

  • TIMELY. PRACTICAL. RELIABLE.

    Rima Patel SriganeshGerald BroseMicah Silverman

    Wiley Technology Publishing Timely. Practical. Reliable.

    An invaluable tutorial on the dramatic changes to Enterprise JavaBeans (EJB™) 3.0

    Covering basic through advanced subjects,Mastering Enterprise JavaBeans 3.0 ismore than 50 percent new and revised.Four new chapters and one new appendixcover the latest features of this new release,and in-depth coverage of the Java™Persistence API and the entities definedtherein is provided. The authors’ maingoal is to get you programming with EJBimmediately. To that end, you’ll learn:

    • How to implement EJB 3.0 beans,with emphasis on session beans(stateful and stateless) and mes-sage-driven beans

    • Both basic and advanced concepts(such as inheritance, relationships,and so on) of Java Persistence APIdefined entities

    • How to develop and deploy EJB 3.0Web services

    • How to secure EJB applications

    • How to integrate EJB applicationswith the outside world via the JavaEE Connector technology

    • Tips and techniques for designing anddeploying EJB for better performance

    • How clustering in large-scale EJBsystems works

    Visit the companion Web site at www.wiley.com/go/sriganesh

    Mastering Enterprise JavaBeans

    ™3.0Sriganesh

    BroseSilverman

    Programming Languages/Java $45.00 USA/$58.99 CAN/£29.99 UK

    ISBN: 0-471-78541-5

    Mastering EnterpriseJavaBeans™ 3.0

    Featuring myriad changes from its previous versions, EJB 3.0 boasts avery different programming anddeployment model, with nearly everyaspect of development affected. Even themost experienced EBJ and J2EE™ developers will need to relearn how tobest use EJB to develop mission-criticalapplications. This author team of expertshas taken their combined skills inarchitecture, development, consulting,and knowledge transfer to explain thevarious changes to EJB 3.0 as well asthe rationale behind these changes.You’ll learn the concepts and techniquesfor authoring distributed, enterprisecomponents in Java from the ground up.

    • Best practices for EJB applicationdesign, development, and testing

    Rima Patel Sriganesh is a staff engi-neer in the technology outreachgroup at Sun Microsystems, Inc.She speaks frequently at majorindustry conferences and is acoauthor of Mastering EnterpriseJavaBeans, Third Edition (Wiley).

    Gerald Brose works for Projektron,a German vendor for project man-agement software. He maintainsthe Open Source ORB JacORB.Gerald holds a Ph.D. in computerscience and has published widely onJava, CORBA, and security.

    Micah Silverman, a SoftwareArchitect for 15 years, has special-ized in Java since 1995. He foundedM*Power Internet Services, Inc.,providing architect, development,and security services. He has contributed to books and publishednumerous articles.

    The companion Web site providesall the source code, updates to thesource code examples, and a PDFversion of the book.

    785415 Cover_rb2.qxp 5/25/06 2:14 PM Page 1

  • Mastering Enterprise JavaBeans™ 3.0

    01_785415 ffirs.qxp 6/5/06 7:09 PM Page i

  • 01_785415 ffirs.qxp 6/5/06 7:09 PM Page ii

  • Rima Patel SriganeshGerald Brose

    Micah Silverman

    Mastering EnterpriseJavaBeans™ 3.0

    01_785415 ffirs.qxp 6/5/06 7:09 PM Page iii

    Click here to purchase this book.

    http://www.amazon.com/gp/product/0471785415/ref=sr_11_1/103-1174895-6545420?%5Fencoding=UTF8jpiscitellicover

  • Mastering Enterprise JavaBeans™ 3.0Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in CanadaISBN-13: 978-0-471-78541-5ISBN-10: 0-471-78541-5Manufactured in the United States of America10 9 8 7 6 5 4 3 2 11B/SS/QW/QW/IN

    No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by anymeans, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sec-tions 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Pub-lisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center,222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for per-mission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indi-anapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

    Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or war-ranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim allwarranties, including without limitation warranties of fitness for a particular purpose. No warranty may becreated or extended by sales or promotional materials. The advice and strategies contained herein may not besuitable for every situation. This work is sold with the understanding that the publisher is not engaged in ren-dering legal, accounting, or other professional services. If professional assistance is required, the services of acompetent professional person should be sought. Neither the publisher nor the author shall be liable for dam-ages arising herefrom. The fact that an organization or Website is referred to in this work as a citation and/ora potential source of further information does not mean that the author or the publisher endorses the infor-mation the organization or Website may provide or recommendations it may make. Further, readers should beaware that Internet Websites listed in this work may have changed or disappeared between when this workwas written and when it is read.

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

    Library of Congress Cataloging-in-Publication DataSriganesh, Rima Patel.Mastering enterprise JavaBeans 3.0 / Rima Patel Sriganesh, Gerald Brose,

    Micah Silverman.p. cm.

    Includes index.ISBN-13: 978-0-471-78541-5 (paper/website)ISBN-10: 0-471-78541-5 (paper/website)1. JavaBeans. 2. Java (Computer program language) I. Brose, Gerald. II. Silverman, Micah. III. Title. QA76.73.J38S756 2006005.13'3--dc22

    2006011333

    Trademarks: Wiley, the Wiley logo, and related trade dress are trademarks or registered trademarks of JohnWiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used withoutwritten permission. Enterprise JavaBeans is a trademark of Sun Microsystems, Inc. All other trademarks arethe property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendormentioned in this book.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may notbe available in electronic books.

    01_785415 ffirs.qxp 6/5/06 7:09 PM Page iv

    www.wiley.com

  • Rima wishes to dedicate this book to her dearest and most lovingMummy and Papa, on their completing 60 years of a wholesome and

    exemplary life this year, and to her beloved husband, Sriganesh.

    To my wonderful wife, Christine, and my sons Johannes and Julius.

    For Dr. Charles Marshall, who taught me Excellence.

    01_785415 ffirs.qxp 6/5/06 7:09 PM Page v

  • 01_785415 ffirs.qxp 6/5/06 7:09 PM Page vi

  • Rima Patel Sriganesh is a staff engineer presently working in the TechnologyOutreach group at Sun Microsystems, Inc. She specializes in Java, XML, and inte-gration platforms. Rima represents Sun at various financial services standards.She is a coauthor of three books and usually publishes her take on technologyin the form of papers and blogs. She also speaks frequently at various industryconferences.

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

    Gerald Brose works as head of software development for Projektron, a soft-ware vendor that produces project management software. In previous jobs hehas worked as a product manager, software architect, and researcher. He holdsa Ph.D. in computer science.

    Gerald is an expert in distributed object computing and middleware secu-rity, including CORBA, J2EE, and Web services. Gerald also coauthored JavaProgramming with CORBA, also published by Wiley.

    Gerald is the maintainer of the JacORB project, the most widely used opensource ORB for Java, which is part of the JBoss and JOnAS J2EE applicationservers. He lives with his wife and two sons in Berlin, Germany.

    Micah Silverman has been a professional software architect and consultant forover 15 years. He has been developing with Java since its release in 1995. Inthat same year, he founded M*Power Internet Services, Inc., a consulting com-pany providing software architecting, development, and security services. Hehas written numerous articles on software development, information security,and operating systems.

    About the Authors

    vii

    01_785415 ffirs.qxp 6/5/06 7:09 PM Page vii

    Click here to purchase this book.

    http://www.amazon.com/gp/product/0471785415/ref=sr_11_1/103-1174895-6545420?%5Fencoding=UTF8jpiscitellicover

  • 01_785415 ffirs.qxp 6/5/06 7:09 PM Page viii

  • Executive EditorRobert Elliott

    Development EditorTom Dinse

    Technical EditorDaniel Rubio

    Production EditorFelicia Robinson

    Copy EditorFoxxe Editorial Services

    Editorial ManagerMary Beth Wakefield

    Production ManagerTim Tate

    Vice President and Executive Group Publisher

    Richard Swadley

    Vice President and Executive Publisher

    Joseph B. Wikert

    Project CoordinatorMichael Kruzil

    Graphics and Production Specialists

    Jennifer ClickLauren GoddardJoyce HaugheyStephanie D. JumperBarry OffringaLynsey OsbornHeather RyanBrent SavageAlicia B. South

    Quality Control TechniciansAmanda BriggsJessica Kramer

    Proofreading and IndexingTechbooks

    Credits

    ix

    01_785415 ffirs.qxp 6/5/06 7:09 PM Page ix

    Click here to purchase this book.

    http://www.amazon.com/gp/product/0471785415/ref=sr_11_1/103-1174895-6545420?%5Fencoding=UTF8jpiscitellicover

  • 01_785415 ffirs.qxp 6/5/06 7:09 PM Page x

  • About the Authors vii

    Acknowledgments xxiii

    Introduction xxv

    Part I Overview 1

    Chapter 1 Overview 3A Prelude to Enterprise JavaBeans 4

    Software Components 4The Need for Componentization 4

    Infrastructure Needs of Distributed Applications 5Application Server–Class Software 8

    Building Middleware Services from Scratch 8Buying Middleware Services via Application Server Software 9

    Standardization of Component Frameworks 9Enterprise JavaBeans Technology 10

    Why Java? 11EJB as a Business Tier Component 12Distributed Computing: The Foundation of EJB 14EJB Middleware Services 16

    Explicit Middleware Approach 16Implicit Middleware Approach 17Implicit vs. Explicit Middleware Services in EJB 18

    Roles in the EJB Application Life Cycle 18The Bean Provider 19The Application Assembler 19The EJB Deployer 20The System Administrator 20

    Contents

    xi

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xi

    Click here to purchase this book.

    http://www.amazon.com/gp/product/0471785415/ref=sr_11_1/103-1174895-6545420?%5Fencoding=UTF8jpiscitellicover

  • EJB Ecosystem 22EJB Container 24EJB Tools 24

    Service-Oriented Architectures and Enterprise JavaBeans 25Defining Service-Oriented Architectures 26

    SOA and Web Services 26SOA and Component Architectures 27

    Divide and Conquer to the Extreme with Reusable Services 27The Java Platform, Enterprise Edition 5.0 (Java EE) 29

    The Java EE Technologies 31Summary 34

    Chapter 2 Pre-EJB 3.0: The World That Was 37What Constituted a Pre-EJB 3.0 Enterprise Bean? 38Developing and Deploying a Pre-EJB 3.0 Enterprise Java Bean 41

    The Remote Interface 42The Local Interface 43The Home Interface 44The Local Home Interface 45The Bean Class 45Deployment Descriptor 47Deploying The Bean 47HelloWorldEJB Client 48

    Dissecting EJB 2.x 50Complexity: The Overarching Issue of EJB 2.x 50

    Development Complexities 51Deployment Complexities 53Debugging and Testing Complexities 54

    What Needs to Be Done to Improve EJB 2.x? 55Summary 55

    Chapter 3 The New Enterprise JavaBean 57Introducing EJB 3.0 57

    EJB Container 59Types of Beans 61RMI-IIOP: The Protocol of the Bean 65EJB and Location Transparency 66Enterprise Bean Environment 67Anatomy of the “New” Bean 68The Role of EJB Home and Object Interfaces 72

    The EJB 3.0 Simplified API 73Elimination of Home and Object Interfaces 74Elimination of Component Interface 74Use of Annotations 76

    Annotations and Bean Development 77Annotations and Deployment Descriptors 77The Good, the Bad, and the Ugly of Deployment Annotations 79

    Simplified Access to Environment 80Packaging and Deployment of the “New” Bean 81

    xii Contents

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xii

  • Example of EJB 3.0 Bean 82The Business Interface 83The Bean Class 83The Deployment Descriptor 84The Client 85

    Summary of Terms 86Summary 87

    Part II The Triad of Beans and Entities 89

    Chapter 4 Introduction to Session Beans 91Session Bean Lifetime 91Session Bean Subtypes 92

    Stateless Session Beans 92Stateful Session Beans 94

    Special Characteristics of Stateful Session Beans 94Achieving the Effect of Pooling with Stateful Beans 95The Rules Governing Conversational State 96Activation and Passivation Callbacks 97Summary of Callback Methods 100A Simple Stateful Session Bean 100

    The Count Bean’s Remote Interface 100The Count Bean 102The Count Bean’s Callback Interceptor 104The Count Bean’s Deployment Descriptor 106The Count Bean’s Proprietary Descriptor and Ejb-jar File 107The Count Bean’s Client Code 107Running the Client 109

    Life-Cycle Diagrams for Session Beans 110Summary 114

    Chapter 5 Writing Session Bean Web Services 115Web Services Concepts 115

    Web Services Standards 118WSDL 118SOAP 120

    XML Artifacts and Platform Independence 121Implementing a Web Service 122

    WSDL and the XML/Java Mapping 125Packaging and Deploying a Web Service Session Bean 125

    Implementing a Web Service Client 126Summary 128

    Chapter 6 Java Persistence: Programming with Entities 129Object-Relational Mapping 130What Is an Entity? 133

    Entities versus Session Beans 134Persistence Provider 135Entity Classes 135

    Contents xiii

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xiii

  • Accessing Entities in the Persistence Context 138Extended Persistence Context 141

    Packaging and Deploying Entity Classes 143The EntityManager API 144

    Entity Life Cycle 145Life-Cycle Callbacks 147

    Database Synchronization 148Direct Entity Data Manipulation 149Concurrent Access and Locking 150Entity Lookup and Query API 153Named Queries 154

    Summary 155

    Chapter 7 Introduction to Message-Driven Beans 157Motivations for Messaging 157The Java Message Service (JMS) 160

    Messaging Domains 161The JMS API 162

    Integrating JMS with EJB 167What Is a Message-Driven Bean? 169

    Developing Message-Driven Beans 173The Semantics 173A Simple Example 175

    The Bean Implementation Class 175The Deployment Descriptor 177More Metadata: Activation Configuration Properties 178The Client Program 183

    Advanced Concepts 183Transactions 183Security 183Load Balancing 183Duplicate Consumption in a Cluster 184

    JMS Message-Driven Bean Gotchas 186Message Ordering 186Missed @PreDestroy Calls 186Poison Messages 187How to Return Results Back to Message Producers 190

    An Alternative Request/Response Paradigm 194The Future: Asynchronous Method Invocations 195

    Summary 195

    Chapter 8 Adding Functionality to Your Beans 197Calling Beans from Other Beans 197

    Default JNDI Lookups 198Annotations 199

    Common Annotations 200Business Interface Annotations 200Other Stateful Annotations 202

    xiv Contents

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xiv

  • Dependency Injection 205Resource References 205

    Interceptors 209Summary 214

    Part III Advanced Enterprise JavaBeans Concepts 217

    Chapter 9 Advanced Persistence Concepts 219Inheritance 220

    Single Table per Class Hierarchy 223Separate Table per Subclass 230Single Table per Concrete Entity Class 232Other Modes of Inheritance 232

    Polymorphism 234Relationships 237

    Relationship Types 237One-to-One 238One-to-Many 245Many-to-Many 254

    EJB-QL Enhancements 261Bulk Updates and Deletes 261JOIN Operations 265GROUP BY and HAVING clauses 266Projection 267Fun with Queries 268

    Dynamic Queries and Named Parameters 268Subqueries 268

    Object Construction in SELECT Statements 269Summary 270

    Chapter 10 Transactions 271Motivation for Transactions 272

    Atomic Operations 272Network or Machine Failure 273Multiple Users Sharing Data 274

    Benefits of Transactions 275The ACID Properties 276

    Transactional Models 278Flat Transactions 278

    How Transactional State Is Rolled Back 280Nested Transactions 280Other Transactional Models 281

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

    and Transaction Contexts 285

    Contents xv

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xv

  • Java Transaction Service and Java Transaction API 285OTS and Java Transaction Service 285The Java Transaction API 286JTS and Distributed Transaction Interoperability

    across Application Servers 287Enterprise JavaBeans Transactions 288

    Underlying Transaction System Abstraction 288Container-Managed, Bean-Managed, and

    Client-Controlled Transactions 288Container-Managed Transactions 289Client-Controlled Transactions 290

    Choosing a Transaction Style 291Container-Managed Transactions 292

    EJB Transaction Attribute Values 293Required 293RequiresNew 294Supports 294Mandatory 294NotSupported 295Never 295Transaction Attribute Summary 295

    Container-Managed Transaction Example 296Applicability of Transaction Attributes to Various Beans 300

    Bean-Managed Transactions 302The javax.transaction.UserTransaction Interface 303Bean-Managed Transaction Example 306

    Client-Controlled Transactions 307Transactional Isolation 307

    The Need for Concurrency Control 308Isolation Levels 310The Dirty Read Problem 310

    READ UNCOMMITTED 311READ COMMITTED 311

    The Unrepeatable Read Problem 312REPEATABLE READ 312

    The Phantom Problem 313SERIALIZABLE 313

    Transaction Isolation Summary 314Using Various Isolation Levels in EJB Applications 314Pessimistic and Optimistic Concurrency Control 315

    Designing Transactional Conversations in EJB 316Summary 319

    xvi Contents

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xvi

  • Chapter 11 Security 321Introduction 322

    Violations, Vulnerabilities, and Risk 323Controls 323

    Web Application Security 325Authentication in Web Applications 326Authorization 327Confidentiality and Integrity 328

    Understanding EJB Security 329Authentication in EJB 329

    JAAS Overview 329The JAAS Architecture 331JAAS Sample Code 333

    Authorization in EJB 341Security Roles 341Performing Programmatic Authorization 342Performing Declarative Authorization 346Declarative or Programmatic? 351

    Security Propagation 351Secure Interoperability 353

    IIOP/SSL 353CSIv2 354

    Web Services Security 356End-to-End Security 357XML Digital Signature and XML Encryption 358SAML 361WS-Security 362

    Summary 364

    Chapter 12 EJB Timers 365Scheduling 365EJB and Scheduling 366The EJB Timer Service 368

    Timer Service API 368javax.ejb.TimerService 369javax.ejb.Timer 370javax.ejb.TimedObject 370javax.ejb.TimerHandle 371

    Interaction between the EJB and the Timer Service 371Timer Example: CleanDayLimitOrdersBean 373

    The CleanDayLimitOrders Business Interface 374The CleanDayLimitOrdersBean Class 374The CleanDayLimitOrders EJB Deployment Descriptor 376The CleanDayLimitOrders EJB Client 377Running the Client 378

    Strengths and Limitations of EJB Timer Service 379Summary 380

    Contents xvii

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xvii

  • Chapter 13 EJB Best Practices 381When to Use EJB 382How to Choose a Web Application Framework

    to Work with EJB 385Applying Model Driven Development in EJB Projects 387Applying Extreme Programming in EJB Projects 389Testing EJB 392

    EJB Unit Testing 392Use Frameworks for EJB Unit Testing 393

    The JUnit Framework 393Mock Object Frameworks 394

    Implementing Client-Side Callback Functionality in EJB 395JMS 395Remote Method Invocation 396Web Service 396

    Choosing between Servlets and Stateless Session Beans as Service Endpoints 396

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

    Aspect-Oriented Programming 397When to Use AOP in EJB Applications 398

    Support Custom Concerns 398Are Interceptors AOP? 398Supply Aspects to the World Outside the EJB Container 399

    Reflection, Dynamic Proxy, and EJB 400Deploying EJB Applications to Various Application Servers 400Debugging EJB 402Inheritance and Code Reuse in EJB 404Writing Singletons in EJB 405When to Use XML with EJB 406When to Use Messaging versus RMI-IIOP 407Summary 410

    Chapter 14 EJB Performance Optimizations 411It Pays to Be Proactive! 411The Stateful versus Stateless Debate from a

    Performance Point of View 413How to Guarantee a Response Time with Capacity Planning 415Use Session Façade for Better Performance 416Choosing between Local Interfaces and Remote Interfaces 418Partitioning Your Resources 419Tuning Stateless Session Beans 420Tuning Stateful Session Beans 421Tuning Entities 423Tuning Message-Driven Beans 426Tuning Java Virtual Machine 427Miscellaneous Tuning Tips 429Choosing the Right EJB Server 430Summary 431

    xviii Contents

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xviii

  • Chapter 15 EJB Integration 433Why Does Integration Matter? 433

    Integration Styles 434EJB and Integration 435Java EE Connector Architecture 436

    Why Java EE Connectors? 436Integrating Java EE Platform with Non-IIOP World 436The M x N Integration Problem 436The Infrastructure Services Problem 438

    Resource Adapter Interaction with Java EE Components 439Resource Adapter Interaction with Application Server 440

    The Java EE Connector API 442The javax.resource Package 442The javax.resource.cci Package 443The javax.resource.spi Package 443The javax.resource.spi.endpoint Package 451The javax.resource.spi.security Package 451The javax.resource.spi.work Package 452

    System Contracts 453Life Cycle Management 453Connection Management 454Security Management 458

    Container-Managed Sign-On 458Component-Managed Sign-On 459

    Transaction Management 460Local Transaction Management Contract 460Global Transaction Management Contract 461

    Work Management 462Message Inflow 464

    Connector Example: OutboundLoanRA 467Example Architecture 468JavaLoanApp.java 469LoanApp.dll 470OutboundLoanRA 471

    OutboundLoanRA Client Contracts 471OutboundLoanRA System Contracts 485Deploying OutboundLoanRA 493

    LoanRatesEJB 495Developing LoanRatesEJB 495

    LoanRatesClient 496Running the Client 497Extending OutboundLoanRA 502

    Integration Best Practice: When to Use Which Technology 502When to Use JMS and JMS-Based MDB 502When to Use Java EE Connectors 503When to Use Java Web Services 503

    Summary 504

    Contents xix

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xix

  • Chapter 16 Clustering 505Overview of Large-Scale Systems 505

    What Is a Large-Scale System? 506Load Balancing and Failover 509Clustering with Collocated or Distributed Java EE Containers 512

    Instrumenting Clustered EJBs 516How EJBs Can Be Clustered 516The Concept of Idempotence 518Stateless Session Bean Clustering 519

    Load Balancing 519Failover 519

    Stateful Session Bean Clustering 521Load Balancing 522Failover 522

    Entity Clustering 523Load Balancing 523Failover 523Caching 523Read-Only Caches 524Distributed Shared Object Caches 524Read-Mostly Caches 525

    Message-Driven Bean Clustering 526Other EJB Clustering Issues 526

    First Contact 527Initial Access Logic 527

    Summary 528

    Chapter 17 EJB-Java EE Integration: Building a Complete Application 529The Business Problem 529A Preview of the Final Web Site 530Scoping the Technical Requirements 534

    The Business Logic Tier 534Persistent Data: Entities 534Business Logic: Session and Message-Driven Beans 538

    The Presentation Tier 541What Are Servlets? 541What Are Java Server Pages? 543How Do I Combine Servlets, JSP, and EJB Components? 543JSP Files in Our E-Commerce Deployment 544

    Example Code 547Summary 558

    Appendix A RMI-IIOP and JNDI Tutorial 559Java RMI-IIOP 560

    Remote Method Invocations 560The Remote Interface 563The Remote Object Implementation 564Stubs and Skeletons 566

    xx Contents

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xx

  • Object Serialization and Parameter Passing 568Passing by Value 568

    Object Serialization 568Rules for Serialization 569What Should You Make Transient? 570Object Serialization and RMI 571Pass-by-Reference Semantics 572

    CORBA Interoperability with RMI-IIOP 573The Big Picture: CORBA and EJB Together 575

    The Java Naming and Directory Interface 576Why Use JNDI? 576Naming and Directory Services 576Problems with Naming and Directories 579Enter JNDI 579Benefits of JNDI 579The JNDI Architecture 580JNDI Concepts 581

    Naming Systems, Namespaces, and Composite Names 582Initial Context Factories 584

    Programming with JNDI 586Integrating RMI-IIOP and JNDI 588

    Binding an RMI-IIOP Server to a JNDI Name 589Looking Up an RMI-IIOP Server with JNDI 590

    Summary 591

    Appendix B Annotations 593Introduction to Annotations 593

    Annotations for EJB 596Background 597

    XDoclet 597Annotations in Java 598Pros and Cons 598

    EJB Annotation Reference 599Bean Type Annotations 599

    Common Annotations for Session and 603Message-Driven Beans

    Entity Annotations 611Summary 645

    Index 647

    Contents xxi

    02_785415 ftoc.qxp 6/5/06 6:53 PM Page xxi

  • 02_785415 ftoc.qxp 6/5/06 6:53 PM Page xxii

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

    As a special thanks, we’d like to acknowledge the great folks at John Wiley &Sons. They have been absolutely outstanding throughout this book’s evolution.In particular, we thank Bob Elliott, Tom Dinse, and Mary Beth Wakefield fortheir incredible efforts. We also thank Daniel Rubio for his insightful technicalreviews, and Linda DeMichiel for lending her help to the authors in under-standing the evolution of EJB 3.0 standard.

    I would like to thank my wife, Tes and my daughter, Shaina for being sopatient while I worked on this book.

    —Micah

    Acknowledgments

    xxiii

    03_785415 flast.qxp 6/5/06 6:53 PM Page xxiii

    Click here to purchase this book.

    http://www.amazon.com/gp/product/0471785415/ref=sr_11_1/103-1174895-6545420?%5Fencoding=UTF8jpiscitellicover

  • 03_785415 flast.qxp 6/5/06 6:53 PM Page xxiv

  • This book is a tutorial on Enterprise JavaBeans (EJB). It’s 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 it—what you are about to read is not easy. EJB incor-porates concepts from a wealth of areas, including distributed computing,databases, security, component-based architecture, message-oriented systems,and more. Combining them is a magnificent stride forward for the Java com-munity, but with that comes a myriad of concepts to learn and understand.This book will teach you the concepts and techniques for authoring distrib-uted, enterprise components in Java, and it will do so from the ground up. Youneed only to understand Java to understand this book.

    While you’re 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

    This book has had a long run and hence, a long history. The first edition of thisbook came out in 1999, followed by second and third editions in 2002 and early2005, respectively. Writing the latest edition of this popular title was not aneasy thing. There was an endless exchange of emails back and forth betweenthe authors before arriving at decisions about the topics to cover, the approachand the tone that should be used to cover them, and so on. We had to make

    Introduction

    xxv

    03_785415 flast.qxp 6/5/06 6:53 PM Page xxv

    Click here to purchase this book.

    http://www.amazon.com/gp/product/0471785415/ref=sr_11_1/103-1174895-6545420?%5Fencoding=UTF8jpiscitellicover

  • some tough calls when writing the second and third editions, and that did notchange in this edition. However, we are confident you’ll like them. Here areour goals for this edition:

    ■■ To update the book for EJB 3.0. EJB 3.0 is a sea change from the previousversions of EJB technology in that the programming and deploymentmodel is very different from its precursors. We take a top-downapproach in explaining these changes. We do not just talk about thechanges themselves but also discuss the rationale for making thesechanges to the existing EJB technology. In addition, this book goes anextra mile in providing in-depth coverage on the Java Persistence APIand the entities defined therein. The ability to use POJO (plain old Javaobject) style entities with enterprise beans is a much sought after fea-ture, and this book doesn’t save pages when it comes to providing realimplementation tips and best practices on how to use POJO entitieswith Enterprise JavaBeans.

    ■■ 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,search through the EJB specification using Adobe Acrobat. Readers whoare looking for a well-written book that is interactive and fun to read,and that covers the basics through advanced subjects in adequatedetails have come to the right place.

    ■■ To be concise. Your time as a reader is extremely valuable, and you’relikely waiting to read a stack of books besides this one. Given that mostpeople don’t have time to read 1,000-plus-page books, we actuallywanted to reduce the size of this book as much as possible. So we’vetightened things up and eliminated redundant examples. This way, youcan get to actually program with EJB immediately, rather than read abook for months on end. The irony of this story is that it was harder forus to write 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. The authors of this book have takentheir skills in architecture, development, consulting, and knowledgetransfer, and applied them to this book. Thus, we’ve infused this bookwith the following attributes:

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

    xxvi Introduction

    03_785415 flast.qxp 6/5/06 6:53 PM Page xxvi

  • ■■ 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 coauthors wrote this book,you’ll hear one voice. This was done to combine best-of-breedknowledge from several expert coauthors, while maintaining a uniform 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 have participated in the forums, worked onmany real-world projects, attended conferences and seminars, talked tothe people who have worked on the actual EJB specifications, and net-worked with the top experts throughout the world.

    ■■ To be vendor-neutral. The code listings for the examples in this bookwill work on any EJB application server, thereby making the book usefulimmaterial of the vendor you use. To stay away from the vendor wars,we have a policy to deploy all of our examples on the Java EE referenceimplementation rather than on a specific vendor’s platform.

    ■■ To take all the source code and make it available online. Becausewe’ve made the code available on the Web, you know it’s tested on thelatest version of the EJB application server. This will ensure that thecode you receive works right the first time.

    Organization of the Book

    The text is organized into the following five parts:

    ■■ Part I is a whirlwind introduction to EJB programming. Part I serves as agreat overview for people in a hurry. While Part I is essential informationfor EJB newcomers, veterans will also find nuggets of useful knowledge.The following chapters are included:

    ■■ Chapter 1 is a tour of enterprise computing. We’ll talk about component-based software, distributed computing frameworks,application server–class software, service-oriented architectures, andcontainers. In this regard, we’ll introduce EJB and Java EnterpriseEdition (Java EE).

    Introduction xxvii

    03_785415 flast.qxp 6/5/06 6:53 PM Page xxvii

  • ■■ Chapter 2 sets the scene for introducing the changes of EJB 3.0 inChapter 3. This chapter is a must read for long timers in EJB in thatit explains why a drastic change was needed in the programmingand deployment model of EJB.

    ■■ Chapter 3 shows you how to put together a simple EJB 3.0 bean ofthe HelloWorld fame. It introduces the EJB technology at a more fundamental level by bringing the discussions on IIOP, locationtransparency, JNDI naming services, annotations, deploymentdescriptors, and so on, to the fore.

    ■■ Part II devotes exclusive attention to programming with EJB. We’ll seehow to use the trio of session beans, session bean Web services, andmessage-driven beans. More interestingly, we will learn programmingof the new and cool Java Persistence API based POJO entities. Needlessto say, our discussions are accompanied with working examples.

    ■■ Chapter 4 introduces session beans. We’ll look at the differencebetween stateful and stateless session beans, how to code a sessionbean, and what’s going on behind the scenes with session beans.

    ■■ Chapter 5 shows how Web services can be implemented using theEJB model. In particular, we show how a stateless session bean canbe made available as a Web service.

    ■■ Chapter 6 introduces the Java Persistence API, which is a specificationcreated within the EJB Expert Group hosted at http://www.jcp.org. The mechanisms for development and deployment of POJOstyle entities defined in this specification are crucial in eliminatingthe complexity from EJB applications. This chapter explains thebasics of object-relational mapping and the notion of an entity withrespect to Java Persistence API.

    ■■ Chapter 7 covers message driven beans. We’ll begin with a reviewof message-oriented middleware (MOM) and the Java Message Service (JMS), which forms the backbone of all Java based MOMsoftware. Underneath, message driven beans use the JMS frame-work This is followed by an extensive discussion on various aspectsof writing message-oriented EJB applications and their respectiveexamples.

    ■■ Chapter 8 discusses the useful bits and pieces of EJB technologysuch as how to access resources made available using JNDI namingservices, how to use annotations in conjunction with EJB, and so on.It further explains the resource and dependency injection mechanismsas well as interceptors introduced in EJB 3.0 with examples.

    xxviii Introduction

    03_785415 flast.qxp 6/5/06 6:53 PM Page xxviii

  • ■■ Part III, the most exciting part of the book, covers advanced EJB con-cepts. The following chapters are included:

    ■■ Chapter 9 provides a comprehensive discussion on the advancedconcepts of persistent entities such as inheritance, polymorphism,entity relationships, and EJB Query Language (EJB-QL) enhance-ments. This chapter has a wealth of information for anyone whowants to get deeper into the world of persistent entities.

    ■■ Chapter 10 tackles transactions. Transactions are a crucial topic foranyone building an EJB application where ACIDity (Atomicity, Consistency, Isolation, and Durability) is a prerequisite. We’ll discusstransactions at a conceptual level followed by a discussion on howto apply them to EJB. We’ll learn a lot about the Java Transaction API(JTA) in the process.

    ■■ Chapter 11 provides in-depth coverage of EJB security and covers JavaAuthentication and Authorization Service (JAAS), secure interoperability,and Web Services security, within the purview of enterprise beans.

    ■■ Chapter 12 introduces the EJB Timer Service, which lets you sched-ule tasks for automatic execution at given point(s) in time.

    ■■ Chapter 13 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 14 covers EJB tips and techniques for designing anddeploying EJB for better performance. You’ll 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 as well as for Java Persistence API–based entities.

    ■■ Chapter 15 covers integration to and from EJB platform in depth.It provides an introduction to the various styles of integration, fol-lowed by a discussion of various techniques for integrating EJB withthe outside world. It explains the Java EE Connector Architecture, apredominant framework for integrating EJB with back-end enter-prise applications, and discusses a connector example.

    ■■ Chapter 16 discusses clustering in large-scale EJB systems. You’lllearn about how clustering works behind the scenes and learn a fewstrategies for how containers might support clustering. This is a crit-ical topic for anyone building a system that involves several machinesworking together.

    Introduction xxix

    03_785415 flast.qxp 6/5/06 6:53 PM Page xxix

  • ■■ Chapter 17 shows how to build a real-world Java EE applicationcontaining EJB components. We’ll see how the EJB componentsshould be used together with other technologies of the Java EE stacksuch as the persistent entities, as in an enterprise, as well as how toconnect them with clients using Java servlets and JavaServer Pages(JSP) technologies. We’ll also demonstrate how to design an EJBobject model using UML.

    ■■ The Appendices are a collection of ancillary EJB topics. Some developersmay want to read the appendices, while some may not feel the need to doso. Appendices A and B are provided in the book, whereas Appendices C,D, and E have been made available on the companion web site.

    ■■ 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 you’re just starting down the EJB road, you shall find itvery helpful to read this appendix first.

    ■■ Appendix B discusses the newly introduced annotations feature forthe Java platform. It provides a quick reference of various annota-tions supported by the EJB 3.0 specification. This can come in handywhile writing EJB code.

    ■■ Appendix C is a deployment descriptor reference guide. This willbe useful to you especially when you’re examining deploymentdescriptors and if you ever find yourself in a situation of modifyingthe deployment descriptors manually.

    ■■ 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 a class in theEJB programming API.

    NOTE Throughout the book, this icon will signal a tip, note, or other helpfuladvice on EJB programming.

    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 don’t know

    xxx Introduction

    03_785415 flast.qxp 6/5/06 6:53 PM Page xxx

  • UML, pick up a copy of The Unified Modeling Language User Guide (Addi-son-Wesley, ISBN 0201571684), which illustrates how to effectively use UML inyour everyday software. UML is a highly important achievement in object-ori-ented methodology. It’s 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. Thereyou’ll find:

    ■■ All of the source code you see in this book. The code comes completewith Ant scripts, ready to build and run. It can be deployed on anyapplication server that is Java EE 5–compliant.

    ■■ Updates to the source code examples.

    ■■ Error corrections from the text.

    ■■ A PDF copy of this book.

    The Web site is at www.wiley.com/go/sriganesh.

    Feedback

    When you begin your EJB programming, we’re sure you’ll have many experi-ences to share with other readers. Feel free to e-mail examples, case studies,horror stories, or tips that you’ve found helpful in your experience, and we’llpost them on the Web site.

    From Here

    Now that we’ve gotten the logistics out of the way, let’s begin our explorationof Enterprise JavaBeans 3.0.

    Introduction xxxi

    03_785415 flast.qxp 6/5/06 6:53 PM Page xxxi

  • 03_785415 flast.qxp 6/5/06 6:53 PM Page xxxii

  • PA R T

    In Part I, we introduce the server-side development platform, the Java Enter-prise Edition (Java EE), of which the Enterprise JavaBeans (EJB) componentarchitecture is a vital piece. Java EE is a conglomeration of concepts, pro-gramming standards, and innovations—all written in the Java programminglanguage. With Java EE, you can rapidly construct distributed, scalable, reli-able, and portable as well as secure server-side deployments.

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

    ■■ Chapter 2 focuses on explaining why the existing EJB technology,especially the programming and deployment model, has to change tosomething much simpler. Chapter 2 makes this point by walking usthrough an example of developing and deploying an EJB 2.1 bean.

    ■■ Chapter 3 gets down and dirty with EJB programming. Here, we’llwrite our first truly simple EJB 3.0 bean. In this chapter, we will alsointroduce other technologies and concepts that go hand in hand withEJB such as IIOP, JNDI naming services, annotations, deploymentdescriptors, and so on.

    Overview

    I

    04_785415 pt01.qxp 6/5/06 6:54 PM Page 1

    Click here to purchase this book.

    http://www.amazon.com/gp/product/0471785415/ref=sr_11_1/103-1174895-6545420?%5Fencoding=UTF8jpiscitellicover

  • 04_785415 pt01.qxp 6/5/06 6:54 PM Page 2

  • 3

    Enterprise JavaBeans (EJB) is a server-side component framework that simpli-fies 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-dor’s enterprise middleware services. For the benefit of those new to enter-prise computing, these concepts will be clarified shortly. EJB is a complicatedsubject and deserves a thorough explanation.

    This chapter introduces 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?

    Let’s kick things off with a brainstorming chapter.

    Overview

    C H A P T E R

    1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 3

  • A Prelude to Enterprise JavaBeans

    Simply put, an EJB is a component. What are components? Unfortunately, overthe years, this question has become a bit rhetorical, especially in the context ofsoftware engineering, because there is no exact or widely accepted answer toit. Henceforth, we will present our understanding of components.

    Software ComponentsThe online WordNet service hosted by Princeton University (http://wordnet.princeton.edu/perl/webwn) defines component quite simply and suc-cinctly as “an abstract part of something.” A software component goes onestep beyond. It is a concrete part of something. A software component is a pieceof code written to manifest the behavior of a corresponding abstract concept.Mostly, these abstract concepts find their underlying basis in the real world.For example, a MortgageDebt component might emulate the nuances associ-ated with actual mortgage debts of real-world entities such as people, corpo-rations, and so on. This explanation of components probably sounds a lot likehow objects were explained in the late 1980s. Even so, components differ fromobjects in a substantial manner—they live an independent existence. Thereinlies all the difference between objects and components.

    A component is a self-contained entity such that it can be reused in a similaror a completely different application, as long as the semantics of the compo-nent are well understood. A component must be packaged with all the requi-site artifacts so that it can live an independent, reusable existence outside ofthe original application. A business or system application can thus be designedto consist of multiple such reusable software components, each tasked with acertain functional responsibility.

    So what do we stand to gain by designing software applications in terms ofcomponents? How did we reach the conclusion that componentization wasthe right approach to take? Well, continue reading.

    The Need for ComponentizationOne of the fortuitous by-products of a more than decade-long U.S. JusticeDepartment vs. IBM antitrust lawsuit (more details of this landmark trial can befound at http://www.hagley.lib.de.us/1980.htm) was the emer-gence of a burgeoning software industry. The U.S. Justice Department basedthe antitrust lawsuit on the premise that IBM’s bundling of software, hardware(including peripherals), and services under a single pricing model marred theindependent players in the software as well as the peripherals markets. Upuntil then, IBM and other hardware vendors did not sell software but rather

    4 Chapter 1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 4

  • bundled it with hardware almost for free, thereby making the survival of inde-pendent software vendors impossible. Even though the Justice Departmenteventually withdrew their charges against IBM in 1982, the impact that thiscase had on IBM and other players was profound. Suffice it to say that the1970s marked the dawn of the software industry.

    The emergence of the software market led to the advent of new softwarearchitectures and development paradigms. In the ensuing 25-odd years, thesoftware industry became increasingly sophisticated in terms of architectureand development methodologies. The industry had begun deploying two-tierarchitectures where monolithic applications communicated with large data-bases running on a different system. Object-oriented development in older aswell as newer languages such as C++ and Java, respectively, was in full swing.People were trying to fathom the potential of the public Internet. Corporationswere beginning to realize that having a corporate Web site was as important as having phones and fax machines for communication with customers andpartners.

    It was at this juncture that software architects started recognizing the lack offlexibility and interoperability in existing application deployments. The inflexi-bility was attributed to the inherent nature of monolithic applications that inhib-ited the ability to repurpose and reuse existing functionality. Even though thesemonolithic applications were developed using object-oriented languages, objecttechnology by itself was not fully equipped to garner optimum levels of reuse.Dividing functionality into independent and self-contained components thatcan interoperate with each other to assemble an application was deemed the bet-ter solution for building applications.

    The preference for component-based architectural principles gradually gaveway to component frameworks such as Common Object Request Broker Archi-tecture (CORBA), ActiveX/COM, EJB, and so on. In keeping pace with otherdisruptive forces at work in software design (mainly distributed multi-tiercomputing), these frameworks ended up providing much more than merelythe mechanisms for component development. Component frameworksevolved sufficiently to support development and deployment of enterpriseapplications comprising components distributed over various tiers.

    To dive further, let us identify the infrastructure needs of multi-tier enter-prise applications that could be provided by component frameworks.

    Infrastructure Needs of Distributed Applications

    Figure 1.1 shows a typical business application. This application could exist inany industry and could solve any business problem. It could be an equity trad-ing system, a corporate banking application, a call center application, a salesautomation application, and so on.

    Overview 5

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 5

  • Figure 1.1 A typical multi-tier deployment.

    Notice that this enterprise application is a distributed system. We broke upwhat would otherwise be a large, monolithic application and divorced eachlayer of the application from the other, so that each of these layers is indepen-dent and serves a distinct purpose. For instance, the presentation layer carriesthe logic to provide a user interface to the client, the middleware tier consistsof the logic to provide the actual business functionality and other services,whereas the database tier provides data services.

    Now look at this picture and ask yourself which issues would need to betaken care of for such a deployment? Take a moment to reflect on this questionbefore proceeding to the following list of aspects worth considering in such adistributed deployment.

    ■■ Remote Method Invocation. We need logic that connects one tier toanother via a network connection—viz. logic to connect presentationtier to middleware tier and middleware tier to database tier. Thisincludes dispatching method requests, brokering parameters, dispatch-ing SQL statements, and more.

    ■■ Load balancing. Presentation clients must be directed to the middle-ware (as well as database) servers with the lightest load. If a server isoverloaded, a different server should be chosen.

    ClientPresentation Tier

    ClientPresentation Tier

    ClientPresentation Tier

    BusinessLogic

    Middleware Tier

    BusinessLogic

    Middleware Tier

    Database

    6 Chapter 1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 6

  • ■■ Transparent failover. If a server crashes, or if the network crashes, canclients be rerouted to other servers without interruption of service? Ifso, how fast does failover happen? Seconds? Minutes? What is accept-able for your business problem?

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

    ■■ Transactions. What if two clients access the same row of the databasesimultaneously? Or what if the database crashes? Transactions protectyou from these issues.

    ■■ Clustering. What if the server contains state when it crashes? Is thatstate replicated across all servers, so that clients can use a differentserver?

    ■■ Dynamic redeployment. How do you perform software upgradeswhile the site is running? Do you need to take a system down, or canyou keep it running?

    ■■ Clean shutdown. If you need to shut down a server, can you do it in asmooth, clean manner so that you don’t 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 helpyou debug the problem so it does not happen again.

    ■■ Systems management. In the event of a catastrophic failure, who ismonitoring your system? You want monitoring software that pages asystem administrator 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 clientrequests simultaneously. This means the server must be coded to bemultithreaded.

    ■■ 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.

    ■■ Component life cycle. The components that live within the server needto be created or destroyed when client traffic increases or decreases,respectively.

    ■■ Resource pooling. If a client is not currently using a server, thatserver’s precious resources can be returned to a pool to be reused whenother clients connect. This includes sockets (such as database connec-tions) as well as components that live within the server.

    Overview 7

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 7

  • ■■ Security. The servers and databases need to be shielded from saboteurs.Known users must be allowed to execute operations for which theyhave adequate rights of execution.

    ■■ Caching. Let’s assume that there is some database data that all clientsshare and make use of, such as a common product catalog. Why shouldyour servers retrieve that same catalog data from the database over andover again? You could keep that data around in the servers’ memoryand avoid costly network roundtrips and database hits.

    ■■ And much, much more.

    Each of these aspects should be addressed to enable deployment of robustlarge-scale distributed applications. Consequently, each of these aspects can be thought of as a service—a service to do resource pooling, a service to pro-vide message-based communications, a service to provide authentication andother security facilities. These services are termed middleware services due tothe fact that they are commonly required in the middleware layer of a multi-tier application.

    Application Server–Class SoftwareClearly middleware services are a must for an enterprise application to functionsuccessfully. So how should one go about availing such infrastructure services?What greater role can component frameworks play in this regard? IT and tech-nology organizations around the world can do one of the two things—buildthese services or buy them.

    Building Middleware Services from Scratch

    This approach could be considered perilous because building and maintainingmiddleware services is a complicated affair. It requires expertise in system-level programming semantics such as multithreading, pooling, transactionmanagement, clustering, and so on. Most business application developersemployed by IT departments are not skilled enough in system programming.Undertaking such a development would therefore require additional invest-ment in hiring system programmers proficient in this arena.

    Moreover, such infrastructure services are orthogonal to the core business ofmost corporations using IT. Therefore, building such infrastructure services in-house would divert IT departments from the business information servicesthat they are supposed to be delivering to the rest of the organization.Nonetheless, quite a few companies have taken this route, mainly due to theabsence of frameworks to provide such distributed computing services, out ofthe box, at the time.

    8 Chapter 1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 8

  • Buying Middleware Services via Application Server Software

    The increasing popularity of component-based development and distributedcomputing gave rise to component frameworks that provided not only thebasic component development facilities but also commonplace infrastructureservices—a.k.a. quality of services (QoS)—for multi-tier enterprise applica-tions. These QoS are rendered to the components hosted within an environ-ment, namely application server, which implements a distributed componentframework such as EJB.

    Application server–class software came into existence to let you buy thesemiddleware services rather than build them yourself. Application serversenable you to focus on your business application and not worry about themiddleware plumbing you need for a robust server-side deployment. Youwrite the code specific to your business and industry, and deploy that codeinto the runtime environment of an application server. You’ve just solved yourbusiness problem by dividing and conquering.

    Standardization of Component FrameworksIt has been a number of years since the idea of multi-tier 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-upon definition of what a component should be or how it should be providedwith services or how should it interact with the application server. The result?Once you bet on an application server, your code was locked into that ven-dor’s solution. This greatly reduced portability and was an especially toughpill to swallow in the Java world, which has always promoted openness andportability.

    What we need is an agreement, or a set of standard interfaces, between appli-cation servers and components. This agreement will enable any component torun within any application server. It will allow components to be switched inand out of various application servers without having to change code orpotentially even recompile the components themselves. Application servervendors that implement such a standardized component framework securetheir business by providing a higher quality of implementation of the stan-dard, rather than locking in their customers.

    Figure 1.2 depicts an application server that implements a standard compo-nent framework such as EJB.

    Overview 9

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 9

  • Figure 1.2 A standard component framework.

    NOTE Even though software is regarded as one of the most cutting-edgeindustries, it has lagged behind in the trend to standardize componentinterfaces. Other industries, such as consumer device manufacturers, beganfollowing this path long before the software industry. For instance, televisionvendors started supporting NTSC (National TV Standards Committee), astandard for broadcasting, in TV sets almost five decades before we startedseeing similar design principles in software.

    Enterprise JavaBeans Technology

    Let us finally define EJB properly. EJB is a standard for developing and deploy-ing server-side distributed components in Java. It defines an agreement (con-tract) between components and application servers that enables anycomponent to run in any compliant application server.

    The three main value propositions of EJB are:

    ■■ It is a ubiquitous industry standard. EJB has benefited from its wide-spread use—it is easy now to hire staff with a good knowledge of EJB todevelop and maintain your systems. Also, due to the maturity of thetechnology, numerous best practices for implementing EJB are availableto those who use it.

    ■■ Portability is possible. The EJB specification is published and availablefreely to all. Since EJB is a standard, you do not need to gamble on thelong-term viability and proprietary architecture of a single vendor. Andalthough porting applications from one platform to another will neverbe without its costs, it is easier to get it done working with a standardthan without it.

    Application Server

    Components

    Interaction withapplicationserver viastandard interfaces

    10 Chapter 1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 10

  • ■■ Rapid application development. Your application can be built fasterbecause you get middleware infrastructure services such as transac-tions, pooling, security, and so on from the application server. Also,innumerable tools have been made available by vendors as well as theopen source community over the years to do rapid application develop-ment using EJB.

    Note that while EJB does have these virtues, there are also scenarios inwhich EJB is overkill. Hopefully, with the simpler programming model intro-duced in EJB 3.0, its usage in smaller applications will increase. See Chapter 13for best practices and discussions surrounding the issue of when to (and whennot to) use EJB.

    NOTE Physically, EJB is actually two things in one:

    ■■ Specification. With EJB 3.0, the specification has been divided into three documents, which are all freely downloadable fromhttp://www.jcp.org/en/jsr/detail?id=220. The specificationlays out the rules of engagement between components and applicationservers. It constricts how you code enterprise beans to enable “writeonce, 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 any EJB-compliant components.

    Why Java?The EJB framework has supported only the Java language thus far, unlike the.NET framework that supports multiple languages. Though this sounds a bitrestrictive, the good news is that Java is one of the best-suited languages forbuilding distributed 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 a mini-mum. Java supports this separation at a syntactic level through theinterface and 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 not an issue since the language never exposes them tothe programmer. Memory leaks occur much less often. Java also has arich library set, so that Java is not just the syntax of a language but awhole set of prewritten, debugged libraries that enable developers to

    Overview 11

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 11

  • avoid reinventing the wheel in a buggy way. This safety is extremelyimportant for mission-critical applications.

    ■■ Cross-platform. Java runs on any platform. There is a Java VirtualMachine (JVM) for all platforms. Vendors provide support for theirapplication servers across all the platforms most of the time. This meansthat EJB applications could be deployed on all these platforms. This isvaluable for customers who have invested in a variety of hardwareplatforms, such as Intel, AMD X32-X64, SPARC, and mainframes, aswell as operating platforms, including various flavors of UNIX, Win-dows, and so on, in their data centers.

    NOTE If you don’t want to go the EJB route, you have two other choices:

    ■■ Lightweight open source Java frameworks such as Spring. In Chapter 13we discuss when to use EJB versus such nonstandard frameworks.

    ■■ Microsoft .NET–managed components, part of the Microsoft .NETplatform.

    EJB as a Business Tier ComponentThe real difference between presentation tier components, such as standaloneapplications and applets, dynamically generated Web pages, or Web serviceclients, and enterprise beans is the domain in which they operate. Presentationcomponents are well suited to handle client-side operations, such as renderingGUIs, executing client-side validations, constructing appropriate SimpleObject Access Protocol (SOAP) messages to send them back and forth to a Webservice, and so on. They deal directly with the end user or end application.

    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 highly transactional business operations. The server side has different kinds of needs than GUIclients do. Server-side components need to run in a highly available (24x7),fault-tolerant, transactional, multi-user, secure environment. The applicationserver provides such a server-side environment for the enterprise beans, and itprovides the runtime services necessary for the functioning of enterprise beans.

    Specifically, EJB is used to help write logic that solves business problems. Typi-cally, EJB components (enterprise beans) can perform any of the following tasks:

    ■■ Perform business logic. Examples include computing taxes on a shopping cart, ensuring that the manager has authority to approve the purchase order, or sending an order confirmation e-mail using theJavaMail API.

    12 Chapter 1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 12

  • ■■ 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 helpdesk ticket in a customer service application.Enterprise beans can achieve database access using many techniques,one of which is the Java Database Connectivity (JDBC) API.

    ■■ Integrate with other systems. Examples include calling a highly trans-actional CICS legacy system written in C that computes the risk expo-sure for a new insurance customer, using a legacy VSAM (VirtualStorage Access Method) data store, or accessing SAP R/3. Enterprisebeans can be integrated with other applications in multiple ways, oneof which is through the Java EE Connector Architecture, which we willcover in detail in Chapter 15.

    Thus, EJB components sit behind the presentation tier applications or components and do all the hard work. Examples of EJB clients include the following:

    ■■ Application clients. Application clients execute on a user’s desktop,either within an Internet browser environment as an applet or alone.They connect through the network to EJB components that live on aserver. These EJB components may perform any of the tasks listed pre-viously (business logic, database logic, or accessing other systems).

    ■■ 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 user’s personal prefer-ences. Core technologies such as Java Servlets and Java Server Pages(JSP) are used to dynamically generate such Web pages. Both servletsand JSPs live within a Web server and can connect to EJB componentsfor business logic, thereby generating dynamic Web pages based uponthe results 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 partners’applications, which in turn may provide their own user interface. Forexample, consider a scenario where Dell Computer Corporation needsto procure Intel chips to assemble and distribute desktop computers.Here, Intel could expose an Order Parts Web service that enables theDell Procurement Web service client to order chips. In this case, the Intelsystem does not provide a graphical user interface per se, but ratherprovides a programmatic Web service interface that can be used by asystem instead of a human user. This scenario is shown in Figure 1.3.

    Overview 13

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 13

  • Figure 1.3 EJBs as Web service clients.

    Distributed Computing: The Foundation of EJBEJB enables development and deployment of distributed components. A dis-tributed component, also commonly referred to as distributed object or remoteobject, is callable from a remote system. That is, not only can it be called froman in-process client but also from an out-of-process client that might be locatedon a different system on the network.

    A remote invocation of a method on a distributed object follows a commonprocess that is similar across almost all distributed computing technologies.The main steps of this remote method invocation process are:

    1. The client calls a stub, which is a client-side proxy object. This stub isresponsible for masking network communications from the client. Thestub knows how to call over the network using sockets and also how tomassage parameters from their Java representations to the correspond-ing network representations.

    2. The stub calls over the network to a skeleton, which is a server-sideproxy object. The skeleton masks network communication from the dis-tributed object. The skeleton understands how to receive calls on asocket as well as how to massage parameters from their network repre-sentations to their Java representations.

    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.

    Dell‘s procurement applicationcommunicates with Intel‘s 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

    14 Chapter 1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 14

  • 3. The skeleton delegates the call to the appropriate implementationobject. This object serves the call and does its work, and returns controlto the skeleton, which returns it to the stub, which finally returns con-trol to the client.

    Figure 1.4 depicts the method invocation on a remote object.A key point here is that both the stub and the server-side implementation

    object implement the same interface (called the remote interface). This meansthe stub clones the distributed object’s method signatures. A client who calls amethod on the stub thinks he is calling the distributed object directly; in reality,the client is calling an empty stub that knows how to go over the network. Thisis called distribution transparency. In fact, the distributed object is an abstractionthat is created by the cooperation between the stub, skeleton, and implemen-tation objects. No single entity in this scenario is the distributed object.

    You can develop and deploy distributed objects using many other technolo-gies, including CORBA (OMG), Distributed Component Object Model orDCOM (; Microsoft), and Java RMI-IIOP (Sun).

    Figure 1.4 Remote method invocation.

    Stub

    ClientDistributed

    Object

    Skeleton

    Remote Interface

    Network

    Remote Interface

    Overview 15

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 15

  • EJB Middleware ServicesAlthough we expound upon the EJB middleware services such as transactionmanagement, persistence, messaging, security, clustering, and so on through-out this book, we think it is about time to introduce you to the approach takenby EJB in provisioning them.

    There are two ways in which a framework such as EJB can provide middle-ware services—explicitly and implicitly. To use explicit middleware servicesyou must explicitly call the middleware services’ APIs. Implicit middlewareservices can be used without having to write against the middleware APIs viz.implicitly.

    Explicit Middleware Approach

    Traditionally, transactional systems such as CORBA, Tuxedo, and COM/DCOM have made available middleware APIs; your code uses them to requestthe framework to provide the requisite services. This explicit approach can beillustrated using pseudo-code. The following example shows a transfermethod on the Bank distributed component that performs transfer of fundsbetween two accounts.

    transfer(Account account1, Account account2, long amount) {

    // 1: Call middleware API to perform a security check

    // 2: Call middleware API to start a transaction

    // 3: Call middleware API to load rows from the database

    // 4: Subtract the balance from one account, add to the other

    16 Chapter 1

    DISTRIBUTION TRANSPARENCY

    Distribution transparency is the Holy Grail in distributed systems technologyand is very hard to achieve. Perfect distribution transparency would mean thata client never sees any differences between local and remote interactions. Inthe presence of the more complex failure modes of remote operations andnetwork latency, this is not possible. Most of the time, the term distributiontransparency is used rather loosely to mean that the syntax of the client codemaking invocations is the same for both remote and local invocations. Even thisis not always the case when you consider the different exceptions found inremote interfaces that in turn require different exception handling, and thesubtle differences between the pass-by-reference and pass-by-value semanticsthat local and remote invocations sometimes exhibit.

    For these reasons, most middleware systems settle for a less ambitious formof transparency, viz. location transparency. We will explore locationtransparency further in Chapter 3.

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 16

  • // 5: Call middleware API to store rows in the database

    // 6: Call middleware API to end the transaction

    }

    Clearly, although we are serviced with the requisite middleware by theframework, our business logic is intertwined with the logic to call these mid-dleware APIs. This approach has some major downsides:

    ■■ Lowers developer productivity. Even though the framework providesmiddleware services, the developer is still supposed to write the codeto use them. Writing and testing this code obviously takes time, therebyleading to lower developer productivity.

    ■■ Difficult to write. The code is bloated. We simply want to perform atransfer, but it requires a large amount of code due to the mingling ofmiddleware service interaction code with the business logic code.

    ■■ Difficult to maintain. If you want to change the way you consumemiddleware services, you need to rewrite your code.

    Implicit Middleware Approach

    Using this approach, the framework would not only provide middleware ser-vices but also an easier way to use them. An implicit middleware frameworkwill let you declare the middleware services that you need for your applicationin a separate descriptor file or even through simple annotations within thecode. Hence, your code contains no cumbersome API calls to use the middle-ware services. The code is clean and focused on business logic. To use the ear-lier illustration, below is how the pseudo-code for the transfer method onthe Bank component will look:

    transfer(Account account1, Account account2, long amount) {

    // 1: Subtract the balance from one account, add to the other

    }

    At the time the preceding code is compiled, the framework will peruse thedescriptor and/or annotations within the code (depending on the approachused) and will provide the requested middleware services. A framework mayor may not prescribe a methodology as to how to implicitly render these ser-vices. For instance, the EJB framework does not define a specific way of doingthis, and different EJB vendors use different mechanisms to provide these ser-vices implicitly. For instance, some vendors choose to consolidate all calls tomiddleware services in the skeleton of the given EJB component, whereassome vendors put these calls in a different object, which is then called by the

    Overview 17

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 17

  • EJB skeleton. Thus, the mechanism used to provide the middleware servicesimplicitly is an implementation detail of the EJB server and is left to the prod-uct vendors to decide individually.

    Most contemporary computing frameworks, standard or not, follow thisapproach. The examples include EJB, Microsoft .NET, Hibernate, and so on.The upsides to this approach are:

    ■■ Increases developer productivity. Developers do not have to write thecode for invoking middleware services. All they have to do is declarethe services they require in a descriptor file or as annotations in thecode itself. This increases their productivity.

    ■■ Easy to write. Since no code needs to be written to call middleware ser-vices, your component code is focused on business logic.

    ■■ Easy to maintain. The separation of business logic and middlewarelogic is clean and maintainable. Changing middleware service con-sumption does not require changing application code.

    NOTE Annotations or metadata facilities have been introduced in the Javaplatform from J2SE 5.0. Annotations are a powerful concept and play animportant role in EJB 3.0 and Java EE 5.0 at large. We will introduce annotationsin Chapter 3, while discussing the EJB 3.0 programming model.

    Implicit vs. Explicit Middleware Services in EJB

    EJB uses the implicit middleware approach—however, it also provides a sim-ple API to explicitly interact with middleware services. Although the APIapproach is a complex one, it puts greater control in the hands of a developer.

    For instance, imagine a scenario where a developer does not want to markan entire method on an EJB as transactional. In this case, he can use the JavaTransaction API to interact with the transaction management services of EJB.Using this middleware service API, the developer can mark the beginning andend of the transaction at specific points within the method code, therebywielding better control.

    Although developers usually use middleware services implicitly, it is help-ful to know that the EJB framework provides a choice. Also, it is good to knowthat you can use some middleware services implicitly and some explicitly,which leads to a hybrid approach to using middleware.

    Roles in the EJB Application Life CycleAn EJB application’s life cycle involve three main phases—development, deploy-ment, and administration. Depending on the size and scale of the application, theactivities related to each of these phases can range from simple to complex. In the

    18 Chapter 1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 18

  • latter case, the time required to take an EJB application live can be significantlyreduced if responsibilities across the life cycle are divided among various parties.Each of these parties will play a role, so to speak, in the EJB application’s lifecycle. These parties can be made up of a single person or groups of 10s or even100s of developers. As long as the individuals playing these roles are well trainedin the given area of application life cycle, this division of labor can yield the max-imum possible efficiency. We have seen such role-based development practiceused widely, especially in medium and large-scale projects.

    The following sections discuss the responsibilities handled by these rolesand clarify the issues that could surface.

    The Bean Provider

    The bean provider supplies business components, or enterprise beans. It istasked with writing the code of enterprise beans and also unit testing theirbeans. The bean provider can be an internal department providing compo-nents to other departments, or it can be a group of developers in a teamresponsible for writing EJB components, which can subsequently be used byother developers in the same team.

    The Application Assembler

    The application assembler is the overall application architect. This party isresponsible for understanding how various components fit together andwrites the glue code, if required, to make the components work together in ameaningful manner. An application assembler may even author a few compo-nents along the way for this purpose. The application assembler is mostly theconsumer of the beans supplied by the bean provider.

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

    ■■ Using an understanding of the business application to decide whichcombination of existing components and new enterprise beans areneeded to provide an effective solution; in essence, plan the applicationassembly.

    ■■ Supply a user interface (perhaps a Swing-based application or applet,or servlet, or JSP) or a Web service.

    ■■ Write the client code to access components supplied by bean providers.

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

    The role of application assembler can be played either by a systems integra-tor, a consulting firm, or an in-house developer.

    Overview 19

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 19

  • The EJB Deployer

    After the application assembler builds the application, the application must bedeployed (and go into production) in a running operational environment. Manytimes, the bean provider or an application assembler is unaware of the issuesinvolved in a production environment. Invariably, the environment in whichEJB applications are developed is not the same as the one in which they aredeployed. Hence, definite skills are required to take care of such differences insystem and software infrastructure products used in development versus production to ensure a smooth transition to the live environment. This need isfulfilled by the role of an EJB deployer. The EJB deployer should be wellacquainted with the portfolio of systems, storage, software, and so on in use inproduction, at least for that specific application. For instance, an EJB deployershould be able to work with the various application server(s) used in the pro-duction environment.

    Some of the responsibilities of an EJB deployer include:

    ■■ Securing the deployment with a hardware or software firewall andother such security measures. Usually, enterprise applications arehosted within managed data centers. In which case, the EJB deployerwill interact actively with the data center staff and co-manage thedeployment of EJB applications.

    ■■ Choosing hardware that provides the required level of robustness andquality of service. Again, if your enterprise application lives within thewalls of a data center, the EJB deployer will work with data center staffto identify the systems that meet the needs in terms of resources such asstorage, network bandwidth, memory, and so on.

    ■■ Providing redundant hardware and other resources for reliability andfault tolerance. This involves configuring the EJB deployment for faulttolerance at the system level and/or application level.

    ■■ Tuning application performance. EJB deployment is not consideredcomplete without ensuring that its performance meets the definedrequirements. If the application does not meet the desired performance,then it will need tuning. Deployers can conduct this exercise in coordi-nation with other performance experts in their organization.

    The System Administrator

    Once 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 use

    20 Chapter 1

    05_785415 ch01.qxp 6/5/06 6:54 PM Page 20

  • of various performance monitoring and application management tools in theprocess.

    For example, in the event of failures or disruptions, a sophisticated EJBapplication-monitoring tool can send an alarm to the designated administra-tor, calling for their immediate attention. Some EJB server vendors have sup-plemented their server offerings by integrating with widely used managementtool product lines such as OpenView, Tivoli, Unicenter, and so on. Others suchas JBoss have written their own support for EJB application monitoring andmanagement using technologies such as JMX.

    Figure 1.5 highlights the coordination between the various parties through-out the EJB application’s life cycle.

    Note that some of these roles could be combined as well. For example, at asmall startup company, the bean provider, application assembler, anddeployer could all be the same person who is trying to build a business solu-tion using EJBs.

    Overview 21

    DATA CENTERS

    A data center is a consolidated facility that houses computer systems, storage,and communication related equipment needed to run information technologyoperations. In a typical data center, a dedicated staff manages not just hardwaresystems but also the hosted software applications. Depending on how criticalthe 24x7 functioning of a hosted application is, a data center would providevarious levels of service agreements to their clients.

    In years gone by, almost all companies operated an in-house data center.Many business models bloomed during the Internet revolution of the late1990s, and outsourcing data centers was one. Most of the dotcoms at the timeoutsourced the hosting and operations of their Web sites to professional datacenter businesses. Even today, small as well a