Presentation is loading. Please wait.

Presentation is loading. Please wait.

Enterprise Java Beans Alex Chaffee, slides originally created by Dave Orchard

Similar presentations


Presentation on theme: "Enterprise Java Beans Alex Chaffee, slides originally created by Dave Orchard"— Presentation transcript:

1 Enterprise Java Beans Alex Chaffee, http://www.jguru.com slides originally created by Dave Orchard http://www.pacificspirit.com/daveshome.html

2 N-tier Application Architecture Server maps HTTP request to Business Object request Client Presentation Logic Business Logic - EJB Persistence Used by most application servers Natural fit for EJB Physical vs Logical tiers –Could have 4 logical tiers in 3 physical tiers with business objects inside web server Note: Business Object = Business Logic + Data Access HTTP DB access Web Browser Business Object Data Persistence Web Server (Servlets) Message

3 EJB Overview EJB is an architecture for Java servers Specification for Persistent Server Objects Implemented by multiple products from multiple vendors Write-Once, Run Anywhere within Middleware Middleware provides all services –Instance management, transactions, concurrency, persistence –Beans stay simple! Compatible with CORBA, RMI

4 EJB Spec Spec developed by Sun and dozens of competing vendors –IBM, Oracle, BEA, WebLogic,... –Interoperable -- a miracle! Why did they cooperate? –Common Enemy phenomenon

5 EJB Advantages With EJB, you can write a business object and easily make it –Distributed –Transactional –Secure –Multithreaded –Persistent

6 EJB Advantages Can also provide wrappers for legacy apps –Mainframes –Native code –Proprietary code –Corporate databases

7 The Framework specification Container model Runtime environment Naming Life-cycle Persistence –Including instance and state management Transactions Security Packaging

8 The benefits Client scalability User performance Reusability Time to market Security Preservation of Heritage data and systems

9 What’s in a name? Enterprise Java Beans has absolutely nothing to do with JavaBeans –Except that both are Java-based component architectures EJB is server-side, JB is client-side –EJB has no GUI, JB usually has GUI JB is basically naming conventions for fully powered Java classes EJB rules are much more rigid EJB classes are less powerful on their own, but more powerful in a container

10 Persistence 2x2 Grid Entity Bean vs. Session Bean Container-Managed vs. Bean-Managed

11 Transactions Support for distributed transactions (more later) You can let the Server manage transactions –You will if you know what’s good for you

12 Secure SSL/RMI protects transmitted data Client-Server architecture protects –proprietary code –backend database SSL authenicates client, server ACLs provide fine-grained control of access to objects, methods, services

13 Multithreaded Programmer delegates all responsibility for multithreading to server –Programmer literally can’t spawn a thread Program designer and/or sysadmin establishes multithreading policies Server enforces them invisibly

14 Naming JNDI Wrapper for many naming services –CORBA, RMI, etc.

15 Developing EJB Applications

16 EJB-Roles Bean developer: creates JAR with: –Remote interface with business functions –Home for accessing instances of bean –Bean itself –Properties and descriptor Assembler: integrates beans into clients Deployer: modifies and deploys beans –Organization-specifics, ie security

17 EJB Roles (cont.) Server provider provides Server run-time Container provider: provides tools and containers –Creates container classes that wrap bean –Manage installed beans

18 EJS EJS Container(s) EJB: Tools and Components Client Enterprise Java Bean JAR Enterprise Java Bean JAR Database Deployment Tool Deployment Tool Assembler tool Assembler tool EJB Authoring Tool EJB Authoring Tool Run-time Design/Deploy time

19 EJB Container model CORBA, COM model has objects aggregating behavior –Leads to very large components EJB = Next step in evolution of frameworks Objects gain services by attaching to container Easier to build, maintain and adapt

20 EJB Container Model cont. Object specifies required services from container –Fits into the framework –Services including persistence, transactions, security, etc. Leads to Business objects and Service Objects

21 EJB Runtime environment EJB Server and EJB Container EJB Server co-ordinates resources for Containers EJB Container vendors implement core services –Object Wrapping, Life-cycle management, Transaction co-ordination, Security, Naming 1 EJB Container for every Class –but more than one class per container

22 ’Tis but thy name that is my enemy EJB is all about really poor names Architecture makes sense, object names don’t –“Home” is a factory –“Container” is a helper or context –“EJB Object” is an object but is not an EJB

23 Romeo and Appliet 'Tis but thy name that is my enemy... What's in a name? That which we call a rose By any other name would smell as sweet. So Java would, were he not Java call'd, Retain that dear perfection which he owes Without that title. Java, doff thy name; And for that name, which is no part of thee, Take all myself. - Gosling, _Romeo and Juliet_, 1595

24 EJB Architecture Client Server Home Interface (Factory) EJB Object (Wrapper) Enterprise Java Bean (Biz Logic) Remote Interface Container RMI Naming Service Implements Invokes Creates / uses

25 EJB Object Persistence Entity Bean –long-term persistence, for data –object identified by unique key –has findByXX methods on Home –only 1 copy of entity instance exists in server Session Bean –short-term persistence, for client –copy of object created for each client Persistence can be Container-Managed or Bean-Managed

26 Session Bean Used for single client –Not shared between clients One per client Can access data in a database Optionally transaction-aware Non-persistent object Removed when server crashes Can be stateless or stateful

27 Entity Bean Represents data in a database Shared between users Always transactional Survives server crash

28 Bean provider: What to write? Remote Interface –extend EJBObject interface –Define business method signatures Home Interface –extend EJBHome interface –Define create signatures –May define findBy signatures for entities

29 What to write (cont.)? Enterprise Bean Class –implement EntityBean or SessionBean –Implement business method signatures –Does not need to implement Remote Interface –not abstract –Implement ejbCreate methods matching Home create 1 ejbCreate for every Home.create N.B.: “create” in home interface, “ejbCreate” in Bean

30 Home Interface Defined by Bean developer Implemented by server tools (autogenerated) Must extend interface EJBHome –EJBMetaData getEJBMetaData() –void remove(Handle ejbHandle) –void remove(Object primaryKey) Must provide your own create() methods –Foo create() –Foo create(Bar b, Baz z)…

31 Home Interface: Entity Beans Entity Beans are persistent, therefore they need more than a “create” method Need findXXX methods –public Foo findByPrimaryKey(Object key); –public Foo findByBar(Bar bar); –public Enumeration findOverdrawnAccounts(); Implement ejbFindXXX methods in bean –N.B.: “find” in home interface, “ejbFind” in Bean

32 Sample EJB (Home Interface) // AccountHome.java: public interface AccountHome extends javax.ejb.EJBHome { public Account create( String name, double startBalance) throws java.rmi.RemoteException, javax.ejb. CreateException ; }

33 Remote Interface Written by developer Defines methods accessible by client –Your business methods go here extends javax.ejb.EJBObject –standard methods provided by all EJBs –getEJBHome(), getPrimaryKey(), getHandle(), remove(), isIdentical(EJBObject obj)

34 Remote Interface vs. EJBObject vs. EJB Developer writes Remote Interface Tool uses RI to automatically generate the EJBObject class Developer writes the EJB source file N.B.: The EJB does not implement the Remote Interface –However, you still must implement all the business methods –Lame-o-rama: no type safety provided by compiler –Better: if EJB tool auto-created a new interface for the EJBObject (oh well)

35 Sample EJB (Remote Interface) // Account.java: public interface Account extends javax.ejb.EJBObject { public void deposit( double depositAmount ) throws java.rmi.RemoteException; public double getBalance() throws java.rmi.RemoteException; }

36 (drum roll…)

37 Implementing the EJB Implements all your business methods Must also implement –ejbCreate() methods –ejbFind() methods (for Entity Beans) Also callback methods –ejbRemove() –ejbActivate() –ejbPassivate() Implement which interface? –javax.ejb.SessionBean –javax.ejb.EntityBean

38 Sample EJB (Session Bean) // AccountBean.java import javax.ejb.*; public class AccountBean implements SessionBean { public String accountName; public double balance; protected SessionContext sessionContext; // Methods public void deposit( double amount) { balance += amount; } public double getBalance() { return balance; } public void ejbCreate ( String accountName, double balance ) throws CreateException, java.rmi.RemoteException {} public void setSessionContext (SessionContext sc) {} public void ejbRemove () {} public void ejbActivate () {} public void ejbPassivate () {} }

39 Interfaces and Implementations EJBObject getEJBHome() getPrimaryKey() getHandle() isIdentical() remove() deposit() getBalance() Remote Interface deposit() getBalance() EJB ejbCreate() ejbRemove() ejbActivate() ejbPassivate() deposit() getBalance() Home Interface create() remove()

40 EJB Clients Use JNDI to locate Home Interface Use RMI to access Home Interface methods Use create() or findXXX() methods to obtain remote reference Invoke business methods on remote reference

41 Sample EJB (Client) import javax.naming.*; public class AccountTest { public static void main(String[] args) throws Exception { Context initialContext = new InitialContext(); AccountHome myAccountHome = (AccountHome)initialContext.lookup("Bank/Account") ; Account myAccount = myAccountHome.create(”Acct1", 50000); myAccount.deposit(30000); double balance = myAccount.getBalance(); } }

42 Deployment Descriptor (DD) Basically a config file for an EJB Read by tools and container Vendor provides DD editor tool Tool outputs a DD as a Java-serialized file Server reads in DD file (as part of EJB Jar) Structural Information –Shouldn’t change Application Assembly Information –Can be changed by Deployer

43 EJBHome PaSpAccountHome PaSpAccountBean PaSpHome PaSpBean PaSpRemote AccountHome Account AccountBean SessionBean EJBObject PaSpRemoteAccount EJB Spec Developer Container Provider Container Provider tools

44 Freeware EJB server ejbhome.com Great Freeware tool –Recently acquired by Iona (Orbix/OrbixWeb) At v 0.51 Generator –create.java files Server –Runs Instances of Objects Deployment Tool Entity/Session –Container managed - will generate accessors! Transactions No JAR files

45 Demo using EJBHome To use Generator create: –Standard: Account, AccountBean, AccountHome –Proprietary: Account properties –Data Source We’ll use ODBC and Excel Spreadsheet Means slight rewriting of generated code –Excel needs `sheet$` for tablename –java com.ejbhome.Generator -f account.properties

46 Demo (cont.) To use Server modify configuration –beans.properties –datasource.properties –ejbhome.properties –java com.ejbhome.EJBServer Normal client –java AccountTest

47 Transactions Simple Transaction –Transaction = more than one statement which must all succeed (or all fail) together –If one fails, the system must reverse all previous actions –Also can’t leave DB in inconsistent state halfway through a transaction –COMMIT = complete transaction –ROLLBACK = abort

48 Transactions (cont.) Distributed Transaction –Transaction involves many objects many statements many hosts many databases –Two-phase commit required

49 Distributed Transaction Example Client starts transaction Withdraws money from numbered Swiss bank account Deposits amount into offshore Cayman Islands account Each remote bank reads and writes from multiple databases Transaction commits across all databases simultaneously

50 Transaction Technology ACID –Atomicity –Consistency –Isolation –Durability Relational DBs –XA Object standards –OMG OTS/JTS –MS ITransact –EJB JTA -> JTS -> OTS

51 Coordinator Object B Object A Prepared? Yes Coordinator Object B Object A Commit Phase 1: PreparePhase 2: Commit Two-phase commit

52 Java Transactions Java Transaction Service (JTS) –A standard Java mapping of the OMG Object Transaction Service (OTS) –packages org.omg.CosTransaction and org.omg.CosTSPortability Java Transaction API (JTA) –High-level transaction management specification –package javax.transaction –class UserTransaction –tx.begin(), tx.commit(), etc.

53 Creating transactional bean Home Interface Bean –Optionally transactional client Deployment Descriptor –Define Transaction attributes –Define Isolation Level Client can define Transactions

54 Three (two?) major styles of transactions Container managed (implicit) –Clients nor Bean developers never see transactions –Specified by descriptor –Safest, most robust technique Bean Managed (explicit) –Bean manages Client Managed (explicit) –Client begins and ends

55 Client Managed Sample: // get Home javax.transaction.UserTransaction tx = (javax.transaction.UserTransaction)home; tx.begin(); // Home.create/find, business methods tx.commit(); // or tx.rollback();

56 Bean-Managed Transactions Same operations as client managed Performed inside methods Bean retrieves transaction context from enterprise context

57 Container-Managed Transactions Container tool converts implicit to explicit Container is the transactional client Usually manages transaction co-ordination Reads EJB-Jar for bean and deployment descriptor 2 Possible uses of DD –Create code to create transaction in applicable methods –Create code to check descriptor at run-time Layers on JTS/JTA

58 More EJB Stuff

59 Client Enterprise Java Bean Enterprise Java Bean Container Transaction Context Transaction Context Deployment Descriptor Deployment Descriptor Container use of context

60 Packaging: EJB-Jar Interface, Home, Bean implementation Deployment Descriptor –Serialized version EntityDescriptor or SessionDescriptor –Contains much, including properties Manifest –1 section for every bean –Each section contains Name: Enterprise-Bean: True –ie: Name: pasp/AccountDeployment.ser Enterprise-Bean: True

61 Enterprise Java Bean Enterprise Java Bean Deployment Descriptor Deployment Descriptor Properties EJB-Jar file Developer EJB Tools Java IDE EJB-Jar Contents

62 CORBA and EJB Transport –EJB uses RMI interface, RMI uses IIOP CORBA 3.0 promises object compatibility with EJB –Not quite sure what that means Some EJB Servers contain an ORB –All EJB Objects are also CORBA objects

63 CORBA and EJB (Cont.) All EJB Servers use CORBA Transactions (via JTS) –That means that any client can make a distributed transaction that includes both CORBA and EJB Objects Not an either-or decision –You can have both EJB and CORBA working together in a single system

64 EJB/ MS comparison

65 FUD: COM Persistence Claimed that Entity objects are bad –Session objects for scalability Assumption #1: –MS knows more than IBM/Sun/Oracle about scalability Assumption #2 –Sessions = more scalability No caching News to CPU and OS vendors Makes sense if you sell small servers Assumption #3 –Entity objects never allowed Why then is there a COM in memory database? –So Entity objects are bad for scalability, but the upcoming imdb is somehow different? Look for MS Entities soon :-)

66 EJB and the Web EJB is very focused on client/server relationships –RMI, IIOP Still useful within context of Web Servers Using Servlets Servlets map HTTP requests to EJB objects Connect an EJB server to Web server EJB server houses all Java objects Servlet calls the container Aside: Perhaps the Web server and servlet is just a container as well. Need to MAP JNDI objects to URL objects –Web server could do mapping

67 Architecture: Object State Stateful objects are caches of back-end –Instance Management in middle-tier Concurrency control, transaction issues Complicated to implement –EJB, IBM Component Broker, BEA Iceberg Think twice if you are building your own IM Stateless objects discarded after operations –No instance management Separate copy of back-end data for each user Simpler –Microsoft vision of scalability of objects Don’t try! –COM+, MTS Must compare equals

68 Architecture: Containment layers Presentation Object Data Object Business Object Persistent Object Presentation (Session) –UI features Business Object (State) –contains other Bos –contains only 1 DO Data Object –No logic –Complex Java object Persistent Object –maps directly to data storage –flat structure Soon in EJB spec

69 EJB Summary Enterprise Java Beans spec –Server-side object model –Container model –Persistence, Transactions, Security, Packaging –1.0 April 98, 1.1 June 99 Commercial and free implementations now available Adds middleware independence to WORA Promises server object re-use Wrapping of existing systems Future of Server-side Java

70 Credits Alex Chaffee (speaker & writer), alex@jguru.com –jGuru Training by the Magelang Institute –http://www.jguru.com/ Dave Orchard (writer) –http://www.pacificspirit.com/daveshome.html


Download ppt "Enterprise Java Beans Alex Chaffee, slides originally created by Dave Orchard"

Similar presentations


Ads by Google