chapter 3: middleware services

172
Design of Distributed Software Chapter 3: Chapter 3: Middleware Middleware Services Services Overview of 10 important middleware services and examples in CORBA, RMI, JEE, Web Services and .NET (During the lesson, it will be indicated which parts are highly important and which are not important for the exam)

Upload: elvis-powers

Post on 30-Dec-2015

54 views

Category:

Documents


1 download

DESCRIPTION

Overview of 10 important middleware services and examples in CORBA, RMI, JEE, Web Services and .NET (During the lesson, it will be indicated which parts are highly important and which are not important for the exam). Chapter 3: Middleware Services. Overview. Naming Service - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 3: Middleware Services

Design of Distributed Software

Chapter 3: Chapter 3: Middleware ServicesMiddleware Services

Overview of 10 important middleware services and examples in CORBA, RMI, JEE, Web Services and .NET

(During the lesson, it will be indicated which parts are highly important and which are not important for the exam)

Page 2: Chapter 3: Middleware Services

Design of Distributed Software 2

OverviewOverview

Naming Service Event and Notification Service Messaging Service Persistence Service Transaction Service Activation Service Loadbalancing Service Session Tracking Security Service Dynamic Invocation Service

Page 3: Chapter 3: Middleware Services

Design of Distributed Software

3.1 Naming Service3.1 Naming Service

Page 4: Chapter 3: Middleware Services

Design of Distributed Software 4

Naming ServiceNaming Service

Definition Binding Service

Bind Object References to a textual name Operations:

bind / rebind : registration by server lookup / resolve : by client

1. Naming Service

Page 5: Chapter 3: Middleware Services

Design of Distributed Software 5

Java RMI : RegistryJava RMI : Registry RMI registry must run on every server computer in the

distributed system. maps names to remote object references. a name is represented as a string with format:

//computerName:port/objectName

class java.rmi.Naming public void bind(String name, Remote obj)

gives an exception when the name is already bound public void unbind(String name, Remote obj) public void rebind(String name, Remote obj)

when the name is already bound, the object reference is overwritten public Remote lookup(String name) public String[ ] list()

returns all names bound in the Registry

1. Naming Service

Page 6: Chapter 3: Middleware Services

Design of Distributed Software 6

JNDIJNDI Java Naming and Directory Interface

Distributed version of RMI registry applications based on Java technology can store and

retrieve named Java objects of any type JNDI provides methods for performing standard

directory operations, associating attributes with objects searching for objects using their attributes etc.

http://java.sun.com/products/jndi/reference/codesamples/index.html

http://java.sun.com/products/jndi/tutorial/

1. Naming Service

Page 7: Chapter 3: Middleware Services

Design of Distributed Software 7

CORBA Naming ServiceCORBA Naming Service

Registration of Object References Names are structured in a hierarchy

cfr directories in file system files and directories can be assigned a “Kind” id

client server

ab

Namingservice

1

2

3

1. Naming Service

Page 8: Chapter 3: Middleware Services

Design of Distributed Software 8

CORBA serverCORBA server

Java class with Main method Creates and initializes the ORB Creates an instance of Servant class Registers it to the ORB (through the connect

method) Gets a reference for the Naming Service Registers the server to the Naming Service Waits for incoming client requests

1. Naming Service

Page 9: Chapter 3: Middleware Services

Design of Distributed Software 9

CORBA Naming ServiceCORBA Naming Service NamingService implements an interface called

NamingContext rebind for servers to register the remote object

references of CORBA objects by name (e.g. rebind (path, Object))

resolve for clients to look them up by name.(e.g.Object = resolve(path))

The names are structured in a hierarchy, a path is an array of NameComponent (a struct with a

name in it) the path starts from an initial context provided by

CORBA Naming Service is available in all CORBA

implementations

1. Naming Service

Page 10: Chapter 3: Middleware Services

Design of Distributed Software 10

Example ShapeListServer Example ShapeListServer

import org.omg.CosNaming.*;import org.omg.CosNaming.NamingContextPackage.*;import org.omg.CORBA.*;public class ShapeListServer {

public static void main(String args[]) {try{

java.util.Properties props = System.getProperties(); ORB orb = ORB.init(args, props);

ShapeListServant shapeRef = new ShapeListServant(orb); orb.connect(shapeRef);

org.omg.CORBA.Object objRef =

orb.resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef);

NameComponent nc = new NameComponent("ShapeList", "");NameComponent path[] = {nc};ncRef.rebind(path, shapeRef);

orb.run();} catch (Exception e) { ... }

}}

1. Naming Service

Page 11: Chapter 3: Middleware Services

Design of Distributed Software 11

Example ShapeListClientExample ShapeListClient

import org.omg.CosNaming.*;import org.omg.CosNaming.NamingContextPackage.*;import org.omg.CORBA.*;public class ShapeListClient{

public static void main(String args[]) {try{

java.util.Properties props = System.getProperties(); ORB orb = ORB.init(args, props);

org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");

NamingContext ncRef = NamingContextHelper.narrow(objRef);NameComponent nc = new NameComponent("ShapeList", "");NameComponent path [] = { nc };ShapeList shapeListRef =

ShapeListHelper.narrow(ncRef.resolve(path));Shape[] sList = shapeListRef.allShapes();GraphicalObject g = sList[0].getAllState();

} catch(org.omg.CORBA.SystemException e) {...} }

1. Naming Service

Page 12: Chapter 3: Middleware Services

Design of Distributed Software 12

Advanced Example (1)Advanced Example (1)

NameComponent[] contextName= new NameComponent[1]; contextName[0] = new org.omg.CosNaming.NameComponent(); contextName[0].id = "CORBA_test"; contextName[0].kind = “ODS_course"; // Note on kind: The kind field is used to indicate the type

// of the object. This is to avoid conventions such as that used // by files (name.type -- e.g. test.ps = postscript etc.)

org.omg.CosNaming.NamingContext testContext; try { // Bind the context to root, and assign testContext to it: testContext = rootContext.bind_new_context(contextName); } catch(org.omg.CosNaming.NamingContextPackage.AlreadyBound ex) { // If the context already exists, this exception will be raised. // In this case, just resolve the name and assign testContext // to the object returned: org.omg.CORBA.Object tmpobj; tmpobj = rootContext.resolve(contextName); testContext = NamingContextHelper.narrow(tmpobj); if (testContext == null) { System.err.println("Failed to narrow naming context.");

return false;} }

1. Naming Service

Page 13: Chapter 3: Middleware Services

Design of Distributed Software 13

Advanced Example (2)Advanced Example (2)

// Bind the object (obj) to testContext, naming it Echo: org.omg.CosNaming.NameComponent[] objectName=new

org.omg.CosNaming.NameComponent[1]; objectName[0] = new org.omg.CosNaming.NameComponent(); objectName[0].id = "Echo"; objectName[0].kind = "Object";

// Bind obj with name Echo to the testContext: try {

testContext.bind(objectName,obj); } catch(org.omg.CosNaming.NamingContextPackage.AlreadyBound ex) { testContext.rebind(objectName,obj); } // Note: Using rebind() will overwrite any Object previously bound // to /CORBA_test.ATLANTIS_tests with obj. // Alternatively, bind() can be used, which will raise a // CosNaming::NamingContext::AlreadyBound exception if the name // supplied is already bound to an object.

1. Naming Service

Page 14: Chapter 3: Middleware Services

Design of Distributed Software 14

Running server and client with NSRunning server and client with NS Start orbd :

UNIX command shell : $ orbd -ORBInitialPort 1050 -ORBInitialHost nameserverhost &

MS-DOS system prompt : start orbd -ORBInitialPort 1050 -ORBInitialHost nameserverhost

Start the Echo server : UNIX command shell :

$ java echoServer -ORBInitialPort 1050 -ORBInitialHost nameserverhost &

MS-DOS system prompt :

start java echoServer -ORBInitialPort 1050 -ORBInitialHost nameserverhost Result: echoServer ready and waiting ...

Run the client application : $ java echoClient -ORBInitialPort 1050 -ORBInitialHost localhost ResuIt: I said, “Hello!“. The Object said, “Hello!"

1050 = port on which Naming Service listens

1. Naming Service

Page 15: Chapter 3: Middleware Services

Design of Distributed Software 15

CORBA Trading ServiceCORBA Trading Service

Trading Service: Comparable to Naming Service Allows objects to be located by attribute : directory

service Database: service types and attributes -> remote object

references Clients specify :

Constraints on the values of attributes Preferences for the order in which to receive matching offers

1. Naming Service

Page 16: Chapter 3: Middleware Services

Design of Distributed Software 16

Other Name ServicesOther Name Services

Web Services URIs are used to locate the web services DNS (Domain Name Service)

.Net No distributed directory, but a local directory on each

participating machine Based on Web Services

1. Naming Service

Page 17: Chapter 3: Middleware Services

Design of Distributed Software

3.2 Event and 3.2 Event and Notification ServiceNotification Service

Page 18: Chapter 3: Middleware Services

Design of Distributed Software 18

Events and NotificationsEvents and Notifications

data

Method 1Method 2Method 3

A

Client

Event or Notification

MethodCall

2. Event/Notification Service

Page 19: Chapter 3: Middleware Services

Design of Distributed Software 19

Publish - Subscribe paradigmPublish - Subscribe paradigm Object that generates events : publishes the type of

events it will make available

Objects that want to receive notifications: subscribe to the types that are of interest (or: register)

Event types : refer to different operations of object generating events

Objects that represent events = notifications

Asynchronous communication between publishers and the subscribers

2. Event/Notification Service

Page 20: Chapter 3: Middleware Services

Design of Distributed Software 20

Event typeEvent type

Each event has attributes: Name or identifier of generating object Operation Parameters Time Sequence Number

Subscribing = specify event types criterion about attribute values

2. Event/Notification Service

Page 21: Chapter 3: Middleware Services

Design of Distributed Software 21

Architecture for distributed event notificationArchitecture for distributed event notification

observer

Event service

observer

subscriber

subscriber

subscriber

object of interest

3.

object of interest

object of interest

1.

2. notification

notification

notification

notification

Notification : object that contains information about event

Observer : decouple the object of interest from its subscribers (forwarding, filtering, patterns of events, notification mailbox)

2. Event/Notification Service

Page 22: Chapter 3: Middleware Services

Design of Distributed Software 22

CORBA Event ServiceCORBA Event Service

Defines interfaces for: Suppliers Consumers

Push (by supplier to consumer) PushConsumer interface {push (...);} Consumer register their object references

Pull (by consumer from supplier) PullSupplier interface { pull (...); } Suppliers register their object references

2. Event/Notification Service

Page 23: Chapter 3: Middleware Services

Design of Distributed Software 23

Event Service (2)Event Service (2)

Event Channels Allow multiple suppliers to communicate with multiple

consumers Buffer between suppliers and consumers

EventChannel interface implemented by objects in event server

Chains of event channels

2. Event/Notification Service

Page 24: Chapter 3: Middleware Services

Design of Distributed Software 24

Notification ServiceNotification Service

Extends Event Service with filters Notifications have datatype ( <-> any ) Event Consumers may use filters

Specify events they are interested in Proxies forward notifications to consumers according to

constraints specified in filters Event Suppliers can discover the events the consumer

are interested in Event Consumers can discover a set of event types

(subscribe to new event) Configure properties of Event Channel

Reliability, priority of events, required ordering, policy for discarding stored events

Event type repository

2. Event/Notification Service

Page 25: Chapter 3: Middleware Services

Design of Distributed Software 25

Eventing in other technologiesEventing in other technologies

Java RMI / JEE write callbacks Java Message Service

Web Services WS Eventing : W3C draft defines a protocol for eventing http://www.w3.org/Submission/WS-Eventing/

.Net Framework support comparable to JEE

2. Event/Notification Service

Page 26: Chapter 3: Middleware Services

Design of Distributed Software

Intermezzo :Intermezzo :EJB : Enterprise Java BeansEJB : Enterprise Java Beans

I1. Architecture I2. Types of EJBs I3. Stateless Session BeansI4. Stateful Session Beans

Page 27: Chapter 3: Middleware Services

Design of Distributed Software 27

IntroductionIntroductionEJB components

have the remote capabilities of RMI or CORBA objects

are JavaBeans components : allow introspection of properties JavaBeans “design patterns” for component layout

(properties, accessors, modifiers, events, ...) architecture provides non-functional features

component life cycle management, transaction processing, security handling, persistence remotability timer state management resource pooling messaging

I1. Architecture

Page 28: Chapter 3: Middleware Services

Design of Distributed Software 28

IntroductionIntroduction

EJB-container

EJB

EJB

EJB

container hosted on application serverjava beans interactions mediated by containerinteractions :

- with other beans locally (same container)remotely (different container)

- with other JEE components (servlets, jsp, ...)- with client- with other resources (e.g. database)

I1. Architecture

Page 29: Chapter 3: Middleware Services

Design of Distributed Software 29

ArchitectureArchitecture

browser webserver

Application Serverap

ple

t

app

let

Database system

Web container

EJB container

WebserverClient

Servlet

JSP

EJBWeb container services• component life cycle management• handle communication with webserver HTTP <-> servlet• session tracking

EJB container services• component life cycle management• transaction service• security handling• resource pooling

JEE client

I1. Architecture

Page 30: Chapter 3: Middleware Services

Design of Distributed Software 30

Server side architectureServer side architecture

Servlet

JSP

EJB

Java EE container

Web container EJB container Persistence provider

ExternalResource

Entity

business logicpersistent

application data [POJO]

persistent application data

[RDBMS]

I1. Architecture

Page 31: Chapter 3: Middleware Services

Design of Distributed Software 31

Benefits (1)Benefits (1)

simplify the development of large, distributed applications. the EJB container provides system-level services to

enterprise beans, the bean developer can concentrate on solving

business problems. the EJB container--not the bean developer--is

responsible for system-level services such as transaction management and security authorization.

I1. Architecture

Page 32: Chapter 3: Middleware Services

Design of Distributed Software 32

Benefits (2)Benefits (2) the client developer can focus on the presentation

of the client because the beans--and not the clients--contain the

application's business logic, the clients are thinner (important for clients that run

on small devices) enterprise beans are portable/reusable components

the application assembler can build new applications from existing beans.

these applications can run on any compliant J2EE server.

I1. Architecture

Page 33: Chapter 3: Middleware Services

Design of Distributed Software 33

EJB ViewsEJB Views EJBs have two possible views:

The local view Used by local clients (only EJBs in the same container)

The remote view Used by remote clients (not limited to EJBs; can include

Servlets, etc.) Can also be used by clients in the same container

A bean can implement both local and remote views

I1. Architecture

EJB

localrem

ote EJB

Page 34: Chapter 3: Middleware Services

Design of Distributed Software 34

The Local ViewThe Local View

New since EJB 2.0 spec Parameters are passed by reference The client and the EJB must reside in the same

container The client itself must be an EJB

Much faster than remote view No network latency No marshalling/unmarshalling

No need to worry about remote exceptions

I1. Architecture

Page 35: Chapter 3: Middleware Services

Design of Distributed Software 35

The Local View (cont.)The Local View (cont.)

1. Client looks up a bean object - using Java Naming and Directory Interface (JNDI)- using Dependency Injection (DI)

2. Client finds EJB3. Client uses EJB business methods from the local interface

I1. Architecture

client(EJB)

InitialContext JNDI service

EJBLocalObject

BeanInstance

EJB container

Page 36: Chapter 3: Middleware Services

Design of Distributed Software 36

The Remote ViewThe Remote View Based on Java RMI

Uses remote interface, stub, and tie (skeleton) Works with RMI/IIOP (“RMI over IIOP”) Vendor-specific protocols are also possible

Parameters are passed by value All parameter and return-value types must be

serializable Provides location independence and flexibility API design consideration (method granularity) :

One method that does several related tasks is more effective than several smaller methods

I1. Architecture

Page 37: Chapter 3: Middleware Services

Design of Distributed Software 37

The Remote View (cont.)The Remote View (cont.)

Same 3 steps as before, but taken over the network:

I1. Architecture

client(EJB)

InitialContextJNDI service

client container

remote stub

EJBObjectBean

Instance

EJB container

remote tie

Page 38: Chapter 3: Middleware Services

Design of Distributed Software

Intermezzo Intermezzo EJB : Enterprise Java Beans EJB : Enterprise Java Beans

I1. Architecture I2. Types of EJBs I3. Stateless Session BeansI4. Stateful Session Beans

Page 39: Chapter 3: Middleware Services

Design of Distributed Software 39

Types of EJBsTypes of EJBsI2. Types of EJBs

EJBs

Session Beans EntitiesMessage Beans

- session related object- always associated to one single client at most- types stateful : “conversational state” stateless

- “real life” object- mostly associated to “row in database”- persistent- NEW since EJB3.0 [replace (very) complex EntityBeans]- NOT managed by EJB container

- asynchronous message handling- new since J2EE 1.3

synchronous asynchronous

Page 40: Chapter 3: Middleware Services

Design of Distributed Software 40

Session EJBsSession EJBs

A session bean instance is: A non-persistent object Implements some business logic

(“procedural component”) Runs on the server

Not shared among multiple clients

I2. Types of EJBs

Page 41: Chapter 3: Middleware Services

Design of Distributed Software 41

Stateful Session EJBsStateful Session EJBs

A stateful session bean maintains a state values of its instance variables also called : conversational state

The state is relevant only for a single client cannot be seen by other clients

The state is not persistent does not survive a server shutdown when the client removes the bean or terminates, the

session ends and the state disappears Canonical example: ShoppingCart

I2. Types of EJBs

Page 42: Chapter 3: Middleware Services

Design of Distributed Software 42

Stateless Session EJBsStateless Session EJBs

Conceptually, the same as stateful session EJBs

No state http-style request – reply interaction Can have fields, but they are not unique to any client

Basically, it’s an optimization trick: 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) Example: CurrencyConversionBean

I2. Types of EJBs

Page 43: Chapter 3: Middleware Services

Design of Distributed Software 43

EntitiesEntities

Object-oriented view of entities stored in persistent storage Normally, each entity represents a row in a relational

DB table Persistence code generated through ORM-tool

(Object-Relational Mapping, e.g. Hibernate, TopLink)

A single instance (on the server) can be accessed by multiple clients Unlike stateful session EJBs

Each instance must be uniquely identifiable by means of a primary key.

I2. Types of EJBs

Page 44: Chapter 3: Middleware Services

Design of Distributed Software 44

Message Driven Beans (MDBs)Message Driven Beans (MDBs) process messages asynchronously messages originate from JMS (Java Messaging Service)-compliant

system message can be sent by any source

other EJB other JEE component (e.g. web component) any other (legacy) component

indirectly accessed by clients no interface, use message instead

similar to stateless session bean all beans are equivalent (pooling !) – no client specific state no conversational state maintained can handle requests from multiple clients

I2. Types of EJBs

JMS queueMDBClient

Page 45: Chapter 3: Middleware Services

Design of Distributed Software 45

Bean packagingBean packaging

Bean contents deployment descriptor (XML) [deploytool] enterprise bean class (bytecode) [programmer] interfaces [IDE]

local/remote helper classes (utilities/exceptions/...) [programmer]

I2. Types of EJBs

EJB JAR-fileJEE-application

EJB JAR-file

WAR-fileEAR-file

deployable units toapplication server

Page 46: Chapter 3: Middleware Services

Design of Distributed Software 46

Deployment descriptorDeployment descriptorI2. Types of EJBs

-essentially contains meta-data of application/component- cumbersome to construct/maintain- alternative : Annotations

BUT : deployment descriptor can still override annotations

POJO JEEcomponent

Page 47: Chapter 3: Middleware Services

Design of Distributed Software 47

Naming ConventionsNaming ConventionsI2. Types of EJBs

syntax example

bean name <name>Bean ExampleBean

bean class <name>Bean ExampleBean

remote [component] interface <name>Remote ExampleRemote

local [component] interface <name>Local ExampleLocal

Page 48: Chapter 3: Middleware Services

Design of Distributed Software

IntermezzoIntermezzoEJB : Enterprise Java Beans EJB : Enterprise Java Beans

I1. Architecture I2. Types of EJBs I3. Stateless Session BeansI4. Stateful Session Beans

Page 49: Chapter 3: Middleware Services

Design of Distributed Software 49

Session Bean servicesSession Bean servicesI3. Stateless SB

• Thread safe and performant concurrency (techniques : pooling, session management,

passivation – activation)• Remoting• Exposure as Web Service• Transaction Management• Security Management• Timer services (scheduling)

Page 50: Chapter 3: Middleware Services

Design of Distributed Software 50

Session Bean in EJB2.0Session Bean in EJB2.0I3. Stateless SB

• implements the SessionBean + BeanInterface interface• is public• is NOT abstract or final• at least one ejbCreate method• implements required business methods (component i’face)• does NOT have a finalize method

public class MyBean implements javax.ejb.SessionBean,BeanInterface { private javax.ejb.SessionContext context; public void setSessionContext(javax.ejb.SessionContext aContext) { context = aContext; } // called when created public void ejbActivate() { } // called when activated public void ejbPassivate() {} // called when passivated public void ejbRemove() { } // called when removed from server public void ejbCreate() { } // called when created // business methods }

Page 51: Chapter 3: Middleware Services

Design of Distributed Software 51

Session Bean in EJB3.0Session Bean in EJB3.0I3. Stateless SB

@Statefulpublic class MyBean implements BeanInterface { @Resource SessionContext context;

@PostContruct// ... // called when created@PostActivate// ... // called when activated@PrePassivate

// ... // called when passivated@PreDestroy// ... // called when removed from server

// remote business method

// local business method }

• SIMPLE Plain Old Java Object• WITH annotations ...

Page 52: Chapter 3: Middleware Services

Design of Distributed Software 52

Session Bean in EJB3.0Session Bean in EJB3.0Programming RulesProgramming Rules

I3. Stateless SB

- Bean MUST implement at least one business interface- methods must NOT start with “ejb”- business methods are public, NOT final, NOT static- @Remote : arguments and return value

MUST implement Serializable

- Class MUST be concrete, NOT final - MUST have no-arg constructor

(can be default no-arg constructor) - can subclass other Session Bean, or POJO

BUT : mind “inheritance of annotations”- @Stateless, @Stateful -> NOT inherited- lifecycle call back method annotations -> inherited

Page 53: Chapter 3: Middleware Services

Design of Distributed Software 53

Session ContextSession Context During creation, the EJB instance is handed a

Session Context object An instance of javax.ejb.SessionContext

Typically set using DI@Resource SessionContext context;

The context object contains: Security-related information

getCallerPrinciple, isCallerInRole Transaction-related information and methods

getUserTransaction, get/setRollbackOnly EJB Object-related information

getEJBObject, getEJBLocalObject The former must be returned instead of this, whenever required

I3. Session EJBs

Page 54: Chapter 3: Middleware Services

Design of Distributed Software 54

Stateless Session Bean usageStateless Session Bean usageI3. Stateless SB

Client 1

Client 2

Client 3

Bean Pool

Instance 1

Instance 2

Client 4 EJB container

Page 55: Chapter 3: Middleware Services

Design of Distributed Software 55

Session Bean interfacesSession Bean interfacesI3. Stateless SB

SB1

SB2

EJB containerLocal interface ( @Local )

Remote interface ( @Remote )

Web Service interface ( @WebService )Stateless Session Beans ONLY !

Page 56: Chapter 3: Middleware Services

Design of Distributed Software 56

Session Bean interfacesSession Bean interfacesI3. Stateless SB

Interface can ONLY be annotated with 1 SB interface typeNOT allowed :

@WebService@Remotepublic interface MyInterface {

public int f(int i);}

Allowed :public interface MyInterface {

public int f(int i);}@Remotepublic MyRemoteInterface extends MyInterface {}@WebServicepublic MyWSInterface extends MyInterface {}

Page 57: Chapter 3: Middleware Services

Design of Distributed Software 57

Example : a random beanExample : a random beanI3. Stateless SB

• business methods• random() : give a random int number between 0 and 10• random(int n) : idem between 0 and n

package random;import javax.ejb.Remote;

@Remotepublic interface RandomRemote { public int random(); public int random(int n);}

RandomRemote.java

Page 58: Chapter 3: Middleware Services

Design of Distributed Software 58

Coding the RandomBeanCoding the RandomBeanI3. Stateless SB

package random;import javax.ejb.Stateless;

@Statelesspublic class RandomBean implements random.RandomRemote { public RandomBean() { } public int random() { return random(10); } public int random(int n) { return (int)(Math.random()*n); }}

RandomBean.java

Page 59: Chapter 3: Middleware Services

Design of Distributed Software 61

EJB-clientsEJB-clientsI3. Stateless SB

different types of clients-container clients (JEE components) -> support !

- app client (client side component)- other EJB (same container or not)- web component (JSP/Servlet) (other container)

-[non-container clients (standalone)]

Steps :1. Client gets reference to EJB (JNDI or not)2. Invocation of business methods on session bean3. Client calls remove-method (stateful session beans only)

Page 60: Chapter 3: Middleware Services

Design of Distributed Software 64

Coding the AppClientCoding the AppClientI2. Session Beans

package randomappclient;

import javax.ejb.EJB;import random.*;public class Main { @EJB public static RandomRemote r; public static void main(String[] args) { System.out.println("Starting appclient ..."); System.out.println(r.random(10000)); } }

Main.java

INJECTION ONLY DONE FOR - statics- in class Main

Page 61: Chapter 3: Middleware Services

Design of Distributed Software 66

Client 2 : Standalone Application ClientClient 2 : Standalone Application ClientI3. Stateless SB

1. Retrieve InitialContextContext ctx = new InitialContext();

2. Perform explicit JNDI lookup

(MyRemote) ejbRef=(MyRemote)ctx.lookup(“<BeanName>”)

3. Invoke business methods on beanejbREF.method1(par1);ejbREF.method2();// ...

typical client code sequence

Application client separately from enterprise application

USE mappedName (global JNDI names !)

Page 62: Chapter 3: Middleware Services

Design of Distributed Software 68

Example : Random BeanExample : Random BeanI3. Stateless SB

@Stateless(mappedName="Random")public class RandomBean implements random.RandomRemote { public RandomBean() { } public int random() { return random(10); } public int random(int n) { return (int)(Math.random()*n); }}

package randomappclientjndi;import javax.ejb.EJB;import javax.naming.*;import random.RandomRemote;public class Main { public Main() {} public static void main(String[] args) throws Exception { System.out.println("Starting appclient ..."); Context ctx = new InitialContext(); RandomRemote r=(RandomRemote)ctx.lookup("Random"); for(int i=0;i<10;i++) System.out.println(r.random(10000)); }}

Application client

Random Bean

Page 63: Chapter 3: Middleware Services

Design of Distributed Software 70

Client 3 : Web ClientClient 3 : Web ClientI3. Stateless SB

Create jsp or servlet-> WebModule -> New -> JSP or Servlet

Compile web resourceAdd to war (IDE or deploytool)Deploy applicationSet context root for web application (default index.jsp)Browse to indicated URL

(e.g. http://localhost:8080/RandomApp-war/ )

Page 64: Chapter 3: Middleware Services

Design of Distributed Software 71

Client 3 : Web ClientClient 3 : Web ClientI3. Stateless SB

JSP client

<%@page contentType="text/html"%><%@page pageEncoding="UTF-8"%><%@ page import="random.*, javax.ejb.*, java.math.*, javax.naming.*, java.rmi.RemoteException" %>

<%! private RandomRemote bean = null; public void jspInit() { try { InitialContext ic = new InitialContext(); bean=(RandomRemote)ic.lookup(RandomRemote.class.getName()); } catch (Exception ex) { System.out.println("Exception caught : "+ ex.getMessage()); } } public void jspDestroy() { bean = null; }%>

index.jsp

or “Random”

Page 65: Chapter 3: Middleware Services

Design of Distributed Software 72

Client 3 : Web ClientClient 3 : Web ClientI3. Stateless SB

<html> <head><title>Random Values</title></head><body bgcolor="white"><h1><b><center>Random Values</center></b></h1><hr><p>Enter upperbound:</p><form method="get"><input type="text" name="upper" size="25"><br><p><input type="submit" value="Submit"><input type="reset" value="Reset"></form><% String upper = request.getParameter("upper"); if ( upper != null ) { int n = Integer.parseInt(upper);%> <p> Random value smaller than <%= upper %> : <%= bean.random(n) %> <% }%></body></html> index.jsp

Page 66: Chapter 3: Middleware Services

Design of Distributed Software 73

Client 3 : Web ClientClient 3 : Web ClientI3. Stateless SB

Servlet client

private random.RandomRemote lookupRandomBean () {@EJBprivate RandomRemote randomBean;protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet RandomServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("A random value < 100 : "+randomBean.random(100)); out.println("</body>"); out.println("</html>"); out.close(); }

// Servlet methods }

automatically generated DI for EJB lookup(right-click in Servlet body-> Enterprise Resources

-> Call Enterprise Bean-> Select the bean to look up)RandomServlet.java

Page 67: Chapter 3: Middleware Services

Design of Distributed Software

EJB : EJB : Enterprise Java Beans IEnterprise Java Beans I

I1. Architecture I2. Types of EJBs I3. Stateless Session BeansI4. Stateful Session Beans

Page 68: Chapter 3: Middleware Services

Design of Distributed Software 78

Stateful Session Bean usageStateful Session Bean usageI4. Stateful SB

Client 1

Client 2

Client 3

Instance 1

Client 4

EJB container

Instance 2

Instance 3

Instance 4

State 1

State 2

State 3

State 4

typical usage : multi-step workflows

Page 69: Chapter 3: Middleware Services

Design of Distributed Software 81

Stateful Session BeansStateful Session BeansProgramming RulesProgramming Rules

I4. Stateful SB

Additional Rules

- @Stateful (instead of @Stateless)identical (except for name) als @Stateless

- instance variables must be primitive/Serializable- @Remove for “friendliness”

- provide additional methods (wrt stateless beans) : @PostActivate @PrePassivate

Page 70: Chapter 3: Middleware Services

Design of Distributed Software 82

Simple Example : a random beanSimple Example : a random bean

• business methods• random() : give a random int number between 0 and 10• random(int n) : idem between 0 and n• getSum() : get sum of all values produced in this session• getUser() : get user of this session • setUser() : set user of this session

I4. Stateful SB

Page 71: Chapter 3: Middleware Services

Design of Distributed Software 83

Random State Bean : remote interfaceRandom State Bean : remote interface

package randomstate;

import javax.ejb.Remote;import javax.ejb.Remove;

@Remotepublic interface RandomStateRemote { int random(int n); int random(); void setUser(String name); String getUser(); int getSum(); @Remove void remove();}

RandomStateRemote.java

I4. Stateful SB

Page 72: Chapter 3: Middleware Services

Design of Distributed Software 84

Random State Bean : Bean ClassRandom State Bean : Bean Classpackage randomstate;import javax.ejb.Remove;import javax.ejb.Stateful;

@Statefulpublic class RandomStateBean implements RandomStateRemote { private String userName; private int sum=0; public RandomStateBean() {} public int random(int n) { int r=(int)(n*Math.random()); sum+=r; return r; } public int random() {return random(10);} public void setUser(String name) {userName=name;} public String getUser() {return userName;} public int getSum() {return sum;} @Remove public void remove() {userName=null;sum=0;}}

RandomStateBean.java

I4. Stateful SB

session related state variables

friendly removal

Page 73: Chapter 3: Middleware Services

Design of Distributed Software 85

Random State Bean : multisession clientRandom State Bean : multisession client

package twosessionclient;import javax.ejb.EJB;import randomstate.RandomStateRemote;public class Main { @EJB private static RandomStateRemote george; @EJB private static RandomStateRemote john; public Main() {} public static void main(String[] args) { george.setUser("George"); john.setUser("John"); for(int i=0;i<5;i++) System.out.println("1:"+george.random(10)+"\t2:"+john.random(100)); System.out.println(george.getUser()+" : "+george.getSum()); System.out.println(john.getUser()+" : "+john.getSum()); george.remove(); john.remove(); }}

Main.java

I4. Stateful SB

1:5 2:81:0 2:251:6 2:431:3 2:341:1 2:1George:15John:111

sample run

Page 74: Chapter 3: Middleware Services

Design of Distributed Software 86

J2EE canonical example : CartBeanJ2EE canonical example : CartBean

package cart;import java.util.ArrayList;import javax.ejb.Remove;import javax.ejb.Stateful;@Statefulpublic class CartBean implements CartRemote { private String customerName; private String customerId; private ArrayList<Book> contents=new ArrayList<Book>();

public CartBean() {} public void initUser(String person) throws CreateException { initUser(person,"0"); } public void initUser(String person, String id) throws CreateException { if(person==null) throw new CreateException("Null person not allowed."); else customerName=person; customerId=id; }

I4. Stateful SB

CartBean.java

Page 75: Chapter 3: Middleware Services

Design of Distributed Software 87

J2EE canonical example : CartBeanJ2EE canonical example : CartBean

public void addBook(Book b) { contents.add(b); } public void removeBook(Book b) throws BookException { if(contents.contains(b)) contents.remove(b); else throw new BookException("Book not in shopping cart !"); } public ArrayList<Book> getContents() { return contents; } @Remove public void remove() { contents=null; customerName=null; customerId=null; }}

I4. Stateful SB

CartBean.java

Page 76: Chapter 3: Middleware Services

Design of Distributed Software 88

Cart Bean : Remote InterfaceCart Bean : Remote Interfacepackage cart;

import javax.ejb.Remote;import javax.ejb.Remove;

@Remotepublic interface CartRemote { void initUser(String person) throws CreateException; void initUser(String person, String id) throws CreateException; void addBook(Book b); void removeBook(Book b) throws BookException; java.util.ArrayList<cart.Book> getContents(); @Remove void remove(); }

I4. Stateful SB

CartRemote.java

Page 77: Chapter 3: Middleware Services

Design of Distributed Software 89

Cart Bean : Utility ClassesCart Bean : Utility Classespackage cart;

import java.io.Serializable;public class Book implements Serializable { private String title; private String author; public Book(String t,String a) {

title=t;author=a; } public String toString() { return "<"+title+","+author+">"; } public boolean equals(Object o) { if(o instanceof Book) { Book a=(Book)o; return (((a.author).equals(author))&&((a.title).equals(title))); } else return false; }}

I4. Stateful SB

Book.java

MUST be Serializable !

Page 78: Chapter 3: Middleware Services

Design of Distributed Software 90

Cart Bean : Utility ClassesCart Bean : Utility Classespackage cart;

import java.rmi.RemoteException;

public class BookException extends RemoteException{ public BookException(String message) { super(message); } }

I4. Stateful SB

BookException.java

MUST be RemoteException !

package cart;

import java.rmi.RemoteException;

public class CreateException extends RemoteException{

public CreateException(String message) { super(message); } }

CreatekException.java

Page 79: Chapter 3: Middleware Services

Design of Distributed Software 91

CartBean ClientCartBean Clientpackage shoppingcartclient;import cart.*;import java.util.ArrayList;import javax.ejb.EJB;public class Main { @EJB private static CartRemote shoppingCart; public Main() {}

public static void main(String[] args) { try { shoppingCart.initUser("MyFavouriteUser"); } catch(Exception e) {System.err.print(e);} shoppingCart.addBook(new Book("The Martian Chronicles","Jane Austin")); shoppingCart.addBook(new Book("2001 A Space Odyssey","George Lewanski")); shoppingCart.addBook(new Book("The Left Hand of Darkness","Unknown")); ArrayList<Book> bookList = new ArrayList<Book>(); bookList = shoppingCart.getContents(); System.out.println(bookList); try { shoppingCart.removeBook(new Book("Alice in Wonderland","Lewis Carrol")); shoppingCart.remove(); } catch(Exception e) {System.out.println(e);} } }

I4. Stateful SB

Main.java

Page 80: Chapter 3: Middleware Services

Design of Distributed Software

3. Messaging Service3. Messaging Service

1. Messaging concepts2. Message Driven Beans

Page 81: Chapter 3: Middleware Services

Design of Distributed Software 93

Messaging architectureMessaging architecture3.1 Messaging concepts

supports communication between components/subsystems• loosely coupled (no interface to conform to)• asynchronous

-> can be used to couple “fast” and “slow” subsystems

• JMS also supports synchronous communication (with timeout)

message sender= producer

send message

Message Oriented Middleware [MoM]= reliable man-in-the-middle

acknowledgest

ore

retr

ieve

message receiver= consumer

send message“deliver”

acknowledge

Page 82: Chapter 3: Middleware Services

Design of Distributed Software 94

Messaging modelsMessaging models3.1 Messaging concepts

point-to-point (PTP)

publish-subscribe (Topic)

producer Queue

consumer

receiver delivered to 1 online consumer with correct destination ID

producer Topic

consumer

delivered to all consumers subscribed to the topic

consumer

consumer

Page 83: Chapter 3: Middleware Services

Design of Distributed Software 95

JMS-basicsJMS-basics3.1 Messaging concepts

“Java Messaging Service”= messaging API supported by JEE- resembles JDBC API

JMS message

message headers

message properties

message body

common set of (key,value) pairs- JMSTimestamp- JMSCorrelationID- JMSReplyTo- JMSMessageID

application defined (key,value) pairs[String, Object, primitive no char]

message payload -ObjectMessage-BytesMessage-MapMessage-StreamMessage-TextMessage

Page 84: Chapter 3: Middleware Services

Design of Distributed Software 96

JMS programming modelJMS programming model3.1 Messaging concepts

Connection Factory

Connection

long-lived logical relation client-provider

expensive to createresource hungry

Sessionshort-lived logical relationinexpensive to createcheap !

Destination

creates

creates

createscreates

message

creates

Producer Consumer

Destination

Page 85: Chapter 3: Middleware Services

Design of Distributed Software 97

JMS message delivery modelJMS message delivery model3.1 Messaging concepts

Designed for reliable message communication :

•Use of acknowledgements•DeliveryMode can be specified to indicate message persistence•Priority levels can be specified•Support for transactions (default : auto-commit)

Page 86: Chapter 3: Middleware Services

Design of Distributed Software

3. Messaging Service3. Messaging Service

1. Messaging concepts2. Message Driven Beans

Page 87: Chapter 3: Middleware Services

Design of Distributed Software 99

Message Driven BeansMessage Driven Beans3.2 MDBs

client producer 1

MDBean Pool

Instance 1

Instance 2

EJB containerclient producer 2

client producer 3

Services offered- safe multithreading and pooling- simplified coding (wrt native JMS)

messagedestination

Instance 3

Instance 4

Page 88: Chapter 3: Middleware Services

Design of Distributed Software 100

Message Driven BeansMessage Driven BeansProgramming RulesProgramming Rules

3.2 MDBs

Class- must implement message listener interface

(can be declared by annotation)- concrete (not absract), non-final- POJO, not subclass of MDB- public

Methods-MUST have no-arg constructor- no finalizer (use @PreDestroy)- MUST have message listener methods

(public, NOT static, NOT final)- NO runtime exceptions (terminates MDB)

Page 89: Chapter 3: Middleware Services

Design of Distributed Software 101

@MessageDriven : Listener@MessageDriven : Listener

@MessageDriven(name=“MyBean”,messageListenerInterface=“javax.jms.MessageListener”)public class MyBeanMDB { ... }

OR

@MessageDriven(name=“MyBean”)public class MyBeanMDB implements MessageListener { ... }

OR use deployment descriptor

3.2 MDBs

Page 90: Chapter 3: Middleware Services

Design of Distributed Software 102

@MessageDriven : @MessageDriven : ActivationConfigsActivationConfigs

allows for system-specific configuration

public @interface ActgivationConfigProperty {String propertyName();String propertyValue();

}

typical usage@MessageDriven(name=“MyBean”,activationConfig= {@ActivationConfigProperty(propertyName=“destinationType”,

propertyValue=“javax.jms.Queue”),@ActivationConfigProperty(propertyName=“connectionFactoryJndiName”,

propertyValue=“jms/QueueConnectionFactory”),@ActivationConfigProperty(propertyName=“destinationName”,

propertyValue=“jms/MyQueue”;})

Bean listens to Queue

find Factory to connect to Queue

find Queue to listen to

3.2 MDBs

Page 91: Chapter 3: Middleware Services

Design of Distributed Software 103

@MessageDriven : @MessageDriven : ActivationConfigsActivationConfigs

acknowledgeModeHow should the session acknowledge ?AUTO_ACKNOWLEDGE -> rigorous acknowledgement of each message (default)DUPS_OK_ACKNOWLEDGE-> lazy acknowledgement (once in case of duplicate messages)

subscriptionDurability (for Topics)How to handle offline consumers ?NonDurable-> offline consumers do not get the message (default)Durable-> offline consumers get the message as soon as they get connected

3.2 MDBs

Page 92: Chapter 3: Middleware Services

Design of Distributed Software 104

@MessageDriven : @MessageDriven : ActivationConfigsActivationConfigs

messageSelectorconsumer side filtering of messages<expression>

operandsliterals (Strings, numeric values, booleans, ...)Identifiers -> message property name or header field

operatorscomparison

=, >, >=, <=, <>Null comparison : IS NULL, IS NOT NULLtrue/false comparison : IS [NOT] TRUE,

IS [NOT] FALSElogical : NOT, AND, OR

3.2 MDBs

Page 93: Chapter 3: Middleware Services

Design of Distributed Software 105

MDB lifecycleMDB lifecycle

Does NotExist

Ready

0. newInstance()1. Dependency Injection2. @PostConstruct

@PreDestroy

onMessage

@PostConstruct -> setup session with Queue/Topic@PreDestroy -> Release session

3.2 MDBs

Page 94: Chapter 3: Middleware Services

Design of Distributed Software 106

Example: Processing ShipRequestsExample: Processing ShipRequests

NetBeans1. Create EnterpriseProject with Application Client

[JMessageProject]2. Create Message Driven Bean

Right click on JMessageProject-ejb node-> New -> Message Driven BeanEJB-name : ShipRequestMDBpackage : ejbDestination Type : Queue-> Finish

3. Program onMessage() -method

3.2 MDBs

Page 95: Chapter 3: Middleware Services

Design of Distributed Software 107

Example: Processing ShipRequestsExample: Processing ShipRequestspackage ejb;

import javax.ejb.ActivationConfigProperty;import javax.ejb.MessageDriven;import javax.jms.Message;import javax.jms.MessageListener;@MessageDriven(mappedName = "jms/ShipRequestMDB", activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode",

propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType",

propertyValue = "javax.jms.Queue") })public class ShipRequestMDB implements MessageListener { /** Creates a new instance of ShipRequestMDB */ public ShipRequestMDB() { }

public void onMessage(Message message) { } }

ShipRequestMDB.java

IDE-generated

JNDI mapped name

listens to JMS messages

3.2 MDBs

Page 96: Chapter 3: Middleware Services

Design of Distributed Software 108

Example: Processing ShipRequestsExample: Processing ShipRequestspackage ejb;import javax.ejb.ActivationConfigProperty;import javax.ejb.MessageDriven;import javax.jms.*;import util.ShipRequest;@MessageDriven(mappedName = "jms/ShipRequestMDB", activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })public class ShipRequestMDB implements MessageListener { /** Creates a new instance of ShipRequestMDB */ public ShipRequestMDB() { }

public void onMessage(Message message) { try { ObjectMessage oMessage=(ObjectMessage)message; ShipRequest sRequest=(ShipRequest)oMessage.getObject(); processShipRequest(sRequest); } catch(JMSException e) { System.err.println(e); e.printStackTrace(System.err); } } private void processShipRequest(ShipRequest s) { System.out.println(s); }}

ShipRequestMDB.java

with onMessage ...

3.2 MDBs

Page 97: Chapter 3: Middleware Services

Design of Distributed Software 109

Example: Utility ClassExample: Utility Classpackage util;

import java.io.Serializable;

public class ShipRequest implements Serializable { protected String item; protected String dest; /** Creates a new instance of ShipRequest */ public ShipRequest(String i,String d) { item=i; dest=d; } public String toString() { return "Send item : <"+item+"> to destination : "+dest+"."; }}

ShipRequest.java

must be serializable

3.2 MDBs

Page 98: Chapter 3: Middleware Services

Design of Distributed Software 110

Example : Sending messagesExample : Sending messages[from appclient][from appclient]

NetBeans1. Open Application Client project

[JMessageProject-app-client]2. Connect to Message Driven Bean

Right click in main() -method-> Enterprise Resources-> send JMS message

Project : JMessageProject-ejbDestination: ShipRequestMDBSelect : Generate Inline Lookup Code

3. Copy util-package (!)4. Code application logic

3.2 MDBs

Page 99: Chapter 3: Middleware Services

Design of Distributed Software 111

Example : Sending messagesExample : Sending messages[from appclient][from appclient]

package jmessageproject;

import javax.annotation.Resource;import javax.jms.*;import javax.naming.NamingException;public class Main { @Resource(mappedName = "jms/ShipRequestMDBFactory") private static ConnectionFactory shipRequestMDBFactory; @Resource(mappedName = "jms/ShipRequestMDB") private static Queue shipRequestMDB; public Main() { } public static void main(String[] args) { // TODO code application logic here } private Message createJMSMessageForShipRequestMDB(Session session, Object messageData)

throws JMSException { // TODO create and populate message to send // javax.jms.TextMessage tm = session.createTextMessage(); // tm.setText(messageData.toString()); // return tm; } // ...}

Main.java

IDE-generated

inject resources : administrated JMS objects

Convenience templatemethod

3.2 MDBs

Page 100: Chapter 3: Middleware Services

Design of Distributed Software 112

Example : Sending messagesExample : Sending messages[from appclient][from appclient]

private void sendJMSMessageToShipRequestMDB(Object messageData) throws NamingException, JMSException {

Connection connection = null; Session session = null; try { connection = shipRequestMDBFactory.createConnection(); session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(shipRequestMDB); messageProducer.send(createJMSMessageForShipRequestMDB(session, messageData)); } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } } }

Main.java

IDE-generated

Convenience templatemethod

3.2 MDBs

Page 101: Chapter 3: Middleware Services

Design of Distributed Software 113

Example : Sending messagesExample : Sending messages[from appclient][from appclient]

package jmessageproject;import javax.annotation.Resource;import javax.jms.*import javax.naming.NamingException;import util.ShipRequest;public class Main { @Resource(mappedName = "jms/ShipRequestMDBFactory") private static ConnectionFactory shipRequestMDBFactory; @Resource(mappedName = "jms/ShipRequestMDB") private static Queue shipRequestMDB; public Main() {}

public static void main(String[] args) throws Exception { ShipRequest r=new ShipRequest("Book ","Sunset Boulevard"); try { sendJMSMessageToShipRequestMDB(r); }catch(NamingException ne) { System.err.println(ne); }catch(JMSException je) { System.err.println(je); } }

// ...}

Main.java

Modified ...

3.2 MDBs

Page 102: Chapter 3: Middleware Services

Design of Distributed Software 114

Example : Sending messagesExample : Sending messages[from appclient][from appclient]

private static Message createJMSMessageForShipRequestMDB(Session session, ShipRequest mData ) throws JMSException {

ObjectMessage oMessage=session.createObjectMessage(mData); return oMessage; }

private static void sendJMSMessageToShipRequestMDB( ShipRequest mData ) throws NamingException, JMSException {

Connection connection = null; Session session = null; try { connection = shipRequestMDBFactory.createConnection(); session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(shipRequestMDB);

messageProducer.send(createJMSMessageForShipRequestMDB(session, mData)); } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } } } Main.java

Modified ...

3.2 MDBs

Page 103: Chapter 3: Middleware Services

Design of Distributed Software 115

Sending back info to the clientSending back info to the client

How to send JMS message from bean -> client ?-> ConnectionFactory and Destination to be configured by admin-> deployment descriptor contains info for container to set up-> resources can be injected by container

appclient container ONLY injects:- into Main –class- private static attributes

Set up administrated resources for reply (MDB -> appclient)ShipReplyConnectionFactoryShipReplyQueue

3.2 MDBs

Page 104: Chapter 3: Middleware Services

Design of Distributed Software 116

Configuring administrated objectsConfiguring administrated objects

NetBeans1. Select resource type

File -> New File ...Select ejb-project nodeCategories -> Sun ResourcesFile Types -> JMS Resource-> Next

2. Configure JMS resource JNDIname : jms/<name>description : Free text

Select JMS-resource type-> NextEnter properties (if needed)

Name : JNDIname, without prefix-> Finish

[JMessageProject-ejb]

[jms/ShipReplyConnectionFactory][jms/ShipReplyQueue]

[jms.ConnectionFactory][jms.Queue]

[][ShipReplyQueue]

3.2 MDBs

Page 105: Chapter 3: Middleware Services

Design of Distributed Software 117

MDB code with replyMDB code with replypackage ejb;

import javax.annotation.Resource;import javax.ejb.ActivationConfigProperty;import javax.ejb.MessageDriven;import javax.jms.*;import javax.naming.NamingException;import util.ShipRequest;

@MessageDriven(mappedName = "jms/ShipRequestMDB", activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode",

propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType",

propertyValue = "javax.jms.Queue") })public class ShipRequestMDB implements MessageListener { @Resource(mappedName="jms/ShipReplyConnectionFactory") private ConnectionFactory shipReplyCF; @Resource(mappedName="jms/ShipReplyQueue") private Destination shipReplyQueue; public ShipRequestMDB() {}

ShipRequestMDB.java

3.2 MDBs

Page 106: Chapter 3: Middleware Services

Design of Distributed Software 118

MDB code with replyMDB code with reply

public void onMessage(Message message) { try { ObjectMessage oMessage=(ObjectMessage)message; ShipRequest sRequest=(ShipRequest)oMessage.getObject(); processShipRequest(sRequest); } catch(JMSException e) { System.err.println(e); e.printStackTrace(System.err); }}private void processShipRequest(ShipRequest s) { System.out.println("----------------------------->"+s); try { sendJMSMessageToShipReplyQueue(s); }catch(Exception e) { System.err.println(e); }}

ShipRequestMDB.java

3.2 MDBs

Page 107: Chapter 3: Middleware Services

Design of Distributed Software 119

MDB code with replyMDB code with reply private Message createJMSMessageForShipRequestMDB(Session session,ShipRequest mData)

throws JMSException { ObjectMessage oMessage=session.createObjectMessage(mData); return oMessage; }

private void sendJMSMessageToShipReplyQueue(ShipRequest mData) throws NamingException, JMSException {

Connection connection=null; Session session=null; try { connection = shipReplyCF.createConnection(); session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(shipReplyQueue); messageProducer.send(createJMSMessageForShipRequestMDB(session, mData)); } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }}

ShipRequestMDB.java

3.2 MDBs

Page 108: Chapter 3: Middleware Services

Design of Distributed Software 120

Client code with replyClient code with replypackage jmessageproject;

import javax.annotation.Resource;import javax.jms.*;import javax.naming.NamingException;import util.ShipRequest;

public class Main {

@Resource(mappedName = "jms/ShipRequestMDBFactory") private static ConnectionFactory shipRequestMDBFactory;

@Resource(mappedName = "jms/ShipRequestMDB") private static Queue shipRequestMDB; @Resource(mappedName="jms/ShipReplyConnectionFactory") private static ConnectionFactory shipReplyCF; @Resource(mappedName="jms/ShipReplyQueue") private static Queue shipReplyQueue; private static ReplyListener r=null;

Main.java

Sending

Listener

Receiving

3.2 MDBs

Page 109: Chapter 3: Middleware Services

Design of Distributed Software 121

Client code with replyClient code with reply

public Main() {} public static ConnectionFactory getFactory() {return shipReplyCF;} public static Queue getQueue() {return shipReplyQueue;} public static void main(String[] args) throws Exception { r=new ReplyListener(); try { r.init(); } catch(Exception e) { System.err.println(e); } ShipRequest r=new ShipRequest("Book ","Sunset Boulevard"); try { sendJMSMessageToShipRequestMDB(r); }catch(NamingException ne) { System.err.println(ne); }catch(JMSException je) { System.err.println(je); } }

Main.java

Awkward, but needed ...

3.2 MDBs

Page 110: Chapter 3: Middleware Services

Design of Distributed Software 122

Client code with replyClient code with reply

private static Message createJMSMessageForShipRequestMDB(Session session,ShipRequest mData) throws JMSException {

ObjectMessage oMessage=session.createObjectMessage(mData); return oMessage; }

private static void sendJMSMessageToShipRequestMDB(ShipRequest mData) throws NamingException, JMSException {

Connection connection=null; Session session=null; try { connection = shipRequestMDBFactory.createConnection(); session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(shipRequestMDB); messageProducer.send(createJMSMessageForShipRequestMDB(session, mData)); } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }}

Main.java

3.2 MDBs

Page 111: Chapter 3: Middleware Services

Design of Distributed Software 123

Client code with replyClient code with reply

class ReplyListener implements MessageListener { Connection connection=null; Session session=null; public void init() throws Exception { try { ConnectionFactory shipReplyCF=Main.getFactory(); Queue shipReplyQueue=Main.getQueue(); connection = shipReplyCF.createConnection(); session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(shipReplyQueue); messageConsumer.setMessageListener(this); connection.start();

} public void onMessage(Message m) { System.out.println("Received !!!!");

// code to close session/connection : if(message.equals(stop)) { // ... } }} Main.java

Find admin resources

register listener

start listening

3.2 MDBs

Page 112: Chapter 3: Middleware Services

Design of Distributed Software

3.4 Persistence 3.4 Persistence ServiceService

1. Java 5 Entities2. (Java 1.4 Entity Beans) 3. EJB Design Patterns

Page 113: Chapter 3: Middleware Services

Design of Distributed Software 125

JEE ArchitectureJEE Architecture

browser webserver

Application Serverap

ple

t

app

let

Database system

Web container

EJB container

WebserverClient

Servlet

JSP

EJB

4.1 Entities

JEE client

Focus of this section:- Persistence

- Design Patterns

Page 114: Chapter 3: Middleware Services

Design of Distributed Software 126

IntroductionIntroductionEntity = persistent object persistent state realised through persistent fields/properties object/relational annotations used to map to relational data in data

store

Entity class = any Java class but annotated with @Entity public/protected no-arg constructor not final class, no persistent final fields, no final methods if passed by value, must implement Serializable persistent instance variables NOT public

Field is persistent, unless annotated @Transient

Primary key annotated with

- simple primary key @Id

- composite primary key @EmbeddedId, @IdClass

4.1 Entities

Page 115: Chapter 3: Middleware Services

Design of Distributed Software 127

Primary KeyPrimary KeyPrimary Key class must be public properties public public default constructor must implements hashCode() and equals() must be Serializable composite primary key : related to

- multiple fields/properties of the entity class

- embeddable class

Same names of fields/properties as in entity class

4.1 Entities

Page 116: Chapter 3: Middleware Services

Design of Distributed Software 128

Managing EntitiesManaging EntitiesEntityManager- find entities- query entities- life cycle funtions on entities (create, remove, persist)

PersistentContext associated to data store associated to its own EntityManager

Container Managed : changes in PersistentContext automatically propagated by container EntityManager obtained by @PersistenceContext annotation

(through injection)@PersistenceContextEntityManager theManager;

4.1 Entities

Page 117: Chapter 3: Middleware Services

Design of Distributed Software 129

Building Java 5 Applications with Entities Building Java 5 Applications with Entities

Entity objects = simple Java classes no longer need to be placed in an EJB module no longer need to be packaged in an EAR file (both cfr Java 1.4 Entity Beans) entity classes can be created directly inside a web

application

Two options: Option 1 : Start with Entity code

Generate DB tables, columns and DB sync code based on attributes of entities

Option 2 : Start with DB structure (tables, columns)Generate Entity code and DB sync code

See next slides

4.1 Entities

Page 118: Chapter 3: Middleware Services

Design of Distributed Software 130

Building Java 5 Applications with EntitiesBuilding Java 5 Applications with Entities

Option 1: Start with Entity code

Example Netbeans 5.5 IDE Choose File > New Project (Ctrl-Shift-N). Select Web Application

from the Web category and click Next. Name the project, set the server to the Sun Java System

Application Server, set the Java EE Version to Java EE 5, and click Next.

Select the JavaServer Faces checkbox and click Finish.

Next Steps: Creating a Persistence Unit Creating the Entity Classes Creating a Web Interface Running the Project

4.1 Entities

Page 119: Chapter 3: Middleware Services

Design of Distributed Software 131

Creating a Persistence UnitCreating a Persistence Unit

Persistence unit tells the container: which entity classes are to be managed by the entity

manager, the datasource used by those entities.

Created by defining its properties in persistence.xml table generation strategy

Netbeans 5.5 : mostly created using the New Persistence Unit wizard.

4.1 Entities

Page 120: Chapter 3: Middleware Services

Design of Distributed Software 132

Creating a Persistence UnitCreating a Persistence Unit Right-click the web application node in the

Projects window and choose New > File/Folder From the Persistence category, select

Persistence Unit and click Next. Choose Persistence Provider

E.g. TopLink (Netbeans default). Provides the libraries for Java Persistence and the

entity manager Other: Hibernate, etc.

Choose Data Source E.g. jdbc/sample (Netbeans default). Used to connect to the database Specify table generation strategy (default: create)

4.1 Entities

Page 121: Chapter 3: Middleware Services

Design of Distributed Software 133

Creating the Entity ClassesCreating the Entity Classes Cfr http://www.netbeans.org/kb/55/persistence.html

Animal class:

-name

-kind

-weight

-pavilion

Pavilion class:

-name

-address

-Collection <Animals>

1:n

ManyToOneOneToMany

4.1 Entities

Page 122: Chapter 3: Middleware Services

Design of Distributed Software 134

Creating the Entity ClassesCreating the Entity Classes

package entity;

import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.ManyToOne;

@Entitypublic class Animal implements Serializable {

@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name="animalName") private String name; private String kind; private String weight; @ManyToOne private Pavilion pavilion; /** Creates a new instance of Animal */ public Animal() { }

public Long getId() { return id; }

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

public String toString() { return "entity.Animal[id=" + getId() + "]"; }

public String getName() { return name; }

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

public String getKind() { return kind; }

public void setKind(String kind) { this.kind = kind; }

public String getWeight() { return weight; }

public void setWeight(String weight) { this.weight = weight; }

public Pavilion getPavilion() { return pavilion; }

public void setPavilion(Pavilion pavilion) { this.pavilion = pavilion; } }

Animal.java

4.1 Entities

Page 123: Chapter 3: Middleware Services

Design of Distributed Software 135

Creating the Entity ClassesCreating the Entity Classes

package entity;

import java.io.Serializable;import java.util.Collection;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToMany;

@Entitypublic class Pavilion implements Serializable {

@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name="pavilionName") private String name; private String address; @OneToMany(mappedBy="pavilion") private Collection <Animal> animals; public Pavilion() { }

public Long getId() { return id; }

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

Pavilion.java public String toString() { return "entity.Pavilion[id=" + getId() + "]"; }

public String getName() { return name; }

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

public String getAddress() { return address; }

public void setAddress(String address) { this.address = address; }

public Collection<Animal> getAnimals() { return animals; }

public void setAnimals(Collection<Animal> animals) { this.animals = animals; } }

4.1 Entities

Page 124: Chapter 3: Middleware Services

Design of Distributed Software 136

Creating a Web InterfaceCreating a Web Interface4.1 Entities

Page 125: Chapter 3: Middleware Services

Design of Distributed Software 137

Creating a Web InterfaceCreating a Web Interface Choose File > New. Select JSF Pages from Entity

Class from the Persistence category and click Next.

In the New JSF Pages from Entity Class wizard, click Add All to select our two entity classes and click Next.

Specify the package for the generated classes and click Finish.

Running the project: Start the Java DB database by choosing Tools > Java

DB Database > Start Java DB Server. Right-click the project node and choose Run Project.

4.1 Entities

Page 126: Chapter 3: Middleware Services

Design of Distributed Software 138

Building Java 5 Applications with EntitiesBuilding Java 5 Applications with Entities

Option 2: Start from DB structure

Start the Java DB database by choosing Tools > Java DB Database > Start Java DB Server.

Choose New File (Ctrl-N) to open the New File wizard. Select Entity Classes from Database from the Persistence category and click Next.

In the Entity Classes from Database wizard, select the data source for the database : a list of available tables appears in the Available Tables pane.

Select the right table from the Available Tables and click Add. When you click Add, any tables related to the selected table are also added.

Click Next. The selected table and any related tables are displayed. If you want to modify the name of the class that will be generated, you can type the name in the Class Name field.

4.1 Entities

Page 127: Chapter 3: Middleware Services

Design of Distributed Software 139

Building Java 5 Applications with EntitiesBuilding Java 5 Applications with Entities

Option 2: URL:

http://www.netbeans.org/kb/55/customer-book.html (“Comparing Java EE 5 Platform and J2EE 1.4 Platform”)

Shows Use of EntityManager when using entities

4.1 Entities

Page 128: Chapter 3: Middleware Services

Design of Distributed Software 140

Using EntitiesUsing Entities

In the Source Editor, right-click in the java-file and choose Persistence > Use Entity Manager to inject the PersistenceContext in the class.

The IDE adds the following annotation that specifies the persistence unit. The annotation is added above the class declaration. @PersistenceContext(name = "persistence/LogicalName",

unitName = “NamePU") The IDE also adds the following annotation injecting a

resource for managing transaction boundaries: @Resource private UserTransaction utx;

The IDE generates default code, to be adapted by programmers

4.1 Entities

Page 129: Chapter 3: Middleware Services

Design of Distributed Software 141

Using EntitiesUsing Entities

public Customer findByID(Integer customerNr) { Customer customer = null; try { Context ctx = (Context) new InitialContext().lookup("java:comp/env"); EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName"); utx.begin(); customer = em.find(Customer.class, customerNr); utx.commit(); } catch(Exception e) { Logger.getLogger(getClass().getName()).log(Level.SEVERE,"exception caught", e); throw new RuntimeException(e); } return customer; }

Partially generated by IDE, adapted by programmer

4.1 Entities

Page 130: Chapter 3: Middleware Services

Design of Distributed Software 142

Example Object Relational Mapping (ORM)Example Object Relational Mapping (ORM)package ods.ejb;

import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.NamedQueries;import javax.persistence.NamedQuery;

@NamedQueries({ @NamedQuery ( name="findAccountByUsername", query="SELECT acc FROM Account acc

WHERE acc.username = :username" )})

@Entitypublic class Account implements Serializable {

@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id;

//The username of this account. @Column(unique = true, nullable = false) private String username; //The password of this account. @Column(nullable = false) private String password; //Indicates if the user (attached to this account) is an //administrator. @Column(nullable = false) private boolean isAdmin;

public Account() { } public Account(String username, String password,

boolean isAdmin){ this.username = username; this.password = password; this.isAdmin = isAdmin; }

public Long getId() { return this.id; }

public void setId(Long id) { this.id = id; } … }

4.1 Entities

Page 131: Chapter 3: Middleware Services

Design of Distributed Software 143

Example Façade Session Example Façade Session package ods.ejb;

import java.util.List;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.NoResultException;import javax.persistence.PersistenceContext;

@Statelesspublic class AccountFacade implements AccountFacadeLocal {

@PersistenceContext private EntityManager em; public AccountFacade() { } public boolean isValidAccount(String username, String password){ Account account = findByUsername(username); boolean valid = false; If(account != null) if(account.getPassword().equals(password)) valid = true; return valid; } public Account addAccount(String username,

String password, boolean isAdmin) throws IllegalArgumentException{ Account existing = findByUsername(username); if(existing != null) throw new IllegalArgumentException("username allready exists"); else{ Account account = new Account(username, password, isAdmin); create(account); return account; } }

public Account findByUsername(String username){ try { Account account = (Account)

em.createNamedQuery("findAccountByUsername") .setParameter("username", username).getSingleResult(); return account; } catch (NoResultException e) { } return null; }

public void create(Account account) { em.persist(account); }

public void edit(Account account) { em.merge(account); }

public void destroy(Account account) { em.remove(em.merge(account)); }

public Account find(Object pk) { return (Account) em.find(Account.class, pk); }

public List findAll() { return em.createQuery("select object(o) from Account as

o").getResultList(); } }

4.1 Entities

Page 132: Chapter 3: Middleware Services

Design of Distributed Software 144

Entity Lifecycle ManagementEntity Lifecycle Management

@PrePersistMarks a method in the entity class as a pre-persist callback (executed before an entity is persisted).

@PostPersistMarks a method in the entity class as a postpersist callback (executed after an entity is persisted).

@PreUpdateMarks a method in the entity class as a preupdate callback (executed before entity data is updated in the

database).

@PostUpdateMarks a method in the entity class as a postupdate callback (executed after entity data is updated in the

database).

@PreRemoveMarks a method in the entity class as a preremove callback (executed before an entity is removed from the

database).

@PostRemoveMarks a method in the entity class as a postremove callback (executed after an entity is removed from the

database).

@PostLoadMarks a method in the entity class as a postload callback (executed before an entity is loaded from the

database).

4.1 Entities

Page 133: Chapter 3: Middleware Services

Design of Distributed Software

3.4 Persistence Service3.4 Persistence Service

1. Java 5 Entities2. (Java 1.4 Entity Beans) 3. EJB Design Patterns

Page 134: Chapter 3: Middleware Services

Design of Distributed Software 146

IntroductionIntroductionEntity Beans

represents business object in permanent storage= “row in a database table”

persistent storage mechanism in AS :relational database

typically bean class associated to table bean instances associated to row in table

characteristics persistent allow shared access can be found using primary key participate in relations with other beans

4.2. Java 1.4 Entity Beans

Page 135: Chapter 3: Middleware Services

Design of Distributed Software 147

Shared AccessShared Access Multiple clients access same bean Requirements

safe access (locks) client isolation

Implemented using Transaction Service Transaction attributes specified when deploying the

bean Transaction boundaries added by container

4.2. Java 1.4 Entity Beans

Page 136: Chapter 3: Middleware Services

Design of Distributed Software 148

PersistencePersistence Bean survives

- application shutdown- server crashes/restarts/...

• Two persistency flavours- Bean Managed Persistence :

- code (SQL) for DB access (load/store/updates) written by programmer

- not necessarily portable to other DB- Container Managed Persistence

- code automatically generated and called- more portable approach

4.2. Java 1.4 Entity Beans

Page 137: Chapter 3: Middleware Services

Design of Distributed Software 149

Entity Beans : Life CycleEntity Beans : Life Cycle

Does NotExist

Ready

newInstancesetEntityContext

business method ejbLoadejbStore

Pooled

ejbActivate

ejbPassivate

unsetEntityContext1. create2. ejbCreate3. ejbPostCreate

1. remove2. ejbRemove

no specific identityall pooled instances are equal

4.2. Java 1.4 Entity Beans

Page 138: Chapter 3: Middleware Services

Design of Distributed Software 150

Components of an Entity EJBsComponents of an Entity EJBs

Three parts: Component interface (local and/or remote) Home interface (local and/or remote) The bean class

Implements javax.ejb.EntityBean

And a Primary Key class Can be an existing class

String, Integer, Date, etc. Can be a new class (e.g., for composite keys)

Must properly override hashCode and equals Must be serializable Naming convention: XKey

4.2. Java 1.4 Entity Beans

Page 139: Chapter 3: Middleware Services

Design of Distributed Software 151

Home InterfaceHome Interface Life Cycle methods

As with Session Beans, each ejbCreate method is reflected in the Home interface

In addition, for every ejbCreate method there’s a corresponding ejbPostCreate method

PostCreate is invoked after the bean has an EJB object, and is represented in the persistent data storage

Allows you to pass references to the bean to other EJBs– e.g., relationships

Other lifecycle methods include ejbActivate, ejbPassivate,, and ejbRemove

Home methods to be executed on all instances

Finder methods : ejbFindXXX DB Synchronization methods : ejbLoad, ejbStore

4.2. Java 1.4 Entity Beans

Page 140: Chapter 3: Middleware Services

Design of Distributed Software

3.4.2 EJB: Java 1.4 Entity 3.4.2 EJB: Java 1.4 Entity BeansBeans

1. Bean Managed Persistence 2. Container Managed Persistence

Page 141: Chapter 3: Middleware Services

Design of Distributed Software 153

BMP : Activation ...BMP : Activation ... getting an identity

pooled -> ready : bean MUST be associated withbusiness object

done through assigning primary key in ejbCreate AND ejbActivate :

set primary key value Bean creation process

4.2.1 BMP EJB

Page 142: Chapter 3: Middleware Services

Design of Distributed Software 154

Managing StorageManaging Storage

Assuming each bean represents a row in a relational table:

The ejbCreate methods should add a row to the database

The ejbRemove method should remove the row represented by the bean instance

ejbLoad should assume nothing about the instance variables mapped to table fields, and reload their values from the database

You can find the primary key by invoking getPrimaryKey on the EntityContext reference

ejbStore should update the table row to reflect the current bean state

4.2.1 BMP EJB

Page 143: Chapter 3: Middleware Services

Design of Distributed Software 155

Managing StorageManaging Storage

Conceptually, ejbLoad is called before every business method So the method is sure to work with up-to-date values from the

database Likewise, ejbStore is called after every business method

Storing any changes made to the instance variables As a result, beans can survive container crashes Serious performance hit

Common practice: maintain a ‘dirty’ flag

Note that according to the spec, the container may invoke ejbLoad and ejbStore arbitrarily, and does not have to call them before/after every business method invocation

4.2.1 BMP EJB

Page 144: Chapter 3: Middleware Services

Design of Distributed Software 156

Activation and PassivationActivation and Passivation

Bean instances are managed in a pool The same bean instance, after created, can be used for different

table rows at different times Saves instantiation costs

When a bean is returned to the pool (detached from a given row), it is passivated

When a bean is re-attached to a row, it is activated

Persistent data should not be stored/reloaded during activation/passivation

Use ejbPassivate/ejbActivate to release/reacquire other resources

4.2.1 BMP EJB

Page 145: Chapter 3: Middleware Services

Design of Distributed Software 157

Storage and ActivationStorage and Activation 4.2.1 BMP EJB

Page 146: Chapter 3: Middleware Services

Design of Distributed Software 158

Finder MethodsFinder Methods

Given the home interface, a client can create new entity EJBs using the various create methods

Remember that each create method in the home interface has a corresponding ejbCreate and ejbPostCreate method in the bean class

But what if the client wants to locate existing beans? The home interface also includes finder methods.

Named findXXX Must return either java.util.Collection, or the component

interface type Throws FinderException (and RemoteException for remote

homes) Always defined: findByPrimaryKey(keytype)

4.2.1 BMP EJB

Page 147: Chapter 3: Middleware Services

Design of Distributed Software 159

Finder MethodsFinder Methods

For each findXXX method in the home interface, a corresponding ejbFindXXX method must be implemented in the bean class

ejbFindByPrimaryKey is required Finder methods can find a single record

This includes ejbFindByPrimaryKey Value returned must be the primary key of the found record

which is the parameter in ejbFindByPrimaryKey’s case Throw FinderException if no record was found

Finder methods can find a set of records Signature must define java.util.Collection as return type Return a collection of primary keys Return an empty collection if no records were found

4.2.1 BMP EJB

Page 148: Chapter 3: Middleware Services

Design of Distributed Software 160

Removing a RowRemoving a Row

The last lifecycle method, ejbRemove, must include code to remove the row corresponding to the current bean instance from the persistent data store

Can throw javax.ejb.RemoveException if removal failed.

4.2.1 BMP EJB

Page 149: Chapter 3: Middleware Services

Design of Distributed Software 161

SQL mappingSQL mapping

ejbCreate INSERTejbRemove DELETEejbLoad SELECTejbStore UPDATEejbFindXXX SELECT

4.2.1 BMP EJB

Page 150: Chapter 3: Middleware Services

Design of Distributed Software 162

BMP design: different stepsBMP design: different steps

1. Database set up

2. Create bean template

3. Database lookup

4. Class attributes and get/set

5. Life cycle methodsejbCreate, ejbPostCreate, ejbRemoveejbLoad, ejbStoreejbActivate, ejbPassivatefinder methods

6. Business methods 7. Home methods

8. Client code

4.2.1 BMP EJB

Page 151: Chapter 3: Middleware Services

Design of Distributed Software

3.4.2 EJB Java 1.4 : Entity 3.4.2 EJB Java 1.4 : Entity BeansBeans

1. Bean Managed Persistence 2. Container Managed Persistence

Page 152: Chapter 3: Middleware Services

Design of Distributed Software 164

Letting the Container Do the WorkLetting the Container Do the Work

Entity beans, as defined so far, must include a lot of SQL statements if they use a database as their data source

SELECT for ejbLoad and finder methods INSERT for create methods UPDATE for ejbStore DELETE for ejbRemove

The work is repetitive, tedious, and error-prone Why not automate it? Enter CMP: Container Managed Persistence for Entity EJBs

4.2.2 CMP EJB

Page 153: Chapter 3: Middleware Services

Design of Distributed Software 165

CMP Entity BeansCMP Entity Beans

CMP EJBs work just like BMP EJBs Same lifecycle

However, the mapping between persistent bean attributes and table columns is defined in a declarative manner.

tell the container which attribute corresponds to which column the container generates deployment code that handles

loading, finding, deleting, etc. In the EJB 1.x spec, persistent attributes are simply class

variables. Starting with EJB 2.0, persistent attributes are not reflected as

class variables Only defined by getter/setter methods Allows the container to manage a ‘dirty’ flag automatically,

thus saving needless updates

4.2.2 CMP EJB

Page 154: Chapter 3: Middleware Services

Design of Distributed Software 166

CMP BeansCMP Beans

part of bean deployment descriptor (declarative) describes bean persistent state and relationships referenced by queries written in EJB QL supply one EJB query for each finder method

Persistent Fields

Abstract Schema

• persistent bean state• automatically synchronized at runtime• no coding of persistent fields, just declare them in the AS• identified my get/set methods

4.2.2 CMP EJB

Page 155: Chapter 3: Middleware Services

Design of Distributed Software 167

Bean classBean class

CMP BMPClass definition abstract not abstractDB calls handled by container not handled by containerPersistent state virtual state instance variablesAccess methods for state and relationships

required none requiredfindByPrimaryKey by container to be codedfindXXX provide EJB query to be codedselect methods handled by container nonereturn ejbCreate none primary key object

4.2.2 CMP EJB

Page 156: Chapter 3: Middleware Services

Design of Distributed Software 168

Lifecycle Methods in CMP Entity BeansLifecycle Methods in CMP Entity Beans

Each CMP entity bean must include the same lifecycle methods as BMP beans

However, some of the semantics are slightly different: ejbLoad is called immediately after the data is loaded

Allows you to calculate values for any class variables that depend on field values

Should not attempt to load the data by itself ejbStore is called immediately before the data is stored

Does not store the data by itself ejbRemove is called immediately before the row is removed

Does not actually remove the row by itself All are normally empty.

4.2.2 CMP EJB

Page 157: Chapter 3: Middleware Services

Design of Distributed Software 169

Access MethodsAccess Methods

For each persistent attribute A in the bean, there must be a getA and/or a setA method

The getters and setters are defined in the bean class as abstract methods

Their actual implementation is included in a subclass generated by the container.

Implication: the bean class itself is abstract.

4.2.2 CMP EJB

Page 158: Chapter 3: Middleware Services

Design of Distributed Software 170

Finder Methods in CMP Entity BeansFinder Methods in CMP Entity Beans

Finder methods are defined normally in the home interface However, no corresponding ejbFindXXX methods are defined in

the bean class Each finder method is associated (in the deployment descriptor)

with an EJB QL query The query should return one row (at most) if the finder is

defined to return a single bean The query should return zero or more rows if the finder is

defined to return a collection EJB QL is a modified subset of SQL

4.2.2 CMP EJB

Page 159: Chapter 3: Middleware Services

Design of Distributed Software 171

Select MethodsSelect Methods

Similar to finder methods can return local/remote interface queries the DB EJB QL query associated with every select method not implemented in the bean class

Different from finder methods can return persistent state of related bean not exposed to client -> only invoked by other beans methods defined in the entity bean class

4.2.2 CMP EJB

Page 160: Chapter 3: Middleware Services

Design of Distributed Software 172

CMP design: different stepsCMP design: different steps

1. Database set up -> idem as BMP

2. Create bean template

3. Database lookup

4. Class attributes : get/set

5. Life cycle methods1. ejbCreate, ejbPostCreate, ejbRemove2. ejbLoad, ejbStore3. ejbActivate, ejbPassivate4. finder methods

6. Business methods -> idem as BMP

7. Home methods -> idem as BMP

8. Facade Session Bean

9. Client code -> idem as BMP (actually calls SB !)

4.2.2 CMP EJB

Page 161: Chapter 3: Middleware Services

Design of Distributed Software

3.4 Persistence Service3.4 Persistence Service

1. Java 5 Entities2. (Java 1.4 Entity Beans) 3. EJB Design Patterns

Page 162: Chapter 3: Middleware Services

Design of Distributed Software 174

EntityBean 1

EntityBean 1

EntityBean 1

EJB Design PatternsEJB Design Patterns

Facade

ControllerEntityBean 1

EntityBean 2

EntityBean 3

EntityBean 3

EntityBean 3

EntityBean 3

EntityBean 2

Clientproxy

Facade pattern

• session bean

• presents API to clients

Proxy pattern

abstracts the server to the client

Command pattern

• reduce the complexity in the communication

• decouple client - server

4.3 Design Patterns

Page 163: Chapter 3: Middleware Services

Design of Distributed Software 175

The Session Facade PatternThe Session Facade Pattern Used for minimizing

Client/entity bean coupling Risk of client using unapproved business methods

Or using approved business methods in unapproved ways Network delays Points of change if high-level business operations are

modified The idea: create a Session EJB that provides high-

level business methods Client should only work with the session bean(s) Entity EJBs provide (possibly only) a local interface

Session EJB accesses entity EJBs locally

4.3 Design Patterns

Page 164: Chapter 3: Middleware Services

Design of Distributed Software 176

The Session Facade PatternThe Session Facade Pattern

Client

Client

Client

Application Server

No Facade

4.3 Design Patterns

Page 165: Chapter 3: Middleware Services

Design of Distributed Software 177

The Session Facade PatternThe Session Facade Pattern

Client

Client

Client

Application Server

With Facade

4.3 Design Patterns

Page 166: Chapter 3: Middleware Services

Design of Distributed Software 178

Session Facade ExampleSession Facade Example

Client code without the facade: Find Account home Find accounts a1, a2 by primary keys k1, k2 a1.setBalance(a1.getBalance() - amount); a2.setBalance(a2.getBalance() + amount);

Client code with the facade: Find TransferBean home, create TransferBean t1 t1.transfer(k1, k2, amount);

4.3 Design Patterns

Page 167: Chapter 3: Middleware Services

Design of Distributed Software 179

Resulting BenefitsResulting Benefits

Faster operation 1 JNDI lookup, 1 remote object lookup and 1 remote business method

vs. 1 JNDI lookup, 2 remote object lookups and 4 remote business methods in the old code

Easier maintenance If we have two different clients (servlet, application) and we wish to

change the transfer semantics (e.g., add logging), there's only one place to change

Easier transaction management can be started at the facade

Increased security Client can't invoke Account.setBalance directly, since Account has

no remote component interface

4.3 Design Patterns

Page 168: Chapter 3: Middleware Services

Design of Distributed Software 180

Proxy PatternProxy Pattern

Class at client side Abstracts home interface location to the client Performance benefit : cache home objects Also called “EJBHomeFactory pattern”

Application Server

ClientNoProxy

EJBHome

ClientProxy

4.3 Design Patterns

Page 169: Chapter 3: Middleware Services

Design of Distributed Software 181

Proxy PatternProxy Pattern

Advantages Proxy can contain JNDI name – Bean class mapping Can serve as cache for EJBHome objects Allows cleaner coding style

4.3 Design Patterns

Page 170: Chapter 3: Middleware Services

Design of Distributed Software 182

Command PatternCommand Pattern Command pattern

= Class, transmitted from one object to another Client constructs commands, facade forwards them to right controller

Example codepublic interface BasicCommandInterface{

public String getCommandTarget();public String getCommandInstruction();public HashMap getCommandData();public void setCommandData(String key,Object value);public void setCommandTarget(String aTarget);public void setCommandInstruction(String anInstruction);public execute();public void getCommandData(HashMap aData);

}

Applications can be modified dynamically Facade doesn’t need to provide all interface methods

4.3 Design Patterns

Page 171: Chapter 3: Middleware Services

Design of Distributed Software 183

Command PatternCommand Pattern

Client

Command Processor (stateless SB)

Command Routing(could be proxy)

Commands

• decoupling client – server• single network transaction

Controller (stateful SB)

4.3 Design Patterns

Page 172: Chapter 3: Middleware Services

Design of Distributed Software 184

Other Recommended PracticesOther Recommended Practices

Avoid calling EJB methods directly from JSP The need to catch remote exceptions would

complicate the JSP code Avoid hard-coding JNDI properties

Store configuration hashtable values in a file Avoid hard-coding JNDI resource names Avoid fine grain data transfers

4.3 Design Patterns