distributed object-oriented programming (3) – enterprise javabeans snu idb lab. taewhi lee may...
TRANSCRIPT
Distributed Object-Oriented Programming(3) – Enterprise JavaBeans
SNU iDB Lab.Taewhi Lee
May 14th, 2007
Review – Distributed Programming
Paradigm Shift
Socket
RPC
CORBA RMI
CORBA Component
Model
OOP CBD Object – limited reusability Component – independent service Several components are plugged
in to a component architecture
systemStructured Programming
OOP SP – Complexity of system modeling Difficulty in code change/extension OOP – Natural object modeling Reusability by inheritance Flexibility by polymorphism
Distributed Component Model
Distributed Object Model
Basic Inter-Process Communication
Distributed Structural Model
Web Services
Service-Oriented Architecture
Distributed Computing SOA DC – client/server are tightly coupled SOA – everything is decoupled
EJB
Outline
Java EE
EJB Overview
Enterprise Beans
EJB Programming
Changes in EJB 3.0
References
Java EE [1/5]
Jave EE History
1995 1998 1998 2004~
Java J2SE J2EE Java SEJava EE
Object-oriented
Platform-independe
nt
Garbage collection
For Stand-alone
applications
Java 1.2 +Libraries(e.g. GUI,
DB, networkin
g)
Since Java 1.5
For Distributed enterprise application
s
J2SE +Libraries
(e.g. Security,
Transaction)
Java EE [2/5]
What is Jave EE? Java EE (Java Platform, Enterprise Edition)
The industry standard for developing enterprise applications Portable, robust, scalable and secure server-side Java applications
Provides web services, component model, management, and communication APIs
Java EE goals Highly available – to meet the needs of today’s global business
environment Secure – to protect the privacy of users and the integrity of
enterprise data Reliable and scalable – to insure that business transactions are
accurately and promptly processed
Java EE [3/5]
Jave EE & EJBJava EE
WebServices
Technologies
WebApplication
Technologies
Management& Security
Technologies
EnterpriseApplication
Technologies
Java EE [4/5]
Jave EE Technologies Web Services Technologies
Implementing Enterprise Web Services Java API for XML-Based Web Services (JAX-WS) 2.0 Java API for XML-Based RPC (JAX-RPC) 1.1 Java Architecture for XML Binding (JAXB) 2.0 SOAP with Attachments API for Java (SAAJ) Streaming API for XML Web Service Metadata for the Java Platform
Web Application Technologies Java Servlet 2.5 JavaServer Faces 1.2 JavaServer Pages 2.1 JavaServer Pages Standard Tag Library
Java EE [5/5]
Jave EE Technologies (cont’d) Enterprise Application Technologies
Enterprise JavaBeans 3.0 J2EE Connector Architecture 1.5 Common Annotations for the Java Platform Java Message Service API The Java Database Connectivity API (JDBC) Java Persistence API Java Transaction API (JTA) JavaBeans Activation Framework (JAF) 1.1 JavaMail
Management and Security Technologies J2EE Application Deployment J2EE Management Java Authorization Contract for Containers
Outline
Java EE
EJB Overview
Enterprise Beans
EJB Programming
Changes in EJB 3.0
References
EJB Overview [1/11]
What are Enterprise JavaBeans? Enterprise JavaBeans (EJB)
A standard-based component model APIs to implement business logics
EJB design goals Common services
Multithreading Transaction management Resource management (e.g., connection pooling) Persistence management Security services
Distribution and scalability “Throw money at it” solution
EJB Overview [2/11]
EJB Architecture
EJB architecture Specifies the responsibilities and interactions
among EJB entities
EJB ServerEJB Server
EJB ContainerClients
Enterprise
Bean
Enterprise
Bean
EJB Client
EJB ServerEJB Server
EJB ContainerClients
Enterprise
Bean
Enterprise
Bean
EJB Client
EJB Overview [3/11]
EJB Server
EJB server Provides a run-time environment Provides system services and manages
resources Process and thread management System resources management Database connection pooling and caching Management API
EJB ServerEJB Server
EJB ContainerClients
Enterprise
Bean
Enterprise
Bean
EJB Client
EJB Overview [4/11]
EJB Container EJB container
Provides a run-time environment for an enterprise bean
Likely provided by server vendor Hosts the EJBs and provides services to EJBs
Naming Life cycle management Persistence (state management) Transaction Management Security
EJB ServerEJB Server
EJB ContainerClients
Enterprise
Bean
Enterprise
Bean
EJB Client
EJB Overview [5/11]
Enterprise Bean
Enterprise Bean A specialized component for the real business
logic Consists of several classes and interfaces Distributed over a network
Server vendors provide tools that automatically generate distribution, transaction and security behavior
EJB ServerEJB Server
EJB ContainerClients
Enterprise
Bean
Enterprise
Bean
EJB Client
EJB Overview [6/11]
EJB Client
Client access is controlled by the container in which the enterprise bean is deployed
Clients locates an enterprise bean through Java Naming and Directory Interface (JNDI)
RMI is the standard method for accessing a bean over a network
EJB ServerEJB Server
EJB ContainerClients
Enterprise
Bean
Enterprise
Bean
EJB Client
EJB Overview [7/11]
Pros and Cons of EJB Pros
Component modularization Reusability ↑ , maintenance cost ↓
Component portability “Write Once, Run Anywhere” (WORA)
Development simplification A number of tricky middleware services are automatically
managed Programmers can concentrate on writing business logic
Development speed ↑ , code quality ↑
Cons Need to buy EJB container Implementation according to EJB specification
EJB Overview [8/11]
RMI vs. EJB
RMI EJB
Business object type Distributed objectDistributed component
Basic communication protocol
RMI RMI
Business method declaration
Remote interface Remote interface
Business method implementation
Remote class Bean class
How to implement business method
Remote class directly implements remote
interfaceDelegation
Business object construction,
destruction, findNo Home interface
Middleware services(transaction, security…)
No Yes
EJB Overview [9/11]
Code example: HelloWorld in RMI
Remote interface
Remote class
public interface Hello extends Remote { public String sayHello(String name) throws RemoteException;}
public class HelloImpl extends UnicastRemoteObject implements Hello { public HelloImpl() throws RemoteException { } public String sayHello(String name) throws RemoteException { return “Hello, ” + name; }}
EJB Overview [10/11]
Code example: HelloWorld in EJB
Home interface
Remote interface
public interface HelloHome extends EJBHome { public Hello create() throws RemoteException, CreateException;}
public interface Hello extends EJBObject { public String sayHello(String name) throws RemoteException;}
EJB Overview [11/11]
Code example: HelloWorld in EJB (cont’d)
Bean classpublic class HelloBean implements SessionBean { SessionContext ctx; // EJB container contract methods public void ejbCreate() { } public void ejbRemove() { } public void ejbActivate() { } public void ejbPassivate() { } public void setSessionContext(SessionContext ctx) { this.ctx = ctx; } // business method public String sayHello(String name) { return “Hello, ” + name; }}
Outline
Java EE
EJB Overview
Enterprise Beans
EJB Programming
Changes in EJB 3.0
References
Enterprise Bean [1/7]
Types of Enterprise Beans
Session bean Implements some business logic Business process component
e.g., order, payment in an online shopping mall
Entity bean Object-oriented view of entities stored in
persistent storage Normally, each instance represents a row in a RDB
table
e.g., product information, user information
Enterprise Bean [2/7]
Types of Enterprise Beans
Stateful session bean Maintains a state The state is relevant only for a single client
Cannot be seen by other clients Expires after a certain timeout
e.g., shopping cart
Enterprise Bean [3/7]
Stateful Session Bean
Stateless session bean No state
Can have fields, but they are not unique to any client
Since the container knows the bean has no state, it can: Use a single bean instance (while each client thinks it has
its own copy) Destroy/re-instantiate on the fly Redirect requests to different instances (load balancing)
e.g., currency conversion
Enterprise Bean [4/7]
Stateless Session Bean
CMP(Container-Managed Persistence) entity bean Container is responsible for saving the persistent
state
DB-related classes are auto-generated
You specify the container-managed attributes
Persistence is independent of the data source The mapping can be applied to other DBs very portable
Container can manage caching, locking strategies
Can only be used with data sources supported by JDBC
Enterprise Bean [5/7]
CMP Entity Bean
BMP(Bean-Managed Persistence) entity bean The bean writer must provide code for
storing/restoring persistent state
Less portable
Can exploit any persistence framework Not limited to databases
Manual tuning can result in performance benefits At the price of portability and hard work
Enterprise Bean [6/7]
BMP Entity Bean
Deployment Process to plug-in enterprise beans to EJB
container
Jar packaging + plug-in
Class files are auto-generated
Deployment Descriptor XML file
Additional information to run enterprise beanse.g., transaction type, security information
Makes it possible to use enterprise beans which are developed by other developers
Enterprise Bean [7/7]
Deployment Descriptor
Outline
Java EE
EJB Overview
Enterprise Beans
EJB Programming
Changes in EJB 3.0
References
Choice of the bean type Session bean? Entity bean?
Session bean – Stateful? Stateless?
Entity bean – CMP? BMP?
Code writing Home interface
Remote interface
Bean class
Primary key class (entity bean only)
Deployment descriptor
EJB Programming [1/25]
EJB Programming
Template
Example
public interface <BeanName>Home extends javax.ejb.EJBHome { public <BeanName> create(<rmiParams>) throws [<otherException>, …]
javax.ejb.CreateException, java.rmi.RemoteException;}
public interface CartHome extends EJBHome { public Cart create(String customerName, String account) throws BadAccountException, CreateException, RemoteException;}
EJB Programming [2/25] Stateful Session Bean (1/6) Code Example: Shopping Cart – Home Interface
Template
Example
public interface <BeanName> extends javax.ejb.EJBObject { public <rmiReturnType> <businessMethod> (<rmiParams>) throws
[<otherException>, …], java.rmi.RemoteException;}
public interface Cart extends EJBObject { public void addItem(int item) throws RemoteException; public void purchase() throws RemoteException;}
EJB Programming [3/25] Stateful Session Bean (2/6) Code Example: Shopping Cart – Remote Interface
Templatepublic class <BeanName>Bean implements javax.ejb.SessionBean { public <rmiReturnType> <businessMethod> (<rmiParams>) throws
[<otherException>, …], java.rmi.RemoteException { { /* implementation */ } // … other business methods
// EJB container contract methods public void ejbCreate (<rmiParams>) … { /* implementation */ } private SessionContext _context; public void setSessionContext(SessionContext ctx) { _context = ctx; } public void ejbRemove() { /* implementation */ } public void ejbActivate() { } public void ejbPassivate() { } }
EJB Programming [4/25] Stateful Session Bean (3/6) Code Example: Shopping Cart – Bean Class
Examplepublic class CartBean implements SessionBean { private SessionContext _context; private String customerName, account; // to maintain state information
public void setSessionContext(SessionContext ctx) { _context = ctx; } public void ejbCreate (String customerName, String account) { this.customerName = customerName; this.account = account; } public void ejbRemove() { } public void ejbActivate() { /* implementation for activation */ } public void ejbPassivate() { /* implementation for de-activation */ }
public void addItem(int item) { /* implementation */ } public void purchase() { /* implementation */ } }
EJB Programming [5/25] Stateful Session Bean (4/6) Code Example: Shopping Cart – Bean Class (cont’d)
<session id=“Cart"><ejb-name>Cart</ejb-name><home>demo.j2ee. CartHome</home><remote>demo.j2ee. Cart</remote><ejb-class>demo.j2ee.CartBean</ejb-class><session-type>Stateful</session-type><transaction-type>Container</transaction-type>
</session>
EJB Programming [6/25] Stateful Session Bean (5/6) Deployment Descriptor – Shopping Cart
Context initialContext = new InitialContext();
// Get the reference of the home object using JNDI CartHome cartHome = (CartHome)PortableRemoteObject.narrow(
initialContext.lookup(“java:comp/env/ejb/cart”), CartHome.class);
// Create EJB objectCart cart = cartHome.create(“John”, “7506”);
cart.addItem(96); // business method callcart.purchase();
EJB Programming [7/25] Stateful Session Bean (6/6) Code Example: Shopping Cart – Client code
Template
Example
EJB Programming [8/25] Stateless Session Bean (1/5) Code Example: Currency Converter – Home Interface
public interface <BeanName>Home extends javax.ejb.EJBHome { public <BeanName> create() throws javax.ejb.CreateException,
java.rmi.RemoteException;}
public interface CurrencyConverterHome extends EJBHome { public CurrencyConverter create() throws CreateException,
RemoteException;}
Template
Example
public interface <BeanName> extends javax.ejb.EJBObject { public <rmiReturnType> <businessMethod> (<rmiParams>) throws
[<otherException>, …], java.rmi.RemoteException;}
public interface CurrencyConverter extends EJBObject { public double convertUsdToWon(double usd) throws RemoteException;}
EJB Programming [9/25] Stateless Session Bean (2/5) Code Example: Currency Converter – Remote Interface
Templatepublic class <BeanName>Bean implements javax.ejb.SessionBean { public <rmiReturnType> <businessMethod> (<rmiParams>) throws
[<otherException>, …], java.rmi.RemoteException { { /* implementation */ } // … other business methods
// EJB container contract methods public void ejbCreate() … { /* implementation */ } private SessionContext _context; public void setSessionContext(SessionContext ctx) { _context = ctx; } public void ejbRemove() { /* implementation */ } public void ejbActivate() { } public void ejbPassivate() { } }
EJB Programming [10/25] Stateless Session Bean (3/5) Code Example: Currency Converter – Bean Class
Examplepublic class CurrencyConverterBean implements SessionObject { private SessionContext _context; private static final double WON_PER_USD = 950;
public void setSessionContext(SessionContext ctx) { _context = ctx; } public void ejbCreate () { } public void ejbRemove() { } public void ejbActivate() { } public void ejbPassivate() { }
public double convertUsdToNis(double usd) { return usd * WON_PER_USD; }}
EJB Programming [11/25] Stateless Session Bean (4/5) Code Example: Currency Converter – Bean Class (cont’d)
<session id="CurrencyConverter"><ejb-name>CurrencyConverter</ejb-name><home>demo.CurrencyConverterHome</home><remote>demo.CurrencyConverter</remote><ejb-class>demo.CurrencyConverterBean</ejb-
class><session-type>Stateless</session-type><transaction-type>Container</transaction-type>
</session>
EJB Programming [12/25] Stateless Session Bean (5/5) Deployment Descriptor – Currency Converter
EJB Programming [13/25]
Session Bean Lifecycle
Template
EJB Programming [14/25] CMP Entity Bean (1/6) Code Example: Product – Home Interfacepublic interface <BeanName>Home extends javax.ejb.EJBHome { public <BeanName> create(<rmiParams>) throws [<otherException>, …]
javax.ejb.CreateException, java.rmi.RemoteException; public <BeanName> findByPrimaryKey(<PrimaryKey>) throws [<otherException>, …] javax.ejb.CreateException, java.rmi.RemoteException; public Collection findXXX(<rmiParams>) throws [<otherException>, …] javax.ejb.CreateException, java.rmi.RemoteException;}
Example
EJB Programming [15/25] CMP Entity Bean (2/6) Code Example: Product – Home Interface
public interface ProductHome extends EJBHome { public Product create(String productId, String description, double price) throws CreateException, RemoteException; public Product findByPrimaryKey(String productId) throws
RemoteException, FinderException; public Collection findByPriceRange(double low, double high) throws
RemoteException, FinderException;}
Example
EJB Programming [16/25] CMP Entity Bean (3/6) Code Example: Product – Remote Interface
public interface Product extends EJBObject { public void setPrice(double price) throws RemoteException; public double getPrice() throws RemoteException; public String getDescription() throws RemoteException;}
Example
EJB Programming [17/25] CMP Entity Bean (4/6) Code Example: Product – Bean Class
public class ProductBean implements EntityBean { public String productId, description; public double price;
private EntityContext context;
public ejbCreate(String productId, String description, double price) throws CreateException { if (productId == null) throw new CreateException(“productId required.”); this.productId = productId; this.description = description; this.price = price; return null; }
Example (cont’d)
EJB Programming [18/25] CMP Entity Bean (5/6) Code Example: Product – Bean Class (cont’d)
public void setPrice(double price) { this.price = price; } public double getPrice() { return price; } public String getDescription() { return description; }
public void setEntityContext(EntityContext ctx) { this.context = ctx; } public void ejbActivate() { productId = (String)context.getPrimaryKey(); } public void ejbPassivate() { productId = null; description = null; }
public void ejbRemove() { } public void ejbLoad() { } public void ejbStore() { } public void unsetEntityContext() { } public void ejbPostCreate(String productId, String description, double price) { }}
<entity id="Account"> <persistence-type>Container</persistence-type> <ejb-name>Product</ejb-name> <home>demo.ProductHome</home> <remote>demo.Product</remote> <ejb-class>demo.ProductBean</ejb-class> <prim-key-class>java.lang.String</prim-key-class> <abstract-schema-name>Product</abstract-schema-name> <cmp-field><field-name>productId</field-name></cmp-field> <cmp-field><field-name>description</field-name></cmp-field> <cmp-field><field-name>price</field-name></cmp-field> <primkey-field>productId</primkey-field> <query> <query-method> <method-name>findByPriceRange</method-name> </query-method>
<ejb-ql>select object(o) from Product owhere o.price >= ?1 and o.price <= ?2</ejb-ql>
</query></entity>
EJB Programming [19/25] CMP Entity Bean (6/6) Deployment Descriptor – Product
Example
EJB Programming [20/25] BMP Entity Bean (1/5) Code Example: Product – Bean Class
…// Not to locate the record, but to verify that the record existspublic String ejbFindByPrimaryKey(String primaryKey) throws FinderException { boolean result; try { result = selectByPrimaryKey(primaryKey) } catch (Exception e) { } if (result) return primaryKey; else throw new ObjectNotFoundException(“Row for ” + primaryKey + “ not found”);}…
Example
EJB Programming [21/25] BMP Entity Bean (2/5) Code Example: Product – Bean Class
…public boolean selectByPrimaryKey(String primaryKey) throws SQLException { String selectStmt = “select productId ” + “from product where productId = ?”; PreparedStatement prepStmt = _conn.prepareStatement(selectStmt); prepStmt.setString(1, primaryKey);
ResultSet rs = prepStmt.executeQuery(); boolean result = rs.next(); prepStmt.close(); return result;}…
Example
EJB Programming [22/25] BMP Entity Bean (3/5) Code Example: Product – Bean Class
public void ejbLoad() { try { loadRow(); } catch (Exception e) { }}Private void loadRow() throws SQLException { String selectStmt = “select description, price ” + “from product where productId = ?”; PreparedStatement prepStmt = _conn.prepareStatement(selectStmt); prepStmt.setString(1, this.productId); ResultSet rs = prepStmt.executeQuery(); if (rs.next()) { this.description = rs.getString(1); this.price = rs.getDouble(2); } else throw new NoSuchEntityException(“Row for ” + productId + “not found”);}
Example
EJB Programming [23/25] BMP Entity Bean (4/5) Code Example: Product – Bean Class
public Collection ejbFindByPriceRange(double low, double high) throws FinderException { try { result = selectByPriceRange(low, high); } catch (Exception e) { } if (result.isEmpty()) throw new ObjectNotFoundException(“No rows found”); else return result;}
Example
EJB Programming [24/25] BMP Entity Bean (5/5) Code Example: Product – Bean Class
public Collection selectByPriceRange(double low, double high) throws SQLException { String selectStmt = “select productId from product ” + “where price >= low and price <= high”; PreparedStatement prepStmt = _conn.prepareStatement(selectStmt); prepStmt.setDouble(1, low); prepStmt.setDouble(2, high); ResultSet rs = prepStmt.executeQuery(); ArrayList a = new ArrayList(); while (rs.next()) { String productId = rs.getString(1); a.add(productId); } prepStmt.close(); return a;}
EJB Programming [25/25]
Entity Bean Lifecycle
Does not exist
Ready
Pooled
newInstance()setEntityContext()
unset-EntityContext()
ejbRemove() orejbPassivate()
ejbCreate()or ejbActivate()
ejbLoad()business method
ejbStore()
Outline
Java EE
EJB Overview
Enterprise Beans
EJB Programming
Changes in EJB 3.0
References
EJB 2.1 technology very powerful, but too complex Too many classes, interfaces Boilerplate javax.ejb interface methods Clumsy programming model Deployment descriptors
EJB 3.0 Goals Make EJB easier to learn and use Improve developer productivity Attract broader range of developers
Changes in EJB 3.0 [1/3]
Motivation
Simplification of the EJB APIs Removal of need for EJBHome and EJBObject Removal of JNDI APIs from developer and client
view Removal of need for deployment descriptors
Use advantages of Java language metadata Metadata designed so that the most common
cases are easiest to express Defaults available for expected cases
More work is done by container, less by developer
Changes in EJB 3.0 [2/3]
EJB 3.0 Approach
Example
Enterprise Bean [3/3] Stateful Session Bean (1/4) Code Example: Shopping Cart – Bean Class
@stateful public class CartBean implements Cart{ public int addItem(int item) { … } public void purchase() { … } … @PreDestroy remove() { … }}
public interface Cart { public int addItem(int item); public void purchase();}
No Home interface Deployment descriptor
annotations
Outline
Java EE
EJB Overview
Enterprise Beans
EJB Programming
Changes in EJB 3.0
References
References
EJB 프로그래밍 입문http://www.javastudy.co.kr/docs/lec_ejb/ejb/sunny_ejb1.pdf
Jboss – open source
http://labs.jboss.com/
http://sourceforge.net/projects/jboss (download)