enterprise java beans

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

Upload: uriah-cruz

Post on 30-Dec-2015

66 views

Category:

Documents


1 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Enterprise  Java Beans

Enterprise Java Beans

Alex Chaffee, http://www.jguru.comslides originally created by Dave Orchard

http://www.pacificspirit.com/daveshome.html

Page 2: Enterprise  Java Beans

N-tier Application Architecture• Server maps HTTP request

to Business Object request• Client

Presentation 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

DB access

Web Browser

Business Object

Data Persistence

Web Server(Servlets)

Message

Page 3: Enterprise  Java Beans

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

Page 4: Enterprise  Java Beans

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

Page 5: Enterprise  Java Beans

EJB Advantages• With EJB, you can write a business object

and easily make it– Distributed– Transactional– Secure– Multithreaded– Persistent

Page 6: Enterprise  Java Beans

EJB Advantages• Can also provide wrappers for legacy apps

– Mainframes– Native code– Proprietary code– Corporate databases

Page 7: Enterprise  Java Beans

The Framework specification• Container model • Runtime environment• Naming• Life-cycle• Persistence

– Including instance and state management• Transactions• Security• Packaging

Page 8: Enterprise  Java Beans

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

Page 9: Enterprise  Java Beans

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

Page 10: Enterprise  Java Beans

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

Page 11: Enterprise  Java Beans

Transactions• Support for distributed transactions (more

later)• You can let the Server manage transactions

– You will if you know what’s good for you

Page 12: Enterprise  Java Beans

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

Page 13: Enterprise  Java Beans

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

Page 14: Enterprise  Java Beans

Naming• JNDI• Wrapper for many naming services

– CORBA, RMI, etc.

Page 15: Enterprise  Java Beans

Developing EJB Applications

Page 16: Enterprise  Java Beans

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

Page 17: Enterprise  Java Beans

EJB Roles (cont.)• Server provider provides Server run-time• Container provider: provides tools and

containers– Creates container classes that wrap bean– Manage installed beans

Page 18: Enterprise  Java Beans

EJS

EJS

Container(s)Container(s)

EJB: Tools and Components

ClientClient

EnterpriseJava Bean

JAR

EnterpriseJava Bean

JARDatabaseDatabase

Deployment Tool

Deployment Tool

Assemblertool

Assemblertool

EJBAuthoring

Tool

EJBAuthoring

Tool

Run-time

Design/Deploytime

Page 19: Enterprise  Java Beans

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

Page 20: Enterprise  Java Beans

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

Page 21: Enterprise  Java Beans

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

Page 22: Enterprise  Java Beans

’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

Page 23: Enterprise  Java Beans

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

Page 24: Enterprise  Java Beans

EJB Architecture

Client

Server

Home Interface(Factory)

EJB Object(Wrapper) Enterprise

Java Bean(Biz Logic)

RemoteInterface

Container

RMI

RMI

Naming Service

Implements

Invokes

Creates / uses

Page 25: Enterprise  Java Beans

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

Page 26: Enterprise  Java Beans

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

Page 27: Enterprise  Java Beans

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

Page 28: Enterprise  Java Beans

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

Page 29: Enterprise  Java Beans

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

Page 30: Enterprise  Java Beans

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)…

Page 31: Enterprise  Java Beans

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

Page 32: Enterprise  Java Beans

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 ;}

Page 33: Enterprise  Java Beans

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)

Page 34: Enterprise  Java Beans

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)

Page 35: Enterprise  Java Beans

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;

}

Page 36: Enterprise  Java Beans

(drum roll…)

Page 37: Enterprise  Java Beans

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

Page 38: Enterprise  Java Beans

Sample EJB (Session Bean)// AccountBean.javaimport 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 () {}}

Page 39: Enterprise  Java Beans

Interfaces and Implementations

EJBObjectgetEJBHome()

getPrimaryKey()getHandle()isIdentical()

remove()deposit()

getBalance()

Remote Interfacedeposit()

getBalance()

EJBejbCreate()

ejbRemove()ejbActivate()

ejbPassivate()deposit()

getBalance()

Home Interfacecreate()remove()

Page 40: Enterprise  Java Beans

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

Page 41: Enterprise  Java Beans

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();}

}

Page 42: Enterprise  Java Beans

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

Page 43: Enterprise  Java Beans

EJBHomeEJBHome

PaSpAccountHomePaSpAccountHome PaSpAccountBeanPaSpAccountBean

PaSpHomePaSpHomePaSpBeanPaSpBeanPaSpRemotePaSpRemote

AccountHomeAccountHome AccountAccount AccountBeanAccountBean

SessionBeanSessionBeanEJBObjectEJBObject

PaSpRemoteAccountPaSpRemoteAccount

EJB Spec

Developer

ContainerProvider

Container Provider tools

Page 44: Enterprise  Java Beans

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

Page 45: Enterprise  Java Beans

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

Page 46: Enterprise  Java Beans

Demo (cont.)• To use Server modify configuration

– beans.properties– datasource.properties– ejbhome.properties– java com.ejbhome.EJBServer

• Normal client– java AccountTest

Page 47: Enterprise  Java Beans

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

Page 48: Enterprise  Java Beans

Transactions (cont.)• Distributed Transaction

– Transaction involves • many objects• many statements• many hosts• many databases

– Two-phase commit required

Page 49: Enterprise  Java Beans

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

Page 50: Enterprise  Java Beans

Transaction Technology• ACID

– Atomicity– Consistency– Isolation– Durability

• Relational DBs– XA

• Object standards– OMG OTS/JTS– MS ITransact– EJB

• JTA -> JTS -> OTS

Page 51: Enterprise  Java Beans

CoordinatorCoordinator

Object BObject BObject AObject A

Prepared?Prepared?

Yes Yes

CoordinatorCoordinator

Object BObject BObject AObject A

Commit Commit

Phase 1: Prepare Phase 2: Commit

Two-phase commit

Page 52: Enterprise  Java Beans

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.

Page 53: Enterprise  Java Beans

Creating transactional bean• Home• Interface• Bean

– Optionally transactional client• Deployment Descriptor

– Define Transaction attributes– Define Isolation Level

• Client can define Transactions

Page 54: Enterprise  Java Beans

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

Page 55: Enterprise  Java Beans

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();

Page 56: Enterprise  Java Beans

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

enterprise context

Page 57: Enterprise  Java Beans

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

Page 58: Enterprise  Java Beans

More EJB Stuff

Page 59: Enterprise  Java Beans

ClientClientEnterpriseJava BeanEnterpriseJava Bean

ContainerContainer

TransactionContext

TransactionContext

DeploymentDescriptorDeploymentDescriptor

Container use of context

Page 60: Enterprise  Java Beans

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: <relative offset of descriptor>• Enterprise-Bean: True

– ie:• Name: pasp/AccountDeployment.ser

Enterprise-Bean: True

Page 61: Enterprise  Java Beans

EnterpriseJava BeanEnterpriseJava Bean

DeploymentDescriptorDeploymentDescriptor

PropertiesProperties

EJB-Jar file

DeveloperDeveloper

EJB Tools

Java IDE

EJB-Jar Contents

Page 62: Enterprise  Java Beans

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

Page 63: Enterprise  Java Beans

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

Page 64: Enterprise  Java Beans

EJB/ MS comparisonFeature EJB DNA/MTS

Specification Yes Yes

Servers/Tools Yes Yes

Containers Yes Yes

Implicit TX Yes Yes

Cross-language Yes (CORBA) Yes (COM)

Client Platform Many Windows

Server Platform Many Windows

Object-Oriented Yes No (COM+)

Vendors Many 1

Persistence Session/Entity Session

Page 65: Enterprise  Java Beans

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 :-)

Page 66: Enterprise  Java Beans

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

Page 67: Enterprise  Java Beans

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

Page 68: Enterprise  Java Beans

Architecture: Containment layers

PresentationObject

Data Object

Business Object

PersistentObject

• 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

Page 69: Enterprise  Java Beans

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

Page 70: Enterprise  Java Beans

Credits• Alex Chaffee (speaker & writer),

[email protected]– jGuru Training by the Magelang Institute– http://www.jguru.com/

• Dave Orchard (writer) – http://www.pacificspirit.com/daveshome.html