730 likes | 971 Views
Enterprise Java Beans. Alex Chaffee, http://www.jguru.com slides originally created by Dave Orchard http://www.pacificspirit.com/daveshome.html. N-tier Application Architecture. Web Browser. Server maps HTTP request to Business Object request
E N D
Enterprise Java Beans Alex Chaffee, http://www.jguru.com slides originally created by Dave Orchard http://www.pacificspirit.com/daveshome.html
N-tier Application Architecture Web Browser • Server maps HTTP requestto Business Object request • ClientPresentation LogicBusiness Logic - EJBPersistence • 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 Web Server (Servlets) Message Business Object DB access Data Persistence
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
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
EJB Advantages • With EJB, you can write a business object and easily make it • Distributed • Transactional • Secure • Multithreaded • Persistent
EJB Advantages • Can also provide wrappers for legacy apps • Mainframes • Native code • Proprietary code • Corporate databases
The Framework specification • Container model • Runtime environment • Naming • Life-cycle • Persistence • Including instance and state management • Transactions • Security • Packaging
The benefits • Client scalability • User performance • Reusability • Time to market • Security • Preservation of Heritage data and systems
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
Persistence • 2x2 Grid • Entity Bean vs. Session Bean • Container-Managed vs. Bean-Managed
Transactions • Support for distributed transactions (more later) • You can let the Server manage transactions • You will if you know what’s good for you
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
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
Naming • JNDI • Wrapper for many naming services • CORBA, RMI, etc.
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
EJB Roles (cont.) • Server provider provides Server run-time • Container provider: provides tools and containers • Creates container classes that wrap bean • Manage installed beans
EJB: Tools and Components EJS Container(s) Enterprise Java Bean JAR Database Client Run-time Design/Deploy time Assembler tool EJB Authoring Tool Deployment Tool
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
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
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
’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
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
Naming Service Server Container Home Interface (Factory) RMI Client RMI Remote Interface EJB Object (Wrapper) Enterprise Java Bean (Biz Logic) Implements Invokes Creates / uses EJB Architecture
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
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
Entity Bean • Represents data in a database • Shared between users • Always transactional • Survives server crash
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
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
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)…
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
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; }
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)
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)
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; }
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
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 () {} }
Interfaces and Implementations Remote Interface deposit() getBalance() Home Interface create() remove() EJBObject getEJBHome() getPrimaryKey() getHandle() isIdentical() remove() deposit() getBalance() EJB ejbCreate() ejbRemove() ejbActivate() ejbPassivate() deposit() getBalance()
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
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();} }
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
EJBHome EJBObject SessionBean EJB Spec Developer AccountHome Account AccountBean Container Provider PaSpBean PaSpHome PaSpRemote Container Provider tools PaSpAccountHome PaSpRemoteAccount PaSpAccountBean
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
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
Demo (cont.) • To use Server modify configuration • beans.properties • datasource.properties • ejbhome.properties • java com.ejbhome.EJBServer • Normal client • java AccountTest
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
Transactions (cont.) • Distributed Transaction • Transaction involves • many objects • many statements • many hosts • many databases • Two-phase commit required
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
Transaction Technology • ACID • Atomicity • Consistency • Isolation • Durability • Relational DBs • XA • Object standards • OMG OTS/JTS • MS ITransact • EJB • JTA -> JTS -> OTS