enterprise java beans

Post on 30-Dec-2015

57 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

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

Enterprise Java Beans

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

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

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

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.

Developing EJB Applications

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

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

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

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

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;

}

(drum roll…)

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.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 () {}}

Interfaces and Implementations

EJBObjectgetEJBHome()

getPrimaryKey()getHandle()isIdentical()

remove()deposit()

getBalance()

Remote Interfacedeposit()

getBalance()

EJBejbCreate()

ejbRemove()ejbActivate()

ejbPassivate()deposit()

getBalance()

Home Interfacecreate()remove()

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

EJBHomeEJBHome

PaSpAccountHomePaSpAccountHome PaSpAccountBeanPaSpAccountBean

PaSpHomePaSpHomePaSpBeanPaSpBeanPaSpRemotePaSpRemote

AccountHomeAccountHome AccountAccount AccountBeanAccountBean

SessionBeanSessionBeanEJBObjectEJBObject

PaSpRemoteAccountPaSpRemoteAccount

EJB Spec

Developer

ContainerProvider

Container Provider tools

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

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

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.

Creating transactional bean• Home• Interface• Bean

– Optionally transactional client• Deployment Descriptor

– Define Transaction attributes– Define Isolation Level

• Client can define Transactions

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

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

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

enterprise context

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

More EJB Stuff

ClientClientEnterpriseJava BeanEnterpriseJava Bean

ContainerContainer

TransactionContext

TransactionContext

DeploymentDescriptorDeploymentDescriptor

Container use of context

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

EnterpriseJava BeanEnterpriseJava Bean

DeploymentDescriptorDeploymentDescriptor

PropertiesProperties

EJB-Jar file

DeveloperDeveloper

EJB Tools

Java IDE

EJB-Jar Contents

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

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

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

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

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

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

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

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

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

top related