EJB Development and Support Services

48
EJB Development and Support Services

description

EJB Development and Support Services. EJB Development and Support Services. Topics to be Covered: EJB Design Bean/Container Interaction Java Naming and Directory Interface (JNDI) Using Enterprise Beans Server Side Services. EJB Development and Support Services. EJB Design. - PowerPoint PPT Presentation

Transcript of EJB Development and Support Services

Page 1: EJB Development and Support Services

EJB Development andSupport Services

Page 2: EJB Development and Support Services

EJB Development andSupport ServicesTopics to be Covered:• EJB Design• Bean/Container Interaction• Java Naming and Directory Interface

(JNDI)• Using Enterprise Beans• Server Side Services

Page 3: EJB Development and Support Services

EJB Development andSupport Services

EJB Design

Page 4: EJB Development and Support Services

Class and Interface Review• javax.ejb package

– Core of the EJB API• Remote interface

– Defines bean’s remote business methods• Local interface

– Defines bean’s local business methods• Endpoint interface

– Defines SOAP-accessible business methods• Message interface

– Defines methods for asynchronous messages• Bean class

– Implementation of business and lifecycle methods

Page 5: EJB Development and Support Services

Remote Interface• Defines business methods

import javax.ejb.Remote;

@Remotepublic interface CalculatorRemote {public int add(int x, int y);public int subtract(int x, int y);

}

Page 6: EJB Development and Support Services

Bean Class• Actual implementation of business

methodsimport javax.ejb.*;@Statelesspublic class CalculatorBean

implements CalculatorRemote {

public int add(int x, int y) {return x + y;}public int subtract(int x, int y) {return x – y;}

}

Page 7: EJB Development and Support Services

Entity• Java Persistence API

import javax.persistence.*;

@Entity@Table(name=“CABIN”)

public class Cabin {

private int id;private String name;private int deckLevel;

Page 8: EJB Development and Support Services

Primary Key@Id@GeneratedValue@Column(name=“ID”)public int getId() { return id; }

public void setId(int pk) { this.id = pk; }

Page 9: EJB Development and Support Services

Remaining Fields@Column(name=“NAME”)public String getName() { return name; }

public void setName(String str) { this.name = str; }

@Column(name=“DECK_LEVEL”)public int getDeckLevel() { return deckLevel; }

public void setDeckLevel(int level) { this.deckLevel = level; }

}

Page 10: EJB Development and Support Services

Primary Keys• Pointer that locates an enterprise bean• Defined by the bean developer• Must map to one of the following types:

– Any Java primitive type (including wrappers)

– java.lang.String– Primary-key class composed of

primitives and/or Strings

Page 11: EJB Development and Support Services

Primary Key Class• Composed of primitives and/or strings• Must be serializable• Must have a public no-arg constructor• Must implement the equals() and hashCode() methods

Page 12: EJB Development and Support Services

Deployment Descriptors• Specifies how to apply primary services

– security– transactions– naming

• Specifies persistence unit and associated database

• Describe runtime attributes of server-side component

Page 13: EJB Development and Support Services

EJB Packaging• JAR Files used for packaging

– Applets– Applications– JavaBeans– Web Application– Enterprise JavaBeans

•Bean classes•Component interfaces•Supporting Classes•Appropriate Deployment Descriptors

Page 14: EJB Development and Support Services

Example Deployment Descriptor<?xml version="1.0"?><ejb-jar>

<enterprise-beans> <session> <ejb-name>ProcPayBean</ejb-name> <remote>com.relaxalot.ProcPayRemote</remote> <local>com.relaxalot.ProcPayLocal</local> <ejb-class>com.relaxalot.ProcPayBean</ejb-class>

<session-type>Stateless</session-type> </session></enterprise-beans>

</ejb-jar>

Page 15: EJB Development and Support Services

XML and/or Annotations• Defaults make XML deployment

descriptors optional– Default transaction property

REQUIRED– Default security semantics

UNCHECKED• Annotations provide further information

– Metadata placed directly in the bean class file

– Deployment descriptors can override annotations

Page 16: EJB Development and Support Services

Example persistence.xml

<persistence><persistence-unit name=“titan”> <jta-data-source>java:/TitanDB</jta-data-source>

</persistence-unit></persistence>

Page 17: EJB Development and Support Services

EJB Development andSupport Services

Bean/Container Interaction

Page 18: EJB Development and Support Services

EJB Container Implementation• Component interfaces allow external or

co-located clients to interact with session bean class

• Component interfaces interact with instances of the session bean class

• Proxy Stub– Interacts with client, sends message

to EJB Container• EJB Object

– Implements remote interface– Wraps enterprise bean instance– Generated by the container

Page 19: EJB Development and Support Services

beanremote

interfaceEJB object

EJB Architecture

EJB Container

remoteinterface

EJB objectproxy

Client

Page 20: EJB Development and Support Services

EJB Container• Intermediary between bean and server• Interaction defined by SessionBean

interface, and JMS-MessageDrivenBean onMessage() method

• javax.ejb.EJBContext interface implemented by the container.

• Bean uses EJBContext interface to communicate with EJB environment

• JNDI namespace

Page 21: EJB Development and Support Services

EJB Development andSupport Services

Java Naming andDirectory Interface

(JNDI)

Page 22: EJB Development and Support Services

Naming and Directory Services• Naming Service

– Associates names with Objects– Provides facility to find an object

based on a name– Examples: DNS, File System

• Directory Object– Contains attributes– Like a record in a database

• Directory Service– Provides directory object operations

for manipulating attributes

Page 23: EJB Development and Support Services

JNDI Architecture

JNDI Application

FilesystemService Provider

Filesystem

LDAPService Provider

LDAP Directory

RMIService Provider

RMI Registry

Page 24: EJB Development and Support Services

JNDI API Benefits• Standard Java Extension

– javax.naming– javax.naming.directory

• Unified system for resource access• Insulates application from naming and

directory service protocols• Extensible• Composite or federated namespaces

Page 25: EJB Development and Support Services

Naming Concepts• Binding

– Association of a name with an object• Context

– Set of bindings• Subcontext

– Binding one context within another

usr

bin

tom

Context

Subcontext

Binding

Page 26: EJB Development and Support Services

Context & InitialContext• javax.naming.Context interface

– Collection of bindings– Operations apply only to bindings,

not to Context itself• javax.naming.InitialContext class

– Implements the Context interface– Starting point for exploring a

namespace– Requires an initial context factory

com.sun.jndi.fscontext.RefFSContextFactory

Page 27: EJB Development and Support Services

InitialContext Properties• InitialContext constructor takes a set

of properties

Properties props = new Properties();props.put(Context.INITIAL_CONTEXT_FACTORY,“com.sun.jndi.fscontext.RefFSContextFactory”);props.put(Context.PROVIDER_URL,”file:///”);Context initialContext = new

InitialContext(props);

Page 28: EJB Development and Support Services

Looking Up Objects• lookup() method• Specify the name of the child• Type of returned object determined by

service provider• Container with children should

implement javax.naming.Context

Object obj = initialContext.lookup(name);

Page 29: EJB Development and Support Services

Listing Objects• list() method• Returns a list of names of an object’s

children as an instance of javax.naming.NamingEnumeration

• NamingEnumeration contains a collection of javax.naming.NameClassPair objects

• Browsing is a combination of list() and lookup() calls

NamingEnumberation kids = initialContext.list(name);

Page 30: EJB Development and Support Services

Binding Objects• bind() method• Creates a Binding object• Use rebind() if name already exists• Use unbind() to remove a binding

File newfile = File(“c:\temp\

newfile”);tempContext.bind(“newfile”, newfile);

Page 31: EJB Development and Support Services

JNDI and JDBC• JDBC 2.0 DataSource

– Provides Database connections– Information to create connections are

stored as properties– Registered with a directory service

Context ctx = new InitialContext();DataSource ds = (DataSource)

ctx.lookup(“jdbc/EmployeeDB”);Connection con = ds.getConnection();con.close();

Page 32: EJB Development and Support Services

JNDI and EJB• JNDI used to locate a specific EJB

Home

Context ctx = new InitialContext();Object ref = ctx.lookup(“TravelAgntBean”);TravelAgntRemote dao = (TravelAgntRemote)

PortableRemoteObject.narrow(ref,

TravelAgntRemote.class);dao.makeReservation();

Page 33: EJB Development and Support Services

JNDI Environment Naming Context• Part of Bean-Container Contract• Common naming context

– java:comp/env• Declare resources using XML

deployment descriptor or Annotation– EJBs– JDBC DataSource– Java Message Service– Environment Properties

Context ctx = new InitialContext();

Page 34: EJB Development and Support Services

ENC Example (Deployment Descriptor) – Describing the Resource

<resource-ref><description>DataSource for Relaxalot Database</description><res-ref-name>theDataSource</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth>

<mapped-name>java:/DefaultDS</mapped-name><injection-target><injection-target-class>edu.weber.ProcessPaymentBean</injection-target-class><injection-target-name>dataSource</injection-target-name><injection-target></resource-ref>

Page 35: EJB Development and Support Services

ENC Example (Annotation) – Describing the Resource

public class ProcessPaymentBean implements ProcessPaymentRemote

{...

@Resource(mappedName=“java:/DefaultDS”)DataSource dataSource

Page 36: EJB Development and Support Services

ENC Example – Use the Resource

public class ProcessPaymentBean implements ProcessPayment Remote

{...private boolean process(){Connection con = dataSource.getConnection();...con.close();

}

Page 37: EJB Development and Support Services

EJB Development andSupport Services

Using Enterpise Beans

Page 38: EJB Development and Support Services

Entities• Model data and behavior

– Provide interface to data– Business rules that directly affect data– Relationships with other entities

// Use javax.persistence.PersistenceContext// annotation to get access to entities// using an EntityManager service that// references a persistence unit

@PersistenceContext(unitName=“titan”)private EntityManager manager;

...public void createCabin(Cabin cabin) {manager.persist(cabin);}

Page 39: EJB Development and Support Services

Session Beans• Model processes and tasks

– Functions of the business•Inappropriate for client application or entity beans

• Provide business logic• Control workflow// Lookup session beanTravelAgent tAgent = (TravelAgent)...

// Create a reservation tAgent.setCustomer(customer);tAgent.setRoomID(roomID);tAgent.setHotelID(hotelID);

Ticket ticket = tAgent.bookReserve(creditCard, price);

Page 40: EJB Development and Support Services

Session Beans• Stateful

– Maintain conversational state•State kept in memory•Dedicated to a single client

• Stateless– No conversational state

•Method calls are independent– Provide higher performance

•A few stateless beans can service many clients

Page 41: EJB Development and Support Services

EJB Development andSupport Services

Server Side Services

Page 42: EJB Development and Support Services

Resource Management• Instance Pooling

– Clients do not directly access EJB’s– Number of instances can be efficiently

managed and minimized– Reuse existing beans for different client

requests• Activation Mechanism

– Used for stateful session beans– Passivation

•Serialize bean’s state to storage – Activation

•Restore a stateful bean instance’s state

Page 43: EJB Development and Support Services

Concurrency• Multiple clients accessing the same bean

at the same time• Not supported by session beans• Entities represent shared data

– Java Persistence spec: persistence container protects shared data by making a copy of the entity bean on a per-transaction basis

– Defense against stale reads or simultaneous updates is vendor specific

– EJB prohibits synchronized keyword– EJB prohibits beans from creating

threads

Page 44: EJB Development and Support Services

Transactions• Set of tasks executed together

– Atomic•Reservation and Payment must both be successful

• Manage automatically– Declare transactional attribute

• Manage explicitly– Use javax.transaction.UserTransaction object

Page 45: EJB Development and Support Services

Persistence• Applies to Entities

– Java Persistence specification•Plain Old Java objects (POJO)•Can be created outside the scope of the EJB container

•Attached/Detached•Entity Manager

– Object-to-relational persistence•Map entity state to relational database tables and columns

Page 46: EJB Development and Support Services

Distributed Object Interoperability• Location Transparency

– CORBA IIOP– Support mandated in EJB 3.0

•RMI/IIOP•SOAP via JAX-RPC API•Programming model used by Java EJB

Client– Other protocols and clients can be

supported by servers•CORBA clients written in C++, Smalltalk,

Ada using EJB-to-CORBA mapping•SOAP clients written in Visual Basic.NET,

C#, Perl using EJB-to-SOAP mapping

Page 47: EJB Development and Support Services

Asynchronous Enterprise Messaging• Message-driven Beans (MDBs)• Route messages from JMS clients to

JMS-MDB• Reliable delivery

– Attempt redelivery on failure• Persisted messages• Transactional• EJBs can send messages

Page 48: EJB Development and Support Services

EJB Development andSupport ServicesTopics to be Covered:• EJB Design• Bean/Container Interaction• Java Naming and Directory Interface

(JNDI)• Using Enterprise Beans• Server Side Services