CSE298 CSE300 Java Beans and Enterprise Java Beans Paul C. Barr The Mitre Corporation Eatontown NJ Kimble Cheron, Prof. Steven A. Demurjian, and Mitch Saba Computer Science & Engr. Dept. poobarr@mitre.org steve@engr.uconn.edu http://www.engr.uconn.edu/~steve (860) 486 - 4818 JR&B-1.1 CSE298 CSE300 Changing Perspectives Computers are Guilty of Creating More Disorder then Simplicity Current Software Systems are Relics Built Largely By and For Technical Computer Users Never Intended to Operate in Today’s Environment Designer’s Need to Break Out of Old Mold Consider Total Design Space Design Should Help Manage Complexity, Not Add to It What is Available to Assist in Changing Times? JR&B-1.2 CSE298 CSE300 Components Reusable Software Building Blocks Pre-Constructed from Encapsulated Application Code Easily Combined with Other Components Seamlessly Merged with Custom Code Rapid Prototyping of Complete Applicaiton What is a Component? GUI Widget (Button, Window, etc.) Combination of Components (Window with Elevator Bars and Pull-Down Menus) Application Service (Account Management Function) JR&B-1.3 CSE298 CSE300 Overview A First Look at Java Beans What are They? How are They Utilized? Enterprise Java Beans Not Just for Clients Anymore! Capabilities and Usage Relationship to “New” and “Old” Technologies Component-Based Client/Server Model Multi-Tiered Architecture and EJB Tiered Development for Extensibility Comparisons of Approaches Java Blend for Database Interoperability JR&B-1.4 CSE298 CSE300 Java Beans Extends "Write Once, Run Anywhere (WORA)TM" to Include "Reuse Everywhere” What is a Bean? Independent Reusable Software Component Visually Manipulated in Builder Tools Can Be Visible Object: AWT Components or Invisible Objects: Queues and Stacks or Composed Objects: Calculator Ops + Keys + Display JR&B-1.5 CSE298 CSE300 Java Beans Bean vs. Component Source Code Inaccessible Customizable to Suit Application Needs via External Properties Powerful Means of Reuse Examples GUI Button with Property to Allow Button Name to be Set Account Management Component that Allows Account Database Location to be Set Properties Can be Very Complex and Offer Significant Power to Application Builders JR&B-1.6 CSE298 CSE300 Java Beans Fundamentals Supported within IDEs Visual Age, JBuilder, PowerJ, Visual Café Construct JavaBeans Component as Specialized Java Classes with Enhanced Capabilities Three-Part Architecture Events Notifies Others When Something Has Occurred Delegation-Event Model of AWT Properties Define the Characteristics of the Bean Methods Utilized to Define a Property JR&B-1.7 CSE298 CSE300 Architecture: Events Events Notifies Others When Something Has Occurred Delegation-Event Model of AWT Event Elements Eventobjects Components Sends to Listener Eventlisteners In Order to Register an Eventlistener With a Component, the Component Must Understand the Event Set Event Sources We’ll Discuss Shortly and Revisit in Detail with Java RMI JR&B-1.8 CSE298 CSE300 Architecture: Properties Example: AWT Textfield User Will See Properties for the Caret Position, Current Text, and the Echo Character, etc. Methods Used to Define a Property public void setPropertyName(PropertyType value); public PropertyType getPropertyName(); The Name of the Property is Propertyname The Datatype is Propertytype Only One Method Present the Property is ReadOnly (Set Missing) Or the Property is Write-only (Get Missing) JR&B-1.9 CSE298 CSE300 Architecture: Methods Methods Public Available for Anyone to Call Beaninfo and Getmethoddescriptors Method Restricts Which Methods Are Visible to the Beanbuilder/Integration Tool The Getmethoddescriptors Method Reports All the Methods of a Bean Supports Introspection Beaninfoclass Customize a Bean's Appearance to an Integration Tool JR&B-1.10 CSE298 CSE300 Abilitiy Persistence Ability of an Object to Store its State Object Serialization Saves All Non-static and Non-transient Instance Variables of an Object Objectinput and Objectoutput Interfaces The Basis for Serialization Within Java. Objectinputstream and Objectoutputstream Classes Implement the Objectinput and Objectoutput Interfaces JR&B-1.11 CSE298 CSE300 Five Defining Features Introspection Allow a Builder Tool to Analyze How a Bean Works Customization User is Allowed to Alter the Appearance and Behavior of a Bean Events Firing of Events Inform Builder Tools About Both the Events They Can Fire and Handle JR&B-1.12 CSE298 CSE300 Five Defining Features Properties Beans Can Be Manipulated Programmatically Support the Customization as Mentioned Persistence Customized Beans Can Have Their State Saved and Restored Work in a Constructed Application Can Be Restored by an Application Builder's Save and Load Menu Commands Beans Are Used Primarily With Builder Tools Programmatic Interfaces Allow Beans to Be Manually Manipulated by Text Tools JR&B-1.13 CSE298 CSE300 Differences Between Beans and Classes Introspection Process of Determining the Supported Properties, Methods, and Events of a Bean Introspector Class Provides Access to the Beaninfo for the Bean Component Via Its getBeanInfo Method Code TextField tf = new TextField (); BeanInfo bi = Introspector.getBeanInfo (tf.getClass()); Alternative to Introspector Class Provides Access Directly Through the Use of the Reflection API JR&B-1.14 CSE298 CSE300 Introspection Tools Differentiates Beans From Typical Java Classes Recognize Predefined Patterns in Class Definitions and Method Signatures Able to "Look Inside" a Bean to Determine Its Properties and Behavior Require That Method Signatures Within Beans Must Follow a Certain Pattern Recognize How Beans Can Be Manipulated at Design and Run Time Pattern Signatures are Designed to Be Recognized by Human Readers and Builder Tools JR&B-1.15 CSE298 CSE300 Bean vs. Class A Bean's State Can Be Manipulated at Design Time in Contrast to Classes at Run Time Beans Attributes and Behaviors Published by Special Method Signature Patterns Recognized by Beans-Aware Application Construction Tools What to Use for Software Modules? Beans are Better for Software Components Visually Manipulated Within Builder Tools Classes are Better for Functionality Through a Programmatic (Textual) Interface An SQL API Would Be Better Packaged Through a Class Library JR&B-1.16 CSE298 CSE300 Event Model Three Elements Eventobject Eventlistener Eventsource (the Bean) Eventobject Basis of All Beans Events Java.Util.Eventobject Class Require Programmer to Subclass an Eventobject to Have a Specific Event Type JR&B-1.17 CSE298 CSE300 Java 1.1 Delegation Event Model JR&B-1.18 CSE298 CSE300 Example: Event for Employee’s Hire Date public class HireEvent extends EventObject { private long hireDate; public HireEvent (Object source) { super (source); hireDate = System.currentTimeMillis(); } public HireEvent (Object source, long hired) { super (source); hireDate = hired; } public long getHireDate () { return hireDate; } } JR&B-1.19 CSE298 CSE300 EventListener Definition Entity That Desires Notification When an Event Happens Receives the Specific Eventobject Subclass As a Parameter JR&B-1.20 CSE298 CSE300 EventListener Eventlistener Interface Empty Interface Acts as a Tagging Interface That All Event Listeners Must Extend Eventtypelistener Name of Listener Interface The Name for the New Hireevent Listener Would Be Hirelistener Method Names Should Describe the Event Happening Code public interface HireListener extends java.util.EventListener { public abstract void hired (HireEvent e); } JR&B-1.21 CSE298 CSE300 EventSource Eventsource Defines When and Where an Event Will Happen Hireevent and Hirelistener Are Required for an Event Source to Function Sends Notification to Registered Classes When the Event Happens JR&B-1.22 CSE298 CSE300 EventSource: Methods Registration Process Method Patterns public synchronized void addListenerType(ListenerType l); public synchronized void removeListenerType(ListenerType l); Maintaining Eventsource Code private Vector hireListeners = new Vector(); public synchronized void addHireListener(HireListener l) { hireListeners.addElement (l); } public synchronized void removeHireListener (HireListener l) { hireListeners.removeElement (l); } JR&B-1.23 CSE298 CSE300 EventSource: Hiring Example protected void notifyHired () { Vector l; // Create Event HireEvent h = new HireEvent (this); // Copy listener vector so it won't change while firing synchronized (this) { l = (Vector)hireListeners.clone(); } for (int i=0;i<l.size();i++) { HireListener hl = (HireListener)l.elementAt (i); hl.hired(h); } } JR&B-1.24 CSE298 CSE300 What is Enterprise Java Beans ? Expansion of Java Beans (Client-side) to Support Server Side Reusable Components Server Components Run on Application Server EJB Integral Part of Java Technology Component Architecture for Distributed Systems Multi-Tier Distributed Architecture Movement of Application Logic from Client to Server Side Creation of “Thin”, Easier to Maintain Clients Framework for Creating Middle Ware Integration of “New” and “Old” Technologies RMI, IIOP, CORBA, RPC, Active X, etc. JR&B-1.25 Designer and Developer Roles in Enterprise Java Beans (EJB) CSE298 CSE300 Towards “Highly Scalable, Highly Available, Highly Reliable, Highly Secure, Transaction Distributed Applications” Enterprise Bean Provider Creates and Sells EJBs Application Assembler Uses EJBs to Build an Application EJB Server Provider Creates and Sells EJB Server EJB Container Provider Creates and Sells EJB Containers Server Provider Will Likely Provide Containers JR&B-1.26 CSE298 CSE300 EJB Roles & Deployment JR&B-1.27 CSE298 CSE300 Utilizing EJB Technology JR&B-1.28 CSE298 CSE300 The EJB Architecture EJB Servers: Analogous to CORBA ORB Server Software Provides Naming and Transaction Services Makes Containers Visible EJB Containers: Interface Between EJB Bean and Outside World Client Never Accesses Bean Directly Access via Container-Generated Methods These Methods Then Call the Bean’s Methods EJB Clients Locate EJB Containers Via JNDI Make Use of EJB Beans Enterprise Java Beans - Discussed Shortly JR&B-1.29 CSE298 CSE300 Recall CORBA JR&B-1.30 CSE298 CSE300 EJB Container JR&B-1.31 CSE298 CSE300 Enterprise Java APIs JR&B-1.32 Enterprise Java Beans Session Beans CSE298 CSE300 Associated With a Particular Client Performs Operations on Behalf of Client Accessing a Database Performing Calculations Created and Destroyed by a Client Can be Transactional - But, Do Not Survive System Shutdown Can be Stateless or Maintain Conventional State Across Methods and Transactions Must Manage Own Persistent Data JR&B-1.33 Enterprise Java Beans Entity Beans CSE298 CSE300 Object Representation of Persistent Data Maintained in Permanent Store (Database Identifiable by Primary Key Shared by Multiple Clients Persist Across Multiple Invocations Survive System Shutdown Created by Inserting Data into Database Creating an Object Instance JR&B-1.34 Model for Persistence Passivation/Activation CSE298 CSE300 Programmatic Model for Managing Persistent Objects EJB Server has the Right to Manage its Working Set Passivation Saves State of a Bean to Persistent Storage Then Swaps Bean Out Activation Restores State of a Bean From Persistent Storage,Then Swaps Bean in Applies to Both Session and Entity Beans JR&B-1.35 CSE298 CSE300 Stateless vs. Stateful Session Beans Stateless No Internal State Do Not Need to Be "Pass-ivated" Can Be Pooled to Service Multiple Clients Stateful Possess Internal State Need to Handle Passivation/Activation One Per Client JR&B-1.36 CSE298 CSE300 Persistent Session Beans Session Beans Can Be Saved and Restored Across Client Sessions To Save Call the Session Bean’s getHandle() Method Returns a Handle Object To Restore Call the Handle Object’s getEJBObject() Method JR&B-1.37 CSE298 CSE300 Entity Bean Persistence Container-Managed Container is Responsible for Saving State In Deployment Descriptor, Specify ContainerManaged Fields Persistence Independent of Data Source Bean-Managed Bean is Responsible for Saving its Own State Container Doesn’t Need to Generate DB Calls Less Adaptable; Persistence is Hard-Coded JR&B-1.38 CSE298 CSE300 Writing an EJB Client Locate the Bean Container Allocate a Bean, If Needed Use the Bean Dispose of the Bean //An idealized EJB client import paul.ejb.restaurant.*; public class EJBClient{ public static void main(String[] argv){ //get JNDI naming context javax.naming.Context initialContext = new javax.naming.InitialContext(); //use context to look up EJB home interface RestaurantHome rh = initialContext.lookup(“RestaurantHome”); //use home interface to create a session object Restaurant r = rh.Create(“Burger Heaven”); //invoke business methods r.order(“cheeseburger”); //remove session object r.remove(); } } JR&B-1.39 CSE298 CSE300 Writing a Session Bean Create Remote Interface Create Home Interface must extend javax.ejb.EJBHome interface create() methods, remove() methods Implement Create Methods must extend javax.ejb.EJBObject interface must give prototypes for business methods class needn’t say “implements”; this is handled by the container called by container at creation time Implement the SessionBean Interface ejbActivate() - called when bean is activated ejbPassivate() - called when bean is passivated ejbRemove() - called when bean is destroyed setSessionContext(SessionContext ctx) - called by container to give bean a context JR&B-1.40 CSE298 CSE300 Session Bean Example package paul.ejb.restaurant.server; public class OrderBean implements SessionBean{ private transient SessionContext ctx; private String order; //can have many create methods public void ejbCreate () throws Exception { //initialization of class variables here } //business method public boolean order(String order) { this.order = order; System.out.println("order received for " + order); return true; } //these methods are required by the SessionBean interface public void ejbActivate() throws Exception { } public void ejbDestroy() throws Exception { } public void ejbPassivate() throws Exception { } public void setSessionContext(SessionContext ctx) throws Exception { this.ctx = ctx; } } JR&B-1.41 CSE298 CSE300 Writing an Entity Bean Implement the EntityBean Interface ejbActivate() // called on activation ejbPassivate() // called on passivation ejbLoad() // tells bean to load state from database ejbStore() // tells bean to store state in database ejbRemove() // called when client calls remove() setEntityContext() // called by container when instance has been created unsetEntityContext() // called by container before removing the instance must also implement ejbFind() // allows client to look up EJB objects Optionally Implement create() Methods Create Remote Interface must extend javax.ejb.EJBObject interface Create Home Interface JR&B-1.42 CSE298 CSE300 Entity Bean Example package paul.ejb.entity.server; public class ExampleBean implements EntityBean { private transient EntityContext ctx; //notice: no finder method -- generated at deployment time by container provider //can have multiple create methods public void ejbCreate () throws Exception { } //business method public boolean doSomething () { } //required methods for EntityBean interface public void ejbActivate() throws Exception { } public void ejbDestroy() throws Exception { } public void ejbPassivate() throws Exception { } public void ejbLoad() throws Exception { } public void ejbStore() throws Exception { } public void setEntityContext (EntityContext ctx) throws Exception { this.ctx = ctx; } JR&B-1.43 CSE298 CSE300 Deploying EJBs EJBs Deployed As .SER Files: Serialized Instance Manifest File Used to List EJBs Must Also Provide a “Deployment Descriptor” Sample Entry Name: paul.RestaurantDeployment.ser Enterprise-Bean: True “Name” Line Describes a Serialized Deployment Descriptor “Enterprise-Bean” Line Indicates Whether the Entry Should Be Treated as an EJB (Not All Entries Need to Be EJBs) JR&B-1.44 CSE298 CSE300 Who’s Announced EJB Support? WebLogic IBM Oracle GemStone BEA Borland Netscape Lotus Forte Progress Novell Novera Borland Informix IONA More... JR&B-1.45 Typical Development and Deployment Scenario CSE298 CSE300 EJB Server Provider Creates and Sells an EJB Server Provides EJB Containers That Will Run on These Servers EJB Providers Individuals Responsible for Developing the EJBs Provide “Tools” and “Components” for DownStream Usage Application Assemblers Individuals that Utilize Pre-Built EJBs to Construct Their Domain-Specific Applications Utilize “State-of-Art-Tools” for EJB and JB JR&B-1.46 CSE298 CSE300 EJB Component-Based Architecture EJB Server EJB Client Invoke EJB Container Methods Enterprise Java Bean Invoke EJB Methods EJB Container JR&B-1.47 CSE298 CSE300 Client-Server Component Model JR&B-1.48 CSE298 CSE300 Client-Server Component Relationship JR&B-1.49 CSE298 CSE300 Client-Server Component Relationship (Concluded) JR&B-1.50 CSE298 CSE300 EJB Server Example JR&B-1.51 CSE298 CSE300 EJB Server Example (continued) JR&B-1.52 CSE298 CSE300 EJB Server Example (Concluded) JR&B-1.53 CSE298 CSE300 Three-Tier Architecture Concept JR&B-1.54 CSE298 CSE300 Two-Tier, Three-Tier, Four-Tier Example Architectures From: http://java.sun.com/javaone/javaone98/sessions/T400/index.html JR&B-1.55 CSE298 CSE300 Wombat Securities Web Access to Brokerage Accounts Only HTML Browser Required on Front End "Brokerbean" EJB Provides Business Logic Login, Query, Trade Servlets Call Brokerbean Use JNDI to Find EJBs, RMI to Invoke Them Order and History Records from Java Blend Product Records Mapped to Oracle Tables, JDBC Calls JR&B-1.56 CSE298 CSE300 Four-Tier Architecture Example JR&B-1.57 CSE298 CSE300 Initialization Code class LoginServlet extends HttpServlet { private Broker createBroker(String account, String password) { /* Use JNDI to find Broker EJB home, then return new EJB */ Context initialContext = new InitialContext(); BrokerHome brokerHome = (BrokerHome) initialContext.lookup("wombat/Broker"); return brokerHome.create(account, password); } public doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* Get account and password from HTML and create EJB*/ String account = req.getParameter("Account"); String password = req.getParameter("Password"); Broker brk = createBroker(account, password); ...} ...} JR&B-1.58 CSE298 CSE300 User Interface Code class TradeServlet extends HttpServlet { ... public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { /* Get parameters from HTML and session object */ HttpSession session = req.getSession(true); String ticker = req.getParameter("Symbol"); ... Broker brk = (Broker) session.getValue("LoginServlet.BrokerRef"); /* Place order and print confirmation as HTML */ String orderNum = brk.submitOrder(txType, ticker, shares); printOrderSubmitted(out, account, orderNum); ... } } JR&B-1.59 CSE298 CSE300 Business Logic Code class BrokerBean implements SessionBean { public void ejbCreate (String account, String password) ... public SecurityRecord getAcctPositions ( ) ... public OrderRecord getOrderStatus ( ) ... public String getQuote(String ticker) ... public String submitOrder(String txType, String ticker...) ... public HistoryRecord getAcctHistory ( ) ... private boolean login (...) ... ... etc ... } JR&B-1.60 CSE298 CSE300 Database Access Code SQL: CREATE TABLE ORDER( ORDERNUM INTEGER NOT NULL, CUST INTEGER NOT NULL, TICKER VARCHAR(5), ... PRIMARY KEY (ORDERNUM), FOREIGN KEY (CUST) REFERENCES CUSTOMER); Java: class Order{ int orderNum; Customer cust; String ticker; ...} Java Blend Automatically Maps Classes to/from Relational Tables at Compile-Time and Run-Time JR&B-1.61 CSE298 CSE300 Nocturnal Aviation, Inc. Passenger Check-in for Regional Airline Local Database for Seating on Today's Flights Clients Invoke EJBs at Local Site Through RMI EJBs Update Database and Queue Updates JMS Queues Updates to Legacy System DBC API Used to Access Local Database JTS Synchs Remote Queue With Local Updates JR&B-1.62 CSE298 CSE300 Three-Tier Example JR&B-1.63 CSE298 CSE300 Santa Cruz Widgets Small Manufacturer Previously on C++ New Order Entry, Inventory, and Invoicing Applications in Java Programming Language Existing Customer and Order Database Most of Business Logic in Stored Procedures Tool-generated GUI Forms for Java Objects Located Company on Web Using Widgets and Tcl, but Not Widgets and Java JR&B-1.64 CSE298 CSE300 Santa Cruz Widgets (2-tier) JR&B-1.65 CSE298 CSE300 Architecture Comparisons Two-tier Through JDBC API: Simplest Multi-tier: Separate Business Logic, Protect Database Integrity, More Scaleable JMS Queues Vs Synchronous (RMI or IDL): Availability, Response Time, Decoupling JMS Publish & Subscribe: Off-line Notification RMI IIOP Vs JRMP Vs Java IDL: Standard Cross-language Calls or Full Java Functionality JTS: Distributed Integrity, Lockstep Actions JR&B-1.66 CSE298 CSE300 Further API Comparisons Servlets: Simplifies HTML, Connections, Web Front-Ending Legacy Systems EJBs: Simplifies Components, Scalability, Transactions, Multi-threading, Security, State JDBC Vs ODMG Vs SQLJ API: Programming Simplicity, Portability, SQL Knowledge JNDI: Standardized Name Service Access Enterprise Java APIs vs. Proprietary: Multi-Platform, Multiple Providers JR&B-1.67 CSE298 CSE300 Summary & Key Messages Enterprise Java APIs: EJB, JNDI, Java IDL, RMI, JDBC, ODMG, SQLJ, JMS, JTS, JMAPI, Servlets Wide Variety of Architectural Alternatives: Synchronous/Asynchronous, Multi-Tier, Transactional, HTTP/JRMP/IIOP Benefits: WORA Portability Multiple Vendors Legacy Connectivity Java Programming Language Productivity JR&B-1.68 CSE298 CSE300 EJB Roadmap API Specification Complete Products EJB JNDI JIDL RMI JDBC ODMG SQLJ JMS JTS JMAPI Sevlets JavaSoft JavaSoft OMG JavaSoft JavaSoft Consortium Consortium JavaSoft OMG JavaSoft JavaSoft 1.0Q1 1.0 done 1.0 Q2 1.0 done 2.0 Q2 2.0 done 1.0 Q2 1.0 Q2 1.0 done 1.0 Q2 1.1 done See Partners Download SP JDK 1.2 JDK 1.1 JDK 1.2 Partner JavaBlend See Partners See Partners Partners See Partners Java Web Server JR&B-1.69 CSE298 CSE300 What Is the Java Blend Product? Product That Integrates Java Programming Language Objects With Enterprise Data Provides a Single Object Model Based on Java Programming Language Classes Automatic Persistent Storage for Java Application Objects Easy, Automatic Access to Existing Relational Databases From Java Applications Result of Joint Development by the Javasoft Division, Baan and Tech@spree JR&B-1.70 CSE298 CSE300 JavaBlend Applications JavaBlend Software Provides Mapping Capability Between Database Tables and Java Application Classes Programmer Deals Only With Java Programming Language Objects, and Does Not Need to Know SQL or Database Representation JR&B-1.71 CSE298 CSE300 Java Blend Components Flexible Development Tool for Automatic Bi-Directional Mapping Objects to Relational Relational to Objects Powerful Runtime Environment Transaction Management System Query Processor Cache Management System JR&B-1.72 CSE298 CSE300 Java Blend Runtime Architecture JR&B-1.73 Java Blend Software and Enterprise JavaBeans Technology CSE298 CSE300 EJB Technology Provides Scaleable Component Architecture for Business Applications Java Blend Product Provides Transparent Persistence for Enterprise Javabeans Technology Beans Implementing Business Logic Use Java Blend for Database Access Java Blend Product Works With the Enterprise Javabeans API Transaction Mechanisms JR&B-1.74