166
Copyright JBoss Group Copyright JBoss Group The client side Dynamic Proxies, Smart RMI, Client Interceptors Building your own JMX proxy client

Jboss Additional Slides 1

Embed Size (px)

Citation preview

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 1/166

Copyright JBoss GroupCopyright JBoss Group

The client side

Dynamic Proxies, Smart RMI, Client Interceptors

Building your own JMX proxy client

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 2/166

 New York, March 2003 9 - Client Side JBoss"2

20032003 ©© JBoss GroupJBoss Group

Client Architecture Elements 

ß Dynamically generating implementations of interfaces with

• Dynamic proxies

• Generalized invocation handlers

• Invokers

ß Client-side interceptors

• The structure of an invocation

• Context free stateless interceptor design

ß Example: the client EJB design, clustering, caching

ß Getting these objects stacks to the client

• In the case of RMI Remote objects

• In the case of generic interface classes

• The use of JNDI

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 3/166

 New York, March 2003 9 - Client Side JBoss"3

20032003 ©© JBoss GroupJBoss Group

Dynamic Proxies (1/3) 

ß Relies on the Proxy class introduced in JDK 1.3

•  java.lang.reflect.Proxy

ß Capable of offering an implementation of any interface

• It cannot proxy non-interfaces

ß Generates “handler” call for any number of interfaces

ß From interface -> an object “implementing” that interface

• “implementation” means that the object is of the type declared

• It can’t do anything useful

ß Delegates all interface methods to a handler specified at proxy

creation time java.lang.reflect.InvocationHandler 

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable

 java.lang.reflect.InvocationHandler 

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 4/166

 New York, March 2003 9 - Client Side JBoss"4

20032003 ©© JBoss GroupJBoss Group

Dynamic Proxies (2/3) 

ß Creation of a Proxy

• Takes interface(s)

• Takes an invocationHandler 

• Proxy.newProxy(…)

Interfaces

Proxy Generator  Interface + Implementation+IH

Invocation handler 

invoke(method, params)

invoke(m, p)

methodA.1

methodB.1methodA

methodB

The program using DP

specifies the

interfaces and a

handler with a generic

signature

The program using DP

specifies the

interfaces and a

handler with a generic

signature

The “object” is the

whole set of interface +

proxy+handler 

The “object” is the

whole set of interface +

proxy+handler 

methodA.2

methodB.2

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 5/166

 New York, March 2003 9 - Client Side JBoss"5

20032003 ©© JBoss GroupJBoss Group

Dynamic Proxies (3/3) 

ß How does it work?

• A call lands on the “typed” interface

• The proxy mechanism multiplexes on invoke

• We supply an “invocation handler” to actually field the call

Client

Interface

Seen by client Proxy

Invocation Handler 

Invoke(methodA, params)

methodA

methodBInvoke(methodB, params)

Invoke

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 6/166

 New York, March 2003 9 - Client Side JBoss"6

20032003 ©© JBoss GroupJBoss Group

Dynamic Proxies 

ß We now have a DETYPED CHAIN

• This is the basis for our indirected work• We can ADD ANY GENERIC BEHAVIOR to ANY OBJECT

• Example transactions, security, network invocation

• These behaviors are INDEPENDENT of the interface being exposed

ß

The interfaces are not necessarily known when you write thegeneric interceptors, nor do you care

• It can be an EJB interface , or a JMX Mbean Standard interface

• WYSIWYG class development

• These are deployed at run-time in the server 

• The developer of the interceptor DOESN’T know these definitionsß Payload specific interceptors are recommended (caching)

ß Other servers solve this with RUNTIME COMPILATION

• EJBC and other non-sense

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 7/166

 New York, March 2003 9 - Client Side JBoss"7

20032003 ©© JBoss GroupJBoss Group

Dynamic Proxies 

ß Adding behavior to the invocation handler 

• The invocation handler is made up of client side interceptors

• Each interceptor can implement a specific behavior 

• This is the generalized invocation handler 

methodB

Each interface is

the “invoke()”

signature

Each interface is

the “invoke()”

signature

The Handler is

really a set of 

interceptors

The Handler is

really a set of 

interceptors

Object in Client VM

EJB TxSecurity transport

Client

Container 

method

params

method

params

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 8/166

 New York, March 2003 9 - Client Side JBoss"8

20032003 ©© JBoss GroupJBoss Group

The Client Interceptor 

package org.jboss.proxy;

public abstract class Interceptor implements Externalizable{

/** The next interceptor in the chain. */

protected Interceptor nextInterceptor;

public Interceptor setNext(final Interceptor interceptor) {

// assert interceptor != null

nextInterceptor = interceptor;

return interceptor;

}

Public Interceptor getNext() {

return nextInterceptor;

}

public abstract Object invoke(Invocation mi) throws Throwable;

}

package org.jboss.proxy;

public abstract class Interceptor implements Externalizable

{

/** The next interceptor in the chain. */

protected Interceptor nextInterceptor;

public Interceptor setNext(final Interceptor interceptor) {

// assert interceptor != null

nextInterceptor = interceptor;return interceptor;

}

Public Interceptor getNext() {

return nextInterceptor;

}

public abstract Object invoke(Invocation mi) throws Throwable;

}

EJB Tx Security TransportClient

Container 

methodparamsmethodparams

Inside the

Interceptor 

interface

Inside the

Interceptor 

interface

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 9/166

 New York, March 2003 9 - Client Side JBoss"9

20032003 ©© JBoss GroupJBoss Group

Invocation 

ß The Invocation represents an actual call made on the client

interfaceß It is generated right at the head of the handler 

ß It contains the encoded representation of the Method Invocationitself 

• Method, parameters as output by the dynamic proxiesß It can accommodate an arbitrary payload

•  All of the above plus arbitrary data from the interceptors

• Each interceptor can add it’s information

• Transaction, security, caching version etc • Data can be Marshalled in case of application types or just serialized

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 10/166

 New York, March 2003 9 - Client Side JBoss"10

20032003 ©© JBoss GroupJBoss Group

The structure of an Invocation 

package org.jboss.invocation;

public class Invocation{

 /**

* The payload is a repository of everything associated with the invocation

* It is information that will need to travel

*/

// Contextual information to the invocation that is not part of the payloadpublic Map transient_payload = new HashMap();

// as_is classes that will not be marshalled by the invocation (java.* and javax.* or anything in system //classpath is OK)

public Map as_is_payload = new HashMap();

// Payload will be marshalled for type hiding at the RMI layers

public Map payload = new HashMap();

// Invocation context

INVOCATION_CONTEXT = new Integer(new String("INVOCATION_CONTEXT").hashCode()),

package org.jboss.invocation;

public class Invocation{

 /**

* The payload is a repository of everything associated with the invocation

* It is information that will need to travel

*/

// Contextual information to the invocation that is not part of the payload

public Map transient_payload = new HashMap();

// as_is classes that will not be marshalled by the invocation (java.* and javax.* or anything in system //classpath is OK)

public Map as_is_payload = new HashMap();

// Payload will be marshalled for type hiding at the RMI layers

  public Map payload = new HashMap();

// Invocation context

INVOCATION_CONTEXT = new Integer(new String("INVOCATION_CONTEXT").hashCode()),

EJB Tx Security TransportClientContainer 

method

params

method

params

Inside the

Invocation

Inside the

Invocation

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 11/166

 New York, March 2003 9 - Client Side JBoss"1120032003 ©© JBoss GroupJBoss Group

The structure of an Invocation 

//The generic store of variables

public void setValue(Object key, Object value) { setValue(key, value, PAYLOAD); }

// Advanced store

// Here you can pass a TYPE that indicates where to put the value.

// TRANSIENT: the value is put in a map that WON'T be passed

// AS_IS: no need to marshall the value when passed (use for all JDK java types)

// PAYLOAD: we need to marshall the value as its type is application specific

public void setValue(Object key, Object value, int TYPE)

{

switch (TYPE)

{

case TRANSIENT:

transient_payload.put(key,value);

break;

case AS_IS:

as_is_payload.put(key,value);

break;case PAYLOAD:

payload.put(key,value);

break;

}

}

  //The generic store of variables

  public void setValue(Object key, Object value) { setValue(key, value, PAYLOAD); }

// Advanced store

// Here you can pass a TYPE that indicates where to put the value.

// TRANSIENT: the value is put in a map that WON'T be passed

// AS_IS: no need to marshall the value when passed (use for all JDK java types)

// PAYLOAD: we need to marshall the value as its type is application specific

public void setValue(Object key, Object value, int TYPE)

{

switch (TYPE){

case TRANSIENT:

transient_payload.put(key,value);

break;

case AS_IS:

as_is_payload.put(key,value);

break;

case PAYLOAD:

payload.put(key,value);

break;

}

}

EJB Tx Security TransportClient

Container 

methodParams

TX

method

Params

TX

An interceptor 

puts its own data

under a key

An interceptor 

puts its own data

under a key

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 12/166

 New York, March 2003 9 - Client Side JBoss"1220032003 ©© JBoss GroupJBoss Group

The structure of an Invocation 

 // set and get on transaction

public void setTransaction(Transaction tx) { as_is_payload.put(TRANSACTION, tx); }public Transaction getTransaction() { return (Transaction) getValue(TRANSACTION); }

 // Change the security identity of this invocation.

public void setPrincipal(Principal principal) { as_is_payload.put(PRINCIPAL, principal);}

public Principal getPrincipal() { return (Principal) getValue(PRINCIPAL);}

 // A container for server side association

public void setObjectName(Object objectName) { payload.put(OBJECT_NAME, objectName);}

public Object getObjectName() { return getValue(OBJECT_NAME);}

 // set and get on method Return the invocation method.

public void setMethod(Method method) { payload.put(METHOD, method);}

public Method getMethod() { return (Method) getValue(METHOD);}

 // A list of arguments for the methodpublic void setArguments(Object[] arguments) { payload.put(ARGUMENTS, arguments); }

public Object[] getArguments() { return (Object[]) getValue(ARGUMENTS); }

 // A pointer to the contextual information

public void setInvocationContext(InvocationContext ctx) { transient_payload.put(INVOCATION_CONTEXT, ctx);}

 // set and get on transaction

public void setTransaction(Transaction tx) { as_is_payload.put(TRANSACTION, tx); }

public Transaction getTransaction() { return (Transaction) getValue(TRANSACTION); }

 // Change the security identity of this invocation.

public void setPrincipal(Principal principal) { as_is_payload.put(PRINCIPAL, principal);}

public Principal getPrincipal() { return (Principal) getValue(PRINCIPAL);}

 // A container for server side association

public void setObjectName(Object objectName) { payload.put(OBJECT_NAME, objectName);}public Object getObjectName() { return getValue(OBJECT_NAME);}

 // set and get on method Return the invocation method.

public void setMethod(Method method) { payload.put(METHOD, method);}

public Method getMethod() { return (Method) getValue(METHOD);}

 // A list of arguments for the method

public void setArguments(Object[] arguments) { payload.put(ARGUMENTS, arguments); }

public Object[] getArguments() { return (Object[]) getValue(ARGUMENTS); }

 // A pointer to the contextual information

public void setInvocationContext(InvocationContext ctx) { transient_payload.put(INVOCATION_CONTEXT, ctx);}

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 13/166

 New York, March 2003 9 - Client Side JBoss"1320032003 ©© JBoss GroupJBoss Group

The birth of an Invocation 

ß The ClientContainer is the Invocation Handler 

• from there on down it is just a string of interceptorsß The ClientContainer generates the Invocation object

• Puts all contextual data which pertains to the assembly

•  And the first invocation data (method, params)

EJB Tx Security TransportClient

Container 

method

params

method

params

The client container 

holds a reference to the

contextual information

about this assembly

The client container 

holds a reference to the

contextual information

about this assembly

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 14/166

 New York, March 2003 9 - Client Side JBoss"1420032003 ©© JBoss GroupJBoss Group

ClientContainer: Invocation creation 

public class ClientContainer implements Externalizable, InvocationHandler {

// the "static" information that gets attached to every invocation

public InvocationContext context;

public ClientContainer(InvocationContext context) { this.context = context;}

public Object invoke(final Object proxy, final Method m, Object[] args)

throws Throwable

{

//Create the invocation object

Invocation invocation = new Invocation();

// Contextual information for the interceptors

invocation.setInvocationContext(context);

invocation.setObjectName(context.getObjectName());invocation.setMethod(m);

invocation.setArguments(args);

// send the invocation down the client interceptor chain

return next.invoke(invocation);

}}

public class ClientContainer implements Externalizable, InvocationHandler {

// the "static" information that gets attached to every invocation

public InvocationContext context;

public ClientContainer(InvocationContext context) { this.context = context;}

public Object invoke(final Object proxy, final Method m, Object[] args)

throws Throwable

{//Create the invocation object

Invocation invocation = new Invocation();

// Contextual information for the interceptors

invocation.setInvocationContext(context);

  invocation.setObjectName(context.getObjectName());

invocation.setMethod(m);

invocation.setArguments(args);

// send the invocation down the client interceptor chain

return next.invoke(invocation);

}}

EJB Tx Security TransportClient

Container 

method

Paramsctx

method

Paramsctx

Creation in invoke()Creation in invoke()

InvocationHandler 

for dynamic proxy

InvocationHandler 

for dynamic proxy

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 15/166

 New York, March 2003 9 - Client Side JBoss"1520032003 ©© JBoss GroupJBoss Group

InvocationContext, static information 

package org.jboss.invocation;

public class InvocationContext implements java.io.Serializable {

// Context is a map

public Map context;

public static final Integer 

// We can keep a reference to an abstract "container"

OBJECT_NAME = new Integer(new String("OBJECT_NAME").hashCode()),

// The Cache-ID associates an instance in cache somewhere on the server with this invocation

CACHE_ID = new Integer(new String("CACHE_ID").hashCode()),

// The invoker 

INVOKER = new Integer(new String("INVOKER").hashCode());

//The generic store of variables

public void setValue(Object key, Object value) { context.put(key,value); }

// A container for server side association

public void setObjectName(Object objectName) { context.put(OBJECT_NAME, objectName);}

public Object getObjectName() { return context.get(OBJECT_NAME);}

}

package org.jboss.invocation;

public class InvocationContext implements java.io.Serializable {

// Context is a map

public Map context;

public static final Integer 

// We can keep a reference to an abstract "container"

OBJECT_NAME = new Integer(new String("OBJECT_NAME").hashCode()),// The Cache-ID associates an instance in cache somewhere on the server with this invocation

CACHE_ID = new Integer(new String("CACHE_ID").hashCode()),

// The invoker 

INVOKER = new Integer(new String("INVOKER").hashCode());

//The generic store of variables

public void setValue(Object key, Object value) { context.put(key,value); }

// A container for server side association

public void setObjectName(Object objectName) { context.put(OBJECT_NAME, objectName);}

public Object getObjectName() { return context.get(OBJECT_NAME);}

}

EJB Tx Security TransportClient

Container 

methodParams

ctx

method

Params

ctx

Every invocation

generated by this

client has this data

Every invocation

generated by this

client has this data

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 16/166

 New York, March 2003 9 - Client Side JBoss"1620032003 ©© JBoss GroupJBoss Group

EJB Interceptor 

ß EJB interceptor formats the invocation for EJB server-side

ß Can also take care of some local calls

• Either from Object

• Or from EJBObject itself 

ß Every type of bean is defined

• EntityInterceptor 

• StatefulInterceptor 

• StatelessInterceptor 

ß This is the ONLY interceptor that indicates an EJB nature

ß If the call is not fielded go on with the next interceptor 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 17/166

 New York, March 2003 9 - Client Side JBoss"1720032003 ©© JBoss GroupJBoss Group

EJB interceptor 

package org.jboss.proxy.ejb;

public class EntityInterceptor extends GenericEJBInterceptor {

public Object invoke(Invocation invocation) throws Throwable

{

InvocationContext ctx = invocation.getInvocationContext();

Method m = invocation.getMethod();

// Implement local methods

if (m.equals(TO_STRING))

{

  return toString(ctx);

}

else if (m.equals(EQUALS))

{

Object[] args = invocation.getArguments();

String argsString = args[0].toString();

String thisString = toString(ctx);

  return new Boolean(thisString.equals(argsString));

}

EJB Tx Security TransportClient

Container 

The EJB interceptor 

can return

The EJB interceptor 

can return

invocation

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 18/166

 New York, March 2003 9 - Client Side JBoss"1820032003 ©© JBoss GroupJBoss Group

EJB interceptor 

// Implement local EJB calls

else if (m.equals(GET_HANDLE)){

String jndiName = (String) ctx.getValue(JNDI_NAME);

Object id = ctx.getCacheId();

return new EntityHandleImpl(jndiName, id);

}

else if (m.equals(GET_PRIMARY_KEY))

{

return ctx.getCacheId();

}

// If not taken care of, go on and call the container 

else

{

// We are a Remote invocation

invocation.setType(Invocation.REMOTE);// We pertain to this ID (represented by cache ID)

invocation.setId(ctx.getCacheId());

return getNext().invoke(invocation);

}

}

   // Implement local EJB calls

else if (m.equals(GET_HANDLE))

{

String jndiName = (String) ctx.getValue(JNDI_NAME);

Object id = ctx.getCacheId();

return new EntityHandleImpl(jndiName, id);

}

else if (m.equals(GET_PRIMARY_KEY))

{

return ctx.getCacheId();}

// If not taken care of, go on and call the container 

else

{

   // We are a Remote invocation

invocation.setType(Invocation.REMOTE);

// We pertain to this ID (represented by cache ID)

invocation.setId(ctx.getCacheId());

return getNext().invoke(invocation);

}

}

EJB Tx Security TransportClientContainer 

If not done locally

we pass it on to the

next interceptor 

If not done locally

we pass it on to the

next interceptor 

invocation

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 19/166

 New York, March 2003 9 - Client Side JBoss"1920032003 ©© JBoss GroupJBoss Group

TX Interceptor 

ß Tx Interceptor propagates transactional information

• The proxy passes the information through the Invocation payload

• In the case of distributed call we will put TxPropagationContext

ß This is a simple and transparent way to add transactional behavior to your proxies

• Just specify as JBoss’ does for EJB proxies the transactionalinterceptor as part of your stack

• This interceptor is not tied to the EJB behavior it can be added to

any Mbean proxy.

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 20/166

 New York, March 2003 9 - Client Side JBoss"2020032003 ©© JBoss GroupJBoss Group

TxInterceptor 

package org.jboss.proxy;

public class TransactionInterceptor extends Interceptor {

public static TransactionManager tm;

public Object invoke(Invocation invocation) throws Throwable

{

if (tm != null)

invocation.setTransaction(tm.getTransaction());return getNext().invoke(invocation);

}

/** Transaction manager. */

public static void setTransactionManager(TransactionManager tmx) { tm = tmx;}

}

package org.jboss.proxy;

public class TransactionInterceptor extends Interceptor {

public static TransactionManager tm;

public Object invoke(Invocation invocation) throws Throwable

{

if (tm != null)

  invocation.setTransaction(tm.getTransaction());

return getNext().invoke(invocation);

}

/** Transaction manager. */

public static void setTransactionManager(TransactionManager tmx) { tm = tmx;}

}

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 21/166

 New York, March 2003 9 - Client Side JBoss"2120032003 ©© JBoss GroupJBoss Group

Invoker and transport 

package org.jboss.invocation;

public class InvokerInterceptor extends Interceptor implements Externalizable {

// We use this startup time to find if we are in the original VM

private long containerStartup = Invoker.STARTUP;

// Invoker to the remote JMX node

protected Invoker remoteInvoker;

// Static references to local invokers

protected static Invoker localInvoker;

/**

* Returns wether we are local to the originating container or not.

*/

public boolean isLocal() { return containerStartup == Invoker.STARTUP; }

/**

* The invocation on the delegate, calls the right invoker. Remote if we are remote, local if we

* are local.

*/

package org.jboss.invocation;

public class InvokerInterceptor extends Interceptor implements Externalizable {

// We use this startup time to find if we are in the original VM

private long containerStartup = Invoker.STARTUP;

// Invoker to the remote JMX node

protected Invoker remoteInvoker;

// Static references to local invokers

protected static Invoker localInvoker;

/**

* Returns wether we are local to the originating container or not.

*/

public boolean isLocal() { return containerStartup == Invoker.STARTUP; }

/**

* The invocation on the delegate, calls the right invoker. Remote if we are remote, local if we

* are local.

*/

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 22/166

 New York, March 2003 9 - Client Side JBoss"2220032003 ©© JBoss GroupJBoss Group

Invoker and transport 

public Object invoke(Invocation invocation)

throws Exception{

// optimize if calling another bean in same EJB-application

if (isLocal())

{

// The payload as is is goodreturn localInvoker.invoke(invocation);

}

else

{

// this payload will go through marshalling

return invocation.getInvocationContext().getInvoker().invoke(invocation);

}

}

public Object invoke(Invocation invocation)

throws Exception

{

// optimize if calling another bean in same EJB-application

  if (isLocal())

  {

// The payload as is is good

return localInvoker .invoke(invocation);

}

  else

  {

// this payload will go through marshalling

return invocation.getInvocationContext().getInvoker().invoke(invocation);

}

}

The invoker is set

on the “context” it

is a property of the

context

The invoker is set

on the “context” it

is a property of the

context

Local RMI

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 23/166

 New York, March 2003 9 - Client Side JBoss"2320032003 ©© JBoss GroupJBoss Group

Getting the stack on the client 

ß In case you use JNDI

• One of the properties of serialization enables us to download the fullstack of serializable objects to the client VM

• We assemble the stack ON THE SERVER SIDE and have the client

look it up through the JNDI environment

ß

The server assembly is done through the ProxyFactory and theclient described through XML

• This is the simplest way to get working proxies to an EJB

• In 3.0 this is default behavior for EJBs

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 24/166

 New York, March 2003 9 - Client Side JBoss"2420032003 ©© JBoss GroupJBoss Group

Fundamental Hacks (1/8) 

ß JDK 1.2.2 Remote Serialized

ß 2 types of objects in Remote invocations• Remote

• Serializable

ß Remote

• Defined by an interface

• Implementation is a “UnicastRemoteObject” or equivalent

• It is exported in the VM

ß Serializable

• Defined by an actual object definition

• Implements “serializable”

ß They behave differently on remote calls

• Remote passes a Stub

• Serializable passes a copy

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 25/166

 New York, March 2003 9 - Client Side JBoss"2520032003 ©© JBoss GroupJBoss Group

Fundamental Hacks (2/8) 

ß What happens in the VM when the return type is “Remote”

• VM returns a “Remote” object

• VM looks for the exported object

• It returns a Stub to the real object

Server VM

Proxy

Remote

Export

ClientVM

1/lookup

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 26/166

 New York, March 2003 9 - Client Side JBoss"2620032003 ©© JBoss GroupJBoss Group

Fundamental Hacks (3/8) 

ß Server VM returns a Proxy

Server VM

Proxy

Remote

ClientVM

2/return

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 27/166

 New York, March 2003 9 - Client Side JBoss"2720032003 ©© JBoss GroupJBoss Group

Fundamental Hacks (4/8) 

ß Communication is Client Server with Proxy-Remote object

Server VM

Proxy

Remote

ClientVM

3/Client-Server 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 28/166

 New York, March 2003 9 - Client Side JBoss"2820032003 ©© JBoss GroupJBoss Group

Fundamental Hacks (5/8) 

ß What happens in the VM when the return is “Serializable”

• VM knows it is a serializable instance

• VM serializes data

• It returns a copy

Server VM

Serializable

ClientVM

1/method return

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 29/166

 New York, March 2003 9 - Client Side JBoss"2920032003 ©© JBoss GroupJBoss Group

Fundamental Hacks (6/8) 

ß The copy lives in Client VM

Server VMClientVM

2/call local

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 30/166

 New York, March 2003 9 - Client Side JBoss"

3020032003 ©© JBoss GroupJBoss Group

Fundamental Hacks (7/8) 

ß So what?

• Starting 1.2.2 if the Remote Object is not “exported” the VM serializes• You can define a Remote Object and not implement “UnicastRemoteObject”

• It will be serialized even if Remote

• Before 1.2.2 you get a “can not find exported object”

Server VM

Remote(no export)

ClientVM

1/Lookup

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 31/166

 New York, March 2003 9 - Client Side JBoss"

3120032003 ©© JBoss GroupJBoss Group

Fundamental Hacks (8/8) 

ß Remote Object is serialized and lives on client

Server VM

Remote

ClientVM

2/Method Call

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 32/166

 New York, March 2003 9 - Client Side JBoss"

3220032003 ©© JBoss GroupJBoss Group

Remote Serialization + Dynamic Proxy 

= Logical EJBObjects(1/4) ß JBoss was a pioneer in Logical stub and skeletons

• No compilation necessary

• Very easy deployment

• N-1 relationship client server 

• Only 1 exported object

• Scalable

ß We combine these two features

• The EJBHomes and EJBObjects are Proxy instances that implement

EJB interfaces on client

• The Proxy InvocationHandler is a Serializable object that contains areference to the EJB container invoker Remote interface

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 33/166

 New York, March 2003 9 - Client Side JBoss"

3320032003 ©© JBoss GroupJBoss Group

Logical EJBObject (2/4) 

ß On Deployment

• Container Factory takes the interfaces•  And creates a Proxy that implements the EJBObject + bean interfaces

• Creates a EJBHome that it registers in JNDI

ß REMEMBER THAT EJB INTERFACES ARE REMOTE INTERFACES

EJBHome (Remote)

MyBeanHome

invoke(..)

Server 

Home interface as ProxyImplements EJBHome/MyBeanHomeinvoke(..)

Server 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 34/166

 New York, March 2003 9 - Client Side JBoss"

3420032003 ©© JBoss GroupJBoss Group

Logical EJBObject (3/4) 

ß Upon being called the Proxy is Remote but not exported

• EVERYTHING is serialized

• Until we find a REAL exported object

invoke(..)

Server 

JNDI

1/lookup

2/Serialization

No stubhas stub

Remote InterfacesRemote InterfacesRemote Interfaces

The invoker is

really exported

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 35/166

 New York, March 2003 9 - Client Side JBoss"

3520032003 ©© JBoss GroupJBoss Group

Logical EJBObject(4/4) 

ß Local proxy sends “invoke” on the wire

• Need for one proxy handler onlyß We OPTIMIZE the call if 2 VMs are the same (pass by reference)

• Basis for integration

Server invoke(..)methodA

No stubhas stub

Remote InterfacesRemote Interfaces

The Invoker is

the proxy/stub

Real object in

on server 

The Invoker is

the proxy/stub

Real object in

on server 

Server side interceptors

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 36/166

 New York, March 2003 9 - Client Side JBoss"

3620032003 ©© JBoss GroupJBoss Group

Specifying a custom stack for an EJB 

<!– standardjboss.xml or jboss.xml, 3.0 syntax -->

<jboss>

<enforce-ejb-restrictions>false</enforce-ejb-restrictions><container-configurations>

<container-configuration>

<container-name>Standard CMP 2.x EntityBean</container-name>

….

<client-interceptors>

<home>

<interceptor>org.jboss.proxy.ejb.HomeInterceptor</interceptor>

<interceptor>org.jboss.proxy.SecurityInterceptor</interceptor>

<interceptor>org.jboss.proxy.TransactionInterceptor</interceptor>

<interceptor>org.jboss.invocation.InvokerInterceptor</interceptor>

</home>

<bean>

<interceptor>org.jboss.proxy.ejb.EntityInterceptor </interceptor>

<interceptor>org.jboss.proxy.SecurityInterceptor </interceptor>

<interceptor>org.jboss.proxy.TransactionInterceptor </interceptor><interceptor>org.jboss.invocation.InvokerInterceptor </interceptor>

</bean>

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 37/166

 New York, March 2003 9 - Client Side JBoss"

3720032003 ©© JBoss GroupJBoss Group

Using Client side interceptors 

ß JBoss’ EJB use client interceptor 

• EJB = Dynamic Proxy + EJB interceptor + Tx + security

• Clustering is done with one clustering interceptor and smart proxies

ß Add you own behavior to the EJB

• Data entry validation

• Caching of results and session data•  Advanced clustering caches

• Bulk invocation

• Local fielding of calls

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 38/166

 New York, March 2003 9 - Client Side JBoss"

3820032003 ©© JBoss GroupJBoss Group

Distributed Invokers 

package org.jboss.invocation;

import java.rmi.Remote;

public interface Invoker extends Remote {

 /**

* The invoke with an Invocation Object

* the delegate can handle network protocols on behalf of proxies (proxies delegate to these puppies)

* We provide default implemenations with JRMP/Local/Clustered invokers.

* The delegates are not tied to a type of invocation (EJB or generic RMI).

*

* @param invocation A pointer to the invocation object

*

* @return Return value of method invocation.

*

* @throws Exception Failed to invoke method.

*/

public Object invoke(Invocation invocation) throws Exception;

}

package org.jboss.invocation;

import java.rmi.Remote;

public interface Invoker extends Remote {

 /**

* The invoke with an Invocation Object

* the delegate can handle network protocols on behalf of proxies (proxies delegate to these puppies)

* We provide default implemenations with JRMP/Local/Clustered invokers.* The delegates are not tied to a type of invocation (EJB or generic RMI).

*

* @param invocation A pointer to the invocation object

*

* @return Return value of method invocation.

*

* @throws Exception Failed to invoke method.*/

public Object invoke(Invocation invocation) throws Exception;

}

A invoker extends RemoteEven if the implementation is local

A invoker extends RemoteEven if the implementation is local

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 39/166

 New York, March 2003 9 - Client Side JBoss"

3920032003 ©© JBoss GroupJBoss Group

JBoss 3.0 and detached invokers 

ß In 3.0 all components are Mbeans with an object name

• The proxies know about the objectName and sendmethodInvocations that contain it

• JMX is used as a bus (we go through jmx.invoke())

ß Multiple invokers per component

• Deploy a component, it can use the existing RMI/JRMP, RMI/IIOP,SOAP, JMS invokers without additional code

ß One invoker of each type per node, removable at the node level. In2.x this is done per component

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 40/166

 New York, March 2003 9 - Client Side JBoss"

4020032003 ©© JBoss GroupJBoss Group

Conclusion: client side 

ß The client side when in java is a serialized object

• That is generated on the server 

• Serialized to the client

• Made of dynamic proxies and a stack of client interceptors

•  An invoker to the target JMX node

ß ANY MBEAN can have a stack of proxy that generate invocations• Encode in additional interceptor domain specific behavior 

• This is exactly what the client interceptors do for EJB behavior 

• The EJB nature of the proxy is one interceptor.

• Works for Remote and standard interfacesß Extend for custom local behavior 

• Cache, validation, clustering, transactions, security

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 41/166

Copyright JBoss GroupCopyright JBoss Group

The server side

Detached Invokers,The M-Bus, Server InterceptorsPlugins, Adanced Aspect Oriented Programming

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 42/166

 New York, March 2003 9 - Client Side JBoss"

4220032003 ©© JBoss GroupJBoss Group

Server Side creation of Invocation 

RMI Local

CLIENT VM

Invocation

Invocation

Invocation

 We will now look

at the creation

of Invocation in

the server 

 We will now look

at the creation

of Invocation in

the server 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 43/166

 New York, March 2003 9 - Client Side JBoss"

4320032003 ©© JBoss GroupJBoss Group

JBoss 2.x series and direct connectors 

ß The ContainerInvoker unwraps the RemoteMethodInvocation to

create a MethodInvocationß This is passed to the container after establishing the call context

Call

Proxy Container interceptors

TargetBean

CLIENT SERVER/CONTAINER  

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 44/166

 New York, March 2003 9 - Client Side JBoss"

4420032003 ©© JBoss GroupJBoss Group

JBoss 3.x series and detached invokers 

ß The proxy talks to an invoker, himself an MBean in the core

• This is the M-Bus viewß The server does a lookup on the MBean

Call

Proxy

Container 

interceptors

Target

Bean

CLIENT SERVER/CONTAINER  

JMX

Invoker 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 45/166

 New York, March 2003 9 - Client Side JBoss"45

20032003 ©© JBoss GroupJBoss Group

JRMPInvoker 

package org.jboss.invocation.jrmp.server;

 /**

* The JRMPInvoker is an RMI implementation that can generate Invocations

* from RMI/JRMP into the JMX base.

*

* @author <a href="mailto:[email protected]>Marc Fleury</a>

* @version $Revision: 1.17 $

*

* <p><b>Revisions:</b><br>

* <p><b>2002/01/13: Sacha Labourey</b>

* <ol>* <li>Make the exported RemoteStub available. For the clustering we need to

* distribute the stub to the other nodes of the cluster. Sending the

* RemoteServer directly fails.</li>

* </ol>

*/

public class JRMPInvoker 

extends RemoteServer 

implements Invoker, JRMPInvokerMBean, MBeanRegistration

{

package org.jboss.invocation.jrmp.server;

 /**

* The JRMPInvoker is an RMI implementation that can generate Invocations* from RMI/JRMP into the JMX base.

*

* @author <a href="mailto:[email protected]>Marc Fleury</a>

* @version $Revision: 1.17 $

*

* <p><b>Revisions:</b><br>

* <p><b>2002/01/13: Sacha Labourey</b>

* <ol>

* <li>Make the exported RemoteStub available. For the clustering we need to

* distribute the stub to the other nodes of the cluster. Sending the

* RemoteServer directly fails.</li>

* </ol>

*/

public class JRMPInvoker 

extends RemoteServer 

implements Invoker, JRMPInvokerMBean, MBeanRegistration

{

JRMPInvoker is a real invoker 

and a real RMI server 

JRMPInvoker is a real invoker 

and a real RMI server 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 46/166

 New York, March 2003 9 - Client Side JBoss"46

20032003 ©© JBoss GroupJBoss Group

JRMPInvoker 

 // The MBean Server 

protected MBeanServer server;

protected ObjectName serviceName;

public void start() throws Exception {

// Export references to the bean

Registry.bind(serviceName, delegateInvoker);

try {

// Export CI

exportCI();

InitialContext context = new InitialContext();

// Bind the invoker in the JNDI invoker naming space

rebind(

// The context

context,

// It should look like so "invokers/<name>/jrmp"

"invokers/"+InetAddress.getLocalHost().getHostName()+"/jrmp",

// The bare invoker 

delegateInvoker);

if (log.isDebugEnabled())log.debug("Bound JRMP invoker for JMX node");

}

 // The MBean Server 

protected MBeanServer server;

protected ObjectName serviceName;

public void start() throws Exception {

// Export references to the bean

Registry.bind(serviceName, delegateInvoker);

try {

// Export CI

exportCI();

InitialContext context = new InitialContext();

// Bind the invoker in the JNDI invoker naming space

rebind(

// The context

context,

// It should look like so "invokers/<name>/jrmp"

"invokers/"+InetAddress.getLocalHost().getHostName()+"/jrmp",

// The bare invoker 

  delegateInvoker);

if (log.isDebugEnabled())

log.debug("Bound JRMP invoker for JMX node");}

The invoker is “exported” to the

system under a known naming

schema, it is not tied to a bean

The invoker is “exported” to the

system under a known naming

schema, it is not tied to a bean

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 47/166

 New York, March 2003 9 - Client Side JBoss"47

20032003 ©© JBoss GroupJBoss Group

JRMPInvoker 

public Object invoke(Invocation invocation) throws Exception {

ClassLoader oldCl = Thread.currentThread().getContextClassLoader();try

{

// Deserialize the transaction if it is there

invocation.setTransaction(importTPC(((MarshalledInvocation)invocation).getTransactionPropagationContext()));

// Extract the ObjectName, the rest is still marshalled

ObjectName mbean = new ObjectName((String) invocation.getObjectName());

 // The cl on the thread should be set in another interceptor 

Object obj = server.invoke(mbean,

new Object[] {invocation},

Invocation.INVOKE_SIGNATURE);

return new MarshalledObject(obj);}

public Object invoke(Invocation invocation) throws Exception {

ClassLoader oldCl = Thread.currentThread().getContextClassLoader();

try

{

// Deserialize the transaction if it is there

invocation.setTransaction(importTPC(((MarshalledInvocation)invocation).getTransactionPropagationContext()));

// Extract the ObjectName, the rest is still marshalled

ObjectName mbean = new ObjectName((String) invocation.getObjectName());

 // The cl on the thread should be set in another interceptor 

Object obj = server.invoke(mbean,

new Object[] {invocation},

Invocation.INVOKE_SIGNATURE);

return new MarshalledObject(obj);

}The M-Bus is

nothing more

than invoking

the server itself 

The M-Bus is

nothing more

than invoking

the server itself 

Each invocation

specifies an

ObjectName this

is the basis for 

detaching

Each invocationspecifies an

ObjectName this

is the basis for 

detaching

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 48/166

 New York, March 2003 9 - Client Side JBoss"48

20032003 ©© JBoss GroupJBoss Group

Server Side creation of Invocation 

ß An invoker talks to the bus,

• Server.invoke(MBeanName, …)• Information is parsed from the Invocation

• What client generates it is irrelevant

• What gates generates it is irrelevant

RMI Local

InvocationInvocation

The gate is

irrelevant only

the standalone

message counts

The gate is

irrelevant only

the standalone

message counts

Let’s focus on

what is in the

“Container”

Let’s focus on

what is in the

“Container”

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 49/166

 New York, March 2003 9 - Client Side JBoss"49

20032003 ©© JBoss GroupJBoss Group

JBoss: Generalized AOP 

ß Theory behind EJB: Aspect Oriented Programming (AOP)

• Indirection• MetaLevel programming

ß Indirection

• Indirection means that a call on the proxy doesn’t go directly on the

target•  A server interposes on the call and can do “indirected work”

ß MetaLevel

• Means that the work performed in indirection is never on the “body”

of the code• It is about additional information: transactional behavior, persistent

behavior.

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 50/166

 New York, March 2003 9 - Client Side JBoss"50

20032003 ©© JBoss GroupJBoss Group

The Message 

ß Putting interceptors one behind the other works because we work

on a de-typed interceptor chain.• The interceptors do not need to know about the interface/client

• We build those interceptors in complete oblivion of the bean the user 

will deploy at the end

• Each works on a type that is independent of the target type• WYSIWYG class development

ß JBOSS IS BASED INTERNALLY ON A COMMAND PATTERN, THECOMMAND IS THE Invocation OBJECT, A SELF CONTAINEDDESCRIPTION OF AN INVOCATION

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 51/166

 New York, March 2003 9 - Client Side JBoss"51

20032003 ©© JBoss GroupJBoss Group

ContainerFactory MBean 

ß Deployment of an EJB module is handled by an Mbean

• org.jboss.ejb.ContainerFactory• org.jboss.ejb.ContainerFactoryMBean

• Replaced by org.jboss.ejb.EJBDeployer in 3.x

ß It creates and initializes a container for each EJB in the deployment module

• This is where the externalization of container configuration is handled

• Verification of the EJBs is also performed at deployment timeß Its two primary operations are

• public void deploy(String url, String appId)

throws MalformedURLException, DeploymentException;

• public void undeploy(String url)

throws MalformedURLException, DeploymentException;

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 52/166

 New York, March 2003 9 - Client Side JBoss"52

20032003 ©© JBoss GroupJBoss Group

The EJB Container 

ß The common framework for EJB containers is defined by the

abstract container class• org.jboss.ejb.Container 

ß The container itself does not perform much work other thanconnecting the various behavioral components together 

• One expection is the setup of the JNDI enterprise naming context for the EJB

•  java:comp/env

ß Implementations of the behavioral components are referred to asplugins, because you can plug in a new implementation by

changing the container configuration.

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 53/166

 New York, March 2003 9 - Client Side JBoss"53

20032003 ©© JBoss GroupJBoss Group

The EJB Container Types 

ß Four subclasses of the Container class handle the particular bean

types• org.jboss.ejb.EntityContainer handles javax.ejb.EntityBean

• org.jboss.ejb.StatelessSessionContainer handles Stateless

 javax.ejb.SessionBean

• org.jboss.ejb.StatelfulSessionContainer handles Stateful javax.ejb.SessionBean

• org.jboss.ejb.MessageDrivenContainer handles

 javax.ejb.MessageDrivenBean

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 54/166

 New York, March 2003 9 - Client Side JBoss"54

20032003 ©© JBoss GroupJBoss Group

Container Plug-ins 

ß A good deal of the EJB Container behavior is determined by its

configurable plug-insß The ContainerPlugin interface is the parent interface of all

container plug-in interfaces.

• It provides a callback that allows a container to provide each of its

plug-ins a pointer to the container the plug-in is working on behalf of.

public interface ContainerPlugin extends org.jboss.util.Service

{

public void setContainer(Container con);

}

public interface ContainerPlugin extends org.jboss.util.Service

{

public void setContainer(Container con);

}

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 55/166

 New York, March 2003 9 - Client Side JBoss"55

20032003 ©© JBoss GroupJBoss Group

Container Interceptors 

ß The Interceptors associated with a container form a linked-list structure throughwhich MethodInvocation objects pass

ß The first interceptor in the chain is invoked when a ContainerInvoker passes aMethodInvocation to the container 

ß The last interceptor invokes the business method on the bean

ß Advantages of an Interceptor pattern include

• Flexibility in the arrangement of interceptors

• Clear functional distinction between different interceptors.

• For example, logic for transaction and security is cleanly separated between

the TXInterceptor and SecurityInterceptor respectively 

ß If any of the interceptors fail, the call is terminated at that point.

• This is a fail-quickly type of semantic

• For example, if a secured EJB is access without proper permissions, the call will

fail as the SecurityInterceptor before any transactions are started or instance

caches are updated

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 56/166

 New York, March 2003 9 - Client Side JBoss"56

20032003 ©© JBoss GroupJBoss Group

Interceptors 

ß Pluggable approach to indirection implementation

BeanContainer Factory Jboss.xml

Jdk1.2 invocation handler 

Logger 

Security

Stateless session instance acquisition

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 57/166

 New York, March 2003 9 - Client Side JBoss"57

20032003 ©© JBoss GroupJBoss Group

Interceptor 

package org.jboss.ejb;

public interface Interceptor extends ContainerPlugin

{

public void setNext(Interceptor interceptor);

public Interceptor getNext();

public Object invokeHome(Invocation mi) throws Exception;

public Object invoke(Invocation mi) throws Exception;

}

package org.jboss.ejb;

public interface Interceptor extends ContainerPlugin{

public void setNext(Interceptor interceptor);

public Interceptor getNext();

public Object invokeHome(Invocation mi) throws Exception;

public Object invoke(Invocation mi) throws Exception;

}

Tx lockconnection syncsecurity Relationcache call

Each implements

Interceptor 

Each implements

Interceptor 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 58/166

 New York, March 2003 9 - Client Side JBoss"58

20032003 ©© JBoss GroupJBoss Group

AbstractInterceptor 

package org.jboss.ejb.plugins;

public abstract class AbstractInterceptor implements Interceptor 

{

protected Interceptor nextInterceptor;

// Interceptor implementation ------------------------------------

public abstract void setContainer(Container container);

public abstract Container getContainer();

public void setNext(Interceptor interceptor) { nextInterceptor = interceptor; }

public Interceptor getNext() { return nextInterceptor; }

public void init() throws Exception {}

public void start() throws Exception {}

public void stop() {}

public void destroy(){ }

…// Removed the home

public Object invoke(Invocation mi)

throws Exception{

return getNext().invoke(mi);

}

}

package org.jboss.ejb.plugins;

public abstract class AbstractInterceptor 

implements Interceptor 

{

protected Interceptor nextInterceptor;

// Interceptor implementation ------------------------------------

public abstract void setContainer(Container container);

public abstract Container getContainer();

public void setNext(Interceptor interceptor) { nextInterceptor = interceptor; }

public Interceptor getNext() { return nextInterceptor; }

public void init() throws Exception {}

public void start() throws Exception {}

public void stop() {}

public void destroy(){ }

…// Removed the home

public Object invoke(Invocation mi)

throws Exception{

return getNext().invoke(mi);

}

}

Tx lock connection syncsecurity Relationcache call

Each extends

AbstractInterceptor 

Each extends

AbstractInterceptor 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 59/166

 New York, March 2003 9 - Client Side JBoss"59

20032003 ©© JBoss GroupJBoss Group

Interceptors 

ß In ONE VM, Stack the layers up!

VM

Call

Flow

 No network JSP->EJB

JSP/Servlet

EJB

EJB Persistence

Bean

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 60/166

 New York, March 2003 9 - Client Side JBoss"60

20032003 ©© JBoss GroupJBoss Group

Interceptors 

ß Configure per bean

• Each bean comes with it’s own jboss.xml file and configuration• The server has a different personality for all servers deployed

• Ex: Stand Alone Server, embedded application

Includes all

Transactional

And Persistence

no

 persistence

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 61/166

 New York, March 2003 9 - Client Side JBoss"61

20032003 ©© JBoss GroupJBoss Group

Container Interceptors 

ß The “in and out” mapping to “try-finally”

• In maps to a “try”•  All the interceptor code on the way in is done

• The next interceptor is invoked before the call returns

• Out maps to a “finally”

• On the way back up in the interceptor stack we go through thefinally blocks

• Readable code with separated in and out blocks

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 62/166

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 63/166

 New York, March 2003 9 - Client Side JBoss"63

20032003 ©© JBoss GroupJBoss Group

An EJB container 

ß An EJB container is the sum of 

• Interceptors• Plugins per container 

• Mbeans in the server 

Tx lock connection syncsecurity Relationcache call

TxMonTxMon

Bean

Lock

Bean

Lock

DataSourceDataSource

CacheCacheCMP

engine

CMP

engine

Mbeans exist

independently of 

the container 

Mbeans exist

independently of 

the container 

Plug-ins only exist

in the context of 

the container 

Plug-ins only exist

in the context of 

the container 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 64/166

 New York, March 2003 9 - Client Side JBoss"64

20032003 ©© JBoss GroupJBoss Group

An Entity Bean Creation Walkthrough 

ß Deployment

• ContainerFactory• Container configuration

• EJB home proxy creation and export

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 65/166

 New York, March 2003 9 - Client Side JBoss"65

20032003 ©© JBoss GroupJBoss Group

Deployment (1/3) 

ß Put an EJB in the deploy file

• Thread picks it up• Container Factory invoked

• Container stack is created using externalized configuration

Deployer 

/deploy

Container 

Factory

JB 3 0 U ifi d D l i

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 66/166

 New York, March 2003 9 - Client Side JBoss"66

20032003 ©© JBoss GroupJBoss Group

JBoss3.0: Unified Deployer overview 

ß Here the containerFactory is really a “EJBDeployer”

• The deployer takes care of the classloaders in 2.x• In 3.x this is done before in a “unified deployer”

• The UD generates the classloaders to be shared across all stacks in

Jboss, server and application alike

ß

Roughly the same logic of container creation applies, however • Client stacks have been externalized

• Multi-invokers are now supported

D l t (2/3)

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 67/166

 New York, March 2003 9 - Client Side JBoss"67

20032003 ©© JBoss GroupJBoss Group

Deployment (2/3) 

ß Home is created with Proxy

Deployer 

/deploy

Container 

Factory

Proxy

Factory

Proxy Container 

D l t (3/3)

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 68/166

 New York, March 2003 9 - Client Side JBoss"68

20032003 ©© JBoss GroupJBoss Group

Deployment (3/3) 

ß And The home proxy is registered in JNDI

• home is available in JNDI under the EJB name• Jboss.xml was used to configure container and JNDI etc

• Done

Deployer 

/deploy

Container 

Factory

HomeProxy

Container 

JNDI

L I t t

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 69/166

 New York, March 2003 9 - Client Side JBoss"69

20032003 ©© JBoss GroupJBoss Group

Log Interceptor 

org.jboss.ejb.plugins.LogInterceptor ß 1- Logging

• Log the call and what was in it

• The arguments

• The method name

•  All that dependent on the flag container config debug flag or log4j priority

invoke(..) Tx lock connection syncsecurity Relationcache callLog

Invocation

S it I t t

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 70/166

 New York, March 2003 9 - Client Side JBoss"70

20032003 ©© JBoss GroupJBoss Group

Security Interceptor 

ß 2-Security

• Enforces J2EE declarative security

•  Authentication

• Role-based permissions

invoke(..) Tx lock connection syncsecurity Relationcache callLog

Invocation

S it I t t

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 71/166

 New York, March 2003 9 - Client Side JBoss"71

20032003 ©© JBoss GroupJBoss Group

Security Interceptor 

package org.jboss.ejb.plugins;

 /** The SecurityInterceptor is where the EJB 2.0 declarative security modelis enforced. This is where the caller identity propagation is controlled as well.

*/

public class SecurityInterceptor extends AbstractInterceptor 

{

protected AuthenticationManager securityManager;

protected RealmMapping realmMapping;

protected Principal runAsRole;

public void setContainer(Container container)

{

this.container = container;

BeanMetaData beanMetaData = container.getBeanMetaData();

SecurityIdentityMetaData secMetaData = beanMetaData.getSecurityIdentityMetaData();

if( secMetaData != null && secMetaData.getUseCallerIdentity() == false )

{ String roleName = secMetaData.getRunAsRoleName();

runAsRole = new SimplePrincipal(roleName);

}

securityManager = container.getSecurityManager();

realmMapping = container.getRealmMapping();

}

package org.jboss.ejb.plugins;

 /** The SecurityInterceptor is where the EJB 2.0 declarative security model

is enforced. This is where the caller identity propagation is controlled as well.

*/

public class SecurityInterceptor extends AbstractInterceptor 

{

protected AuthenticationManager securityManager ;

protected RealmMapping realmMapping;

protected Principal runAsRole;

public void setContainer(Container container)

{

this.container = container;

BeanMetaData beanMetaData = container.getBeanMetaData();

SecurityIdentityMetaData secMetaData = beanMetaData.getSecurityIdentityMetaData();

if( secMetaData != null && secMetaData.getUseCallerIdentity() == false )

{

String roleName = secMetaData.getRunAsRoleName();

runAsRole = new SimplePrincipal(roleName);

}

securityManager = container.getSecurityManager();

realmMapping = container.getRealmMapping();

}

All

configuration

comes from the

“static”

container 

All

configuration

comes from the

“static”

container 

Sec rit Interceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 72/166

 New York, March 2003 9 - Client Side JBoss"72

20032003 ©© JBoss GroupJBoss Group

Security Interceptor 

public Object invoke(Invocation mi) throws Exception

{

// Authenticate the subject and apply any declarative security checkscheckSecurityAssociation(mi, false);

/* If a run-as role was specified, push it so that any calls made

by this bean will have the runAsRole available for declarative

security checks.

*/

if( runAsRole != null )

{

SecurityAssociation.pushRunAsRole(runAsRole);}

try

{

Object returnValue = getNext().invoke(mi);

return returnValue;

}

finally{

if( runAsRole != null )

{

SecurityAssociation.popRunAsRole();

}

public Object invoke(Invocation mi) throws Exception

{

// Authenticate the subject and apply any declarative security checks

  checkSecurityAssociation(mi, false);

/* If a run-as role was specified, push it so that any calls made

by this bean will have the runAsRole available for declarative

security checks.

*/

if( runAsRole != null )

{

SecurityAssociation.pushRunAsRole(runAsRole);}

try

{

Object returnValue = getNext().invoke(mi);

return returnValue;

}

finally

{

if( runAsRole != null )

{

SecurityAssociation.popRunAsRole();

}

Security Interceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 73/166

 New York, March 2003 9 - Client Side JBoss"73

20032003 ©© JBoss GroupJBoss Group

Security Interceptor 

/** The EJB 2.0 declarative security algorithm:

1. Authenticate the caller using the principal and credentials in the MethodInfocation

2. Validate access to the method by checking the principal's roles againstthose required to access the method.

*/

private void checkSecurityAssociation(Invocation mi, boolean home)

throws Exception

{

Principal principal = mi.getPrincipal();

Object credential = mi.getCredential();

// If there is not a security manager then there is no authentication requiredif (securityManager == null)

{

// Allow for the progatation of caller info to other beans

SecurityAssociation.setPrincipal( principal );

SecurityAssociation.setCredential( credential );

return;

}// Check the security info from the method invocation

if( securityManager.isValid(principal, credential) == false )

{

SecurityException e = new SecurityException(msg);

throw new RemoteException("checkSecurityAssociation", e);

}…

   /** The EJB 2.0 declarative security algorithm:

1. Authenticate the caller using the principal and credentials in the MethodInfocation

2. Validate access to the method by checking the principal's roles against

those required to access the method.

*/

private void checkSecurityAssociation(Invocation mi, boolean home)

throws Exception

{

Principal principal = mi.getPrincipal();

Object credential = mi.getCredential();

// If there is not a security manager then there is no authentication requiredif (securityManager == null)

{

// Allow for the progatation of caller info to other beans

SecurityAssociation.setPrincipal( principal );

SecurityAssociation.setCredential( credential );

return;

}

// Check the security info from the method invocation

if( securityManager.isValid(principal, credential) == false )

{

SecurityException e = new SecurityException(msg);

throw new RemoteException("checkSecurityAssociation", e);

}…

Transaction Interceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 74/166

 New York, March 2003 9 - Client Side JBoss"74

20032003 ©© JBoss GroupJBoss Group

Tx lock connection syncsecurity Relationcache callLog

Transaction Interceptor 

org.jboss.ejb.plugins.TxInterceptorCMT ß 3- Transaction (CMT)

• Does the methodA require a Tx?

• If So start one, if not maybe suspend it

invoke(..)

Invocation

TXInterceptorCMT

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 75/166

 New York, March 2003 9 - Client Side JBoss"75

20032003 ©© JBoss GroupJBoss Group

TXInterceptorCMT 

package org.jboss.ejb.plugins;

public class TxInterceptorCMT extends AbstractTxInterceptor {

private Object runWithTransactions(boolean remoteInvocation, Invocation mi) throws Exception

{

// Old transaction is the transaction that comes with the MI

Transaction oldTransaction = mi.getTransaction();

// New transaction is the new transaction this might start

Transaction newTransaction = null;

// Thread arriving must be clean (jboss doesn't set the thread// previously). However optimized calls come with associated

// thread for example. We suspend the thread association here, and

// resume in the finally block of the following try.

Transaction threadTx = tm.suspend();

if( trace )

log.trace("Thread came in with tx " + threadTx);

try

{

switch (transType)

{

package org.jboss.ejb.plugins;

public class TxInterceptorCMT extends AbstractTxInterceptor {

private Object runWithTransactions(boolean remoteInvocation, Invocation mi) throws Exception

{

// Old transaction is the transaction that comes with the MI

Transaction oldTransaction = mi.getTransaction();

// New transaction is the new transaction this might start

Transaction newTransaction = null;

// Thread arriving must be clean (jboss doesn't set the thread// previously). However optimized calls come with associated

// thread for example. We suspend the thread association here, and

// resume in the finally block of the following try.

Transaction threadTx = tm.suspend();

if( trace )

log.trace("Thread came in with tx " + threadTx);

try

{  switch (transType)

{

Transtype is the

declarative

transactional tag

Transtype is the

declarative

transactional tag

TXInterceptorCMT

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 76/166

 New York, March 2003 9 - Client Side JBoss"76

20032003 ©© JBoss GroupJBoss Group

TXInterceptorCMT 

case MetaData.TX_NOT_SUPPORTED:

// Do not set a transaction on the thread even if in MI, just run

return invokeNext(remoteInvocation, mi, false);

case MetaData.TX_REQUIRED:

if (oldTransaction == null) { // No tx running

// Create tx

tm.begin();

// get the tx

newTransaction = tm.getTransaction();

// Let the method invocation know

mi.setTransaction(newTransaction);

}

else { // We have a tx propagated

// Associate it with the thread

tm.resume(oldTransaction);

}

// Continue invocation

try

{

return invokeNext(remoteInvocation, mi, newTransaction != null);

}

case MetaData.TX_NOT_SUPPORTED:

// Do not set a transaction on the thread even if in MI, just run

return invokeNext(remoteInvocation, mi, false);

case MetaData.TX_REQUIRED:

if (oldTransaction == null) { // No tx running

// Create tx

  tm.begin();

// get the tx

newTransaction = tm.getTransaction();

// Let the method invocation know

mi.setTransaction(newTransaction);

}

else { // We have a tx propagated

// Associate it with the thread

tm.resume(oldTransaction);

}

// Continue invocationtry

{

return invokeNext(remoteInvocation, mi, newTransaction != null);

}

TXInterceptorCMT

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 77/166

 New York, March 2003 9 - Client Side JBoss

"77

20032003 ©© JBoss GroupJBoss Group

TXInterceptorCMT 

case MetaData.TX_SUPPORTS:

{

// Associate old transaction with the thread// Some TMs cannot resume a null transaction and will throw

// an exception (e.g. Tyrex), so make sure it is not null

if (oldTransaction != null)

tm.resume(oldTransaction);

try

{

return invokeNext(remoteInvocation, mi, false);}

finally

{

tm.suspend();

}

// Even on error we don't do anything with the tx, we didn't start it

}

case MetaData.TX_SUPPORTS:

{

// Associate old transaction with the thread

// Some TMs cannot resume a null transaction and will throw

// an exception (e.g. Tyrex), so make sure it is not null

if (oldTransaction != null)

tm.resume(oldTransaction);

try

{

  return invokeNext(remoteInvocation, mi, false);}

finally

{

tm.suspend();

}

// Even on error we don't do anything with the tx, we didn't start it

}

TXInterceptorCMT

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 78/166

 New York, March 2003 9 - Client Side JBoss

"78

20032003 ©© JBoss GroupJBoss Group

TXInterceptorCMT 

case MetaData.TX_REQUIRES_NEW:

{

// Always begin a transaction

tm.begin();

// get it

newTransaction = tm.getTransaction();

// Set it on the method invocation

mi.setTransaction(newTransaction);

// Continue invocationtry

{

return invokeNext(remoteInvocation, mi, true);

}

case MetaData.TX_REQUIRES_NEW:

{

// Always begin a transaction

tm.begin();

// get it

newTransaction = tm.getTransaction();

// Set it on the method invocation

mi.setTransaction(newTransaction);

// Continue invocationtry

{

return invokeNext(remoteInvocation, mi, true);

}

Lock Interceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 79/166

 New York, March 2003 9 - Client Side JBoss

"79

20032003 ©© JBoss GroupJBoss Group

Tx lock connection syncsecurity Relationcache callLog

Lock Interceptor 

org.jboss.ejb.plugins.EntityLockInterceptor 

ß 4 - Instance Locking

• Lock the method and handle transaction synchronization• Pessimistic locking

Bean

Instance

invoke(..)

Invocation

STOPSTOP

Locking

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 80/166

 New York, March 2003 9 - Client Side JBoss

"80

20032003 ©© JBoss GroupJBoss Group

Locking 

ß Locking is required to enforce the EJB semantics a bean developer expects

• Only one thread is active in a bean instance

• Only one transaction is actively associated with the bean instance

ß Support for externalization of the locking policy implementation is handled bytwo classes

• org.jboss.ejb.BeanLockManager 

• org.jboss.ejb.BeanLock

• BeanLock is what you can change

• org.jboss.ejb.plugins.lock.BeanLockSupport is an abstract BeanLock 

implementation helper class

ß Still quite complicated to do

• Locking is used from multiple interceptors and related objects

• Difficult to devise a new policy implementation without understanding all of the

parties involved

ß GREAT GAIN, GREAT DANGER, CALL THE EXPERTS!

org jboss ejb BeanLockManager

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 81/166

 New York, March 2003 9 - Client Side JBoss

"81

20032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.BeanLockManager 

ß Basically just a map for BeanLocks

• Externalizes the type of BeanLock implementation• The get lock operation will create a BeanLock if one does not exist

for the given key

• The get operation increments the BeanLock reference count

• The remove operation decrements the BeanLock reference count• When reference count is mapping between lock and key is

removed 

• Has method reentrancy flag

•  Are methods reentrant for the associated bean (Entity only)

• Has transaction synchronization timeout

• How long will a call wait for the associated transaction to be

scheduled 

org jboss ejb BeanLock Interface

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 82/166

 New York, March 2003 9 - Client Side JBoss

"82

20032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.BeanLock Interface 

public interface BeanLock

{

public Object getId();public void setId(Object id);

public void setReentrant(boolean reentrant);

public void setTimeout(int timeout);

public void sync();

public void releaseSync();

public void schedule(MethodInvocation mi) throws Exception;

public void setTransaction(Transaction tx);

public Transaction getTransaction();

public void endTransaction(Transaction tx);

public void wontSynchronize(Transaction tx); public boolean isMethodLocked();

public int getNumMethodLocks();

public void addMethodLock();

public void releaseMethodLock();

public void addRef();

public void removeRef();

public int getRefs();

}

public interface BeanLock

{

public Object getId();public void setId(Object id);

public void setReentrant(boolean reentrant);

public void setTimeout(int timeout);

public void sync();

public void releaseSync();

public void schedule(MethodInvocation mi) throws Exception;

public void setTransaction(Transaction tx);public Transaction getTransaction();

public void endTransaction(Transaction tx);

public void wontSynchronize(Transaction tx); public boolean isMethodLocked();

public int getNumMethodLocks();

public void addMethodLock();

public void releaseMethodLock();

public void addRef();public void removeRef();

public int getRefs();

}

BeanLock Discussion

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 83/166

 New York, March 2003 9 - Client Side JBoss

"83

20032003 ©© JBoss GroupJBoss Group

BeanLock Discussion 

ß The get/set ID methods

• BeanLocks have a key associated with them. This is set on creationby the BeanLockManager 

ß setReentrant

• Was the entity bean the BeanLockManager is associated with

marked as reentrant

ß setTimeout

•  A transaction synchronization timeout in milliseconds

ß The sync/releaseSync acquire and release the lock mutex

ß The addRef/removeRef/getRefs methods

• Increment, decrement and access the lock reference count

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 84/166

BeanLock Discussion

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 85/166

 New York, March 2003 9 - Client Side JBoss

"85

20032003 ©© JBoss GroupJBoss Group

BeanLock Discussion 

Call Serialization ß The method lock related methods support serialization of threads

during method dispatchß The addMethodLock method

• Increments the active call count

ß The releaseMethodLock method

• Decrements the active call countß The isMethodLocked method

• Is the active call count > 0

ß The getNumMethodLocks method

• Get the count of active calls• This should only be > 1 for reentrant beans

BeanLock Discussion

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 86/166

 New York, March 2003

9 - Client Side JBoss

"86

20032003 ©© JBoss GroupJBoss Group

BeanLock Discussion 

Scheduling ß The schedule(MethodInvocation mi) method

• This is where the lock policy implementation resides• When schedule returns successfully (no Exception)

• The calling thread must have exclusive access to the target bean

instance for the given method invocation

• The transaction associated with the thread must be the only transaction the target bean instance is associated with

Scheduling threads and concurrency

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 87/166

 New York, March 2003

9 - Client Side JBoss

"87

20032003 ©© JBoss GroupJBoss Group

Scheduling threads and concurrency org.jboss.ejb.plugins.EntityLockInterceptor 

public Object invoke(Invocation mi) throws Exception {

// The key.Object key = (CacheKey) mi.getId();

// The lock.

BeanLock lock ;

{

lock = (BeanLock)container.getLockManager().getLock(key);

lock.schedule(mi);

try { return getNext().invoke(mi); }

finally {

// we are done with the method, decrease the count, if it reaches 0 it will wake up the next threadlock.sync();

lock.releaseMethodLock();

lock.releaseSync();

}

 public Object invoke(Invocation mi) throws Exception {

// The key.

Object key = (CacheKey) mi.getId();

// The lock.

BeanLock lock ;

{

lock = (BeanLock)container.getLockManager().getLock(key);

  lock.schedule(mi);

  try { return getNext().invoke(mi); }

finally {

// we are done with the method, decrease the count, if it reaches 0 it will wake up the next threadlock.sync();

lock.releaseMethodLock();

lock.releaseSync();

}

Simple Pessimistic Locking

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 88/166

 New York, March 2003

9 - Client Side JBoss

"88

20032003 ©© JBoss GroupJBoss Group

Simple Pessimistic Locking org.jboss.ejb.plugins.lock.SimplePessimisticEJBLock 

 /**

* @author <a href="[email protected]">Bill Burke</a>

* @author <a href="[email protected]">Marc Fleury</a>

* @version $Revision: 1.9.2.13$

*/

public class SimplePessimisticEJBLock

extends BeanLockSupport

{

… Continued

 /**

* @author <a href="[email protected]">Bill Burke</a>

* @author <a href="[email protected]">Marc Fleury</a>

* @version $Revision: 1.9.2.13$*/

public class SimplePessimisticEJBLock

extends BeanLockSupport

{

… Continued

Simple Pessimistic Locking 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 89/166

 New York, March 2003

9 - Client Side JBoss

"89

20032003 ©© JBoss GroupJBoss Group

p gorg.jboss.ejb.plugins.lock.SimplePessimisticEJBLock 

 /**

* This is called up synchronization to notify the end of the transaction.

*/public void endTransaction(Transaction transaction)

{

//The tx is done

tx = null;

synchronized(lock) {lock.notifyAll();}

}

/**

* if we reach the count of zero it means the instance is free from threads

* (and reentrency) we wake up the next thread in the currentLock

*/

public void releaseMethodLock()

{

numMethodLocks--;

// Wake up a thread to do work on the instance within the current

// transaction

if (numMethodLocks ==0) synchronized(lock) {lock.notifyAll();}

}

 /**

* This is called up synchronization to notify the end of the transaction.

*/

public void endTransaction(Transaction transaction)

{

//The tx is done

tx = null;

synchronized(lock) {lock.notifyAll();}

}

/*** if we reach the count of zero it means the instance is free from threads

* (and reentrency) we wake up the next thread in the currentLock

*/

public void releaseMethodLock()

{

numMethodLocks--;

// Wake up a thread to do work on the instance within the current

// transaction

if (numMethodLocks ==0) synchronized(lock) {lock.notifyAll();}

}

notifyAll

means a

rush of 

threads

FIFO pessimistic scheduling 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 90/166

 New York, March 2003

9 - Client Side JBoss

"90

20032003 ©© JBoss GroupJBoss Group

p gorg.jboss.ejb.plugins.lock.QueudPessimisticEJBLock 

 /**

* This class is holds threads awaiting the transactional lock to be free

* in a fair FIFO transactional queue. Non-transactional threads* are also put in this wait queue as well. Unlike SimplePessimisticEJBLock which notifies all

* threads on transaction completion, this class pops the next waiting transaction from the queue

* and notifies only those threads waiting associated with that transaction. This

* class should perform better than Simple on high contention loads.

*

* As of 04/10/2002, you can now specify in jboss.xml method attributes that define

* methods as read-only. read-only methods(and read-only beans) will release transactional

* locks at the end of the invocation. This decreases likelyhood of deadlock and increases

* performance.

*

* @author <a href="[email protected]">Marc Fleury</a>

* @author <a href="[email protected]">Bill Burke</a>

* @author <a href="[email protected]">Peter Murray</a>

*/

public class QueuedPessimisticEJBLock extends BeanLockSupport{

… Continued

 /**

* This class is holds threads awaiting the transactional lock to be free

* in a fair FIFO transactional queue. Non-transactional threads

* are also put in this wait queue as well. Unlike SimplePessimisticEJBLock which notifies all

* threads on transaction completion, this class pops the next waiting transaction from the queue

* and notifies only those threads waiting associated with that transaction. This

* class should perform better than Simple on high contention loads.

*

* As of 04/10/2002, you can now specify in jboss.xml method attributes that define

* methods as read-only. read-only methods(and read-only beans) will release transactional

* locks at the end of the invocation. This decreases likelyhood of deadlock and increases* performance.

*

* @author <a href="[email protected]">Marc Fleury</a>

* @author <a href="[email protected]">Bill Burke</a>

* @author <a href="[email protected]">Peter Murray</a>

*/

public class QueuedPessimisticEJBLock extends BeanLockSupport

{

… Continued

FIFO pessimistic scheduling 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 91/166

 New York, March 2003

9 - Client Side JBoss

"91

20032003 ©© JBoss GroupJBoss Group

p gorg.jboss.ejb.plugins.lock.QueudPessimisticEJBLock 

/*

* nextTransaction()

** nextTransaction will

* - set the current tx to null

* - schedule the next transaction by notifying all threads waiting on the transaction

* - setting the thread with the new transaction so there is no race with incoming calls

*/

protected void nextTransaction()

{

// is there a waiting list?

if (!txWaitQueue.isEmpty())

{

TxLock thelock = (TxLock) txWaitQueue.removeFirst();

txLocks.remove(thelock);

thelock.isQueued = false;

// The new transaction is the next one, important to set it up to avoid race with

// new incoming callsthis.tx = thelock.tx;

synchronized(thelock) { theLock.notifyAll();}

}

  /*

* nextTransaction()

*

* nextTransaction will

* - set the current tx to null

* - schedule the next transaction by notifying all threads waiting on the transaction

* - setting the thread with the new transaction so there is no race with incoming calls

*/

protected void nextTransaction()

{

// is there a waiting list?if (!txWaitQueue.isEmpty())

{

TxLock thelock = (TxLock) txWaitQueue.removeFirst();

txLocks.remove(thelock);

thelock.isQueued = false;

// The new transaction is the next one, important to set it up to avoid race with

// new incoming calls

this.tx = thelock.tx;

synchronized(thelock) { theLock.notifyAll();}

}

One first transaction getspulled up, implementing a line,

this is the FIFO behavior 

One first transaction getspulled up, implementing a line,

this is the FIFO behavior 

NotifyAll() applies only to

threads in this transaction

NotifyAll() applies only to

threads in this transaction

FIFO pessimistic scheduling 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 92/166

 New York, March 2003

9 - Client Side JBoss

"92

20032003 ©© JBoss GroupJBoss Group

p gorg.jboss.ejb.plugins.lock.QueudPessimisticEJBLock 

 /**

* releaseMethodLock*

* if we reach the count of zero it means the instance is free from threads (and reentrency)

* we wake up the next thread in the currentLock

*/

public void endInvocation(Invocation mi)

{

numMethodLocks--;

if (numMethodLocks == 0){

synchronized(methodLock) {methodLock.notify();}

if (isReadOnlyTxLock && mi.getTransaction() != null)

{

if (isReadOnlyTxLock)

{

endTransaction(mi.getTransaction());}

}

}

}

 /**

* releaseMethodLock

*

* if we reach the count of zero it means the instance is free from threads (and reentrency)

* we wake up the next thread in the currentLock

*/

public void endInvocation(Invocation mi)

{

numMethodLocks--;

if (numMethodLocks == 0){

synchronized(methodLock) {methodLock.notify();}

if (isReadOnlyTxLock && mi.getTransaction() != null)

{

if (isReadOnlyTxLock)

{

endTransaction(mi.getTransaction());

}

}

}

}

Only one thread gets

woken up within the same

transaction

SCALABILITY

Only one thread gets

woken up within the same

transaction

SCALABILITY

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 93/166

Entity Instance from cache 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 94/166

 New York, March 2003

9 - Client Side JBoss

"94

20032003 ©© JBoss GroupJBoss Group

yorg.jboss.ejb.plugins.EntityInstanceInterceptor 

public Object invoke(Invocation mi) throws Exception{

// The key

CacheKey key = (CacheKey) mi.getId();

// The context

EntityEnterpriseContext ctx = (EntityEnterpriseContext) container.getInstanceCache().get(key);

// Associate transaction, in the new design the lock already has the transaction from theprevious interceptor 

ctx.setTransaction(mi.getTransaction());

// Set the current security information

ctx.setPrincipal(SecurityAssociation.getPrincipal());

// Set context on the method invocation

mi.setEnterpriseContext(ctx);

boolean exceptionThrown = false;

try

{

return getNext().invoke(mi);

}

public Object invoke(Invocation mi) throws Exception{

// The key

CacheKey key = (CacheKey) mi.getId();

// The context

EntityEnterpriseContext ctx = (EntityEnterpriseContext) container.getInstanceCache().get(key);

// Associate transaction, in the new design the lock already has the transaction from theprevious interceptor 

ctx.setTransaction(mi.getTransaction());

// Set the current security informationctx.setPrincipal(SecurityAssociation.getPrincipal());

// Set context on the method invocation

mi.setEnterpriseContext(ctx);

boolean exceptionThrown = false;

try{

return getNext().invoke(mi);

}

This “context” is the

wrapper to the real

instance in cache

This “context” is the

wrapper to the real

instance in cache

Synchronization Interceptor 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 95/166

 New York, March 2003

9 - Client Side JBoss

"95

20032003

©©

 JBoss GroupJBoss Group

Tx lock connection syncsecurity Relationcache callLog

ß 6 - Instance Synchronization

• The container knows to refresh the state

• Uses transaction synchronization callback and commit option to synch DB

• Ensures state is “valid” , instance in memory is reflection of DB

invoke(..)

Invocation

Entity State-DB synchronization 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 96/166

 New York, March 2003

9 - Client Side JBoss

"9620032003 ©©

 JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntitySynchronizationInterceptor (load state logic)

public Object invoke(MethodInvocation mi)

throws Exception

{// We are going to work with the context a lot

EntityEnterpriseContext ctx = (EntityEnterpriseContext)mi.getEnterpriseContext();

// The Tx coming as part of the Method Invocation

Transaction tx = mi.getTransaction();

// Is my state valid?

if (!ctx.isValid()) {

// If not tell the persistence manager to load the state

((EntityContainer)getContainer()).getPersistenceManager().loadEntity(ctx);

// Now the state is valid

ctx.setValid(true);

}

public Object invoke(MethodInvocation mi)

throws Exception

{// We are going to work with the context a lot

EntityEnterpriseContext ctx = (EntityEnterpriseContext)mi.getEnterpriseContext();

// The Tx coming as part of the Method Invocation

Transaction tx = mi.getTransaction();

// Is my state valid?

if (!ctx.isValid()) {

// If not tell the persistence manager to load the state

((EntityContainer)getContainer()).getPersistenceManager().loadEntity(ctx);

// Now the state is valid

  ctx.setValid(true);

}

Entity State-DB synchronization 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 97/166

 New York, March 2003

9 - Client Side JBoss

"9720032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntitySynchronizationInterceptor (invocation and in return the registration)

 // Invocation with a running Transaction

if (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) {

try {

//Invoke down the chain

return getNext().invoke(mi);

}

finally {

// Do we have a valid bean (not removed)

if (ctx.getId() != null) {

// If the context was not invoked previously...

if (!ctx.isInvoked()) {

// It is now and this will cause ejbStore to be called...

ctx.setInvoked(true);

// ... on a transaction callback that we register here.

register(ctx, tx);

}

}

 // Invocation with a running Transaction

if (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) {

try {

//Invoke down the chain

  return getNext().invoke(mi);

}

finally {

// Do we have a valid bean (not removed)if (ctx.getId() != null) {

// If the context was not invoked previously...

if (!ctx.isInvoked()) {

// It is now and this will cause ejbStore to be called...

ctx.setInvoked(true);

// ... on a transaction callback that we register here.

register(ctx, tx);

}

}

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 98/166

ContainerInterceptor 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 99/166

 New York, March 2003

9 - Client Side JBoss

"9920032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.EntityContainer$ContainerInterceptor (Inner class, methods on the container)

// This is the last step before invocation - all interceptors are done

class ContainerInterceptor 

implements Interceptor {

…// snip

public Object invoke(MethodInvocation mi)

throws Exception

{

// Get method

Method m = (Method)beanMapping.get(mi.getMethod());

// Select instance to invoke (container or bean)

if (m.getDeclaringClass().equals(EntityContainer.class))

{

// Invoke and handle exceptions

try

{

return m.invoke(EntityContainer.this, new Object[] { mi });} catch (IllegalAccessException e)

{

// Throw this as a bean exception...(?)

throw new EJBException(e);

…// more catch

  // This is the last step before invocation - all interceptors are done

class ContainerInterceptor 

implements Interceptor 

{

…// snip

public Object invoke(MethodInvocation mi)

throws Exception

{

// Get method

Method m = (Method)beanMapping.get(mi.getMethod());

// Select instance to invoke (container or bean)

if (m.getDeclaringClass().equals(EntityContainer.class))

{

// Invoke and handle exceptions

try

{

  return m.invoke(EntityContainer.this, new Object[] { mi });

} catch (IllegalAccessException e)

{

// Throw this as a bean exception...(?)

throw new EJBException(e);

…// more catch

Call is fielded by

the container 

Call is fielded by

the container 

ContainerInterceptor 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 100/166

 New York, March 2003

9 - Client Side JBoss

"10

020032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.EntityContainer$ContainerInterceptor (methods in the bean)

else

{

//wire the transaction on the context, this is how the instance remember the txif (mi.getEnterpriseContext().getTransaction() == null)

mi.getEnterpriseContext().setTransaction(mi.getTransaction());

// Invoke and handle exceptions

try

{

return m.invoke(mi.getEnterpriseContext().getInstance(), mi.getArguments());} catch (IllegalAccessException e)

{// Throw this as a bean exception...(?)

throw new EJBException(e);

} catch (InvocationTargetException e)

{

Throwable ex = e.getTargetException();

if (ex instanceof EJBException)

throw (EJBException)ex;

else if (ex instanceof RuntimeException)

throw new EJBException((Exception)ex); // Transform runtime exception into what a bean *should* havethrown

else if (ex instanceof Exception)

throw (Exception)ex;

else

…//end

else

{

//wire the transaction on the context, this is how the instance remember the tx

if (mi.getEnterpriseContext().getTransaction() == null)

mi.getEnterpriseContext().setTransaction(mi.getTransaction());

// Invoke and handle exceptions

try

{

return m.invoke(mi.getEnterpriseContext().getInstance(), mi.getArguments());} catch (IllegalAccessException e)

{// Throw this as a bean exception...(?)

throw new EJBException(e);

} catch (InvocationTargetException e)

{

Throwable ex = e.getTargetException();

if (ex instanceof EJBException)

throw (EJBException)ex;

else if (ex instanceof RuntimeException)

throw new EJBException((Exception)ex); // Transform runtime exception into what a bean *should* havethrown

else if (ex instanceof Exception)

throw (Exception)ex;

else

…//end

Call is fielded by

the instance

Call is fielded by

the instance

Synchronization Interceptor Exit 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 101/166

 New York, March 2003

9 - Client Side JBoss

"10

120032003 ©© JBoss GroupJBoss Group

Tx lock connection syncsecurity Relationcache callLog

ß End of dive we are going back up!

ß

We register a callback with JTA• We will be notified of end of Tx

• Register with wrapper 

invoke(..)

Invocation

After invoke()

Or in finally()

Entity State-DB synchronization jb jb l i E i S h i i I

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 102/166

 New York, March 2003

9 - Client Side JBoss

"10

220032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntitySynchronizationInterceptor (invocation and in return the registration)

 // Invocation with a running Transaction

if (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) {

try {

//Invoke down the chain

return getNext().invoke(mi);

}

finally {

// Do we have a valid bean (not removed)

if (ctx.getId() != null) {

// If the context was not invoked previously...

if (!ctx.isInvoked()) {

// It is now and this will cause ejbStore to be called...

ctx.setInvoked(true);

// ... on a transaction callback that we register here.

register(ctx, tx);

}

}

 // Invocation with a running Transaction

if (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) {

try {

//Invoke down the chain

return getNext().invoke(mi);

}

finally {

// Do we have a valid bean (not removed)if (ctx.getId() != null) {

// If the context was not invoked previously...

  if (!ctx.isInvoked()) {

// It is now and this will cause ejbStore to be called...

ctx.setInvoked(true);

// ... on a transaction callback that we register here.

  register(ctx, tx);

}

}

Entity State-DB synchronization jb jb l i E tit S h i ti I t t

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 103/166

 New York, March 2003

9 - Client Side JBoss

"10

320032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntitySynchronizationInterceptor (registration on Tx during return)

private void register(EntityEnterpriseContext ctx, Transaction tx)

{// Create a new synchronization

InstanceSynchronization synch = new InstanceSynchronization(tx, ctx);

try {

// We want to be notified when the transaction commits

tx.registerSynchronization(synch);

} catch (RollbackException e) {

// The state in the instance is to be discarded, we force a reload of state

ctx.setValid(false);

} catch (Exception e) {

throw new EJBException(e);

}

}

 private void register(EntityEnterpriseContext ctx, Transaction tx)

{// Create a new synchronization

InstanceSynchronization synch = new InstanceSynchronization(tx, ctx);

try {

// We want to be notified when the transaction commits

  tx.registerSynchronization(synch);

} catch (RollbackException e) {

// The state in the instance is to be discarded, we force a reload of state

ctx.setValid(false);

} catch (Exception e) {throw new EJBException(e);

}

}

Instance Interceptor Exit 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 104/166

 New York, March 2003

9 - Client Side JBoss

"10

420032003 ©© JBoss GroupJBoss Group

Tx lock connection syncsecurity Relationcache callLog

ß Acquisition interceptor 

• Doesn’t do anything if Tx• In case of stateless call frees the instance

• In case of Exception discards the instance

invoke(..)

Invocation

Entity Instance from cache org jboss ejb plugins EntityInstanceInterceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 105/166

 New York, March 2003

9 - Client Side JBoss

"10

520032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntityInstanceInterceptor 

finally {

// ctx can be null if cache.get throws an Exception, for 

// example when activating a bean.if (ctx != null) {

// If an exception has been thrown,

if (exceptionThrown &&

// if tx, the ctx has been registered in an InstanceSynchronization.

// that will remove the context, so we shouldn't.

// if no synchronization then we need to do it by hand

!ctx.hasTxSynchronization()){

// Discard instance

// EJB 1.1 spec 12.3.1

container.getInstanceCache().remove(key);

}

else if (ctx.getId() == null)

{// The key from the Invocation still identifies the right cachekey

container.getInstanceCache().remove(key);

// no more pool return

}

 finally {

// ctx can be null if cache.get throws an Exception, for 

// example when activating a bean.if (ctx != null) {

// If an exception has been thrown,

if (exceptionThrown &&

// if tx, the ctx has been registered in an InstanceSynchronization.

// that will remove the context, so we shouldn't.

// if no synchronization then we need to do it by hand

!ctx.hasTxSynchronization()){

// Discard instance

// EJB 1.1 spec 12.3.1

container.getInstanceCache().remove(key);

}

else if (ctx.getId() == null)

{// The key from the Invocation still identifies the right cachekey

container.getInstanceCache().remove(key);

   // no more pool return

}

Lock Interceptor Exit 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 106/166

 New York, March 2003

9 - Client Side JBoss

"10

620032003 ©© JBoss GroupJBoss Group

Tx lock connection syncsecurity Relationcache callLog

ß Lock Interceptor 

• Cleans up any locks

invoke(..)

Invocation

GO!GO!

Only if part of 

the same

transaction

Only if part of 

the same

transaction

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 107/166

Entity State-DB synchronization (2.4) org jboss ejb plugins EntitySynchronizationInterceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 108/166

 New York, March 2003 9 - Client Side JBoss"10

820032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntitySynchronizationInterceptor (store if no transaction)

if (ctx.getId() != null)

{

boolean dirty = true;// Check isModified bean flag

if (isModified != null)

{

dirty = ((Boolean)isModified.invoke(ctx.getInstance(), newObject[0])).booleanValue();

}

// Store entityif (dirty)

((EntityContainer)getContainer()).getPersistenceManager().storeEntity(ctx);

}

return result;

} catch (Exception e) {

// Exception - force reload on next call

ctx.setValid(false);throw e;

}

}

}

if (ctx.getId() != null)

{

boolean dirty = true;// Check isModified bean flag

if (isModified != null)

{

dirty = ((Boolean)isModified.invoke(ctx.getInstance(), newObject[0])).booleanValue();

}

// Store entityif (dirty)

((EntityContainer)getContainer()).getPersistenceManager().storeEntity(ctx);

}

return result;

} catch (Exception e) {

// Exception - force reload on next call

ctx.setValid(false);

throw e;

}

}

}

 We are in beforecompletion

 We are in beforecompletion

Entity State-DB synchronization (3.0) org jboss ejb plugins EntitySynchronizationInterceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 109/166

 New York, March 2003 9 - Client Side JBoss"10

920032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntitySynchronizationInterceptor (store if no transaction)

 // And skip reads too ("get" methods)

if (ctx.getId() != null)

{if ( container.isReadOnly() == false )

{

container.storeEntity(ctx);

}

}

return result;

}

catch (Exception e)

{

// Exception - force reload on next call

ctx.setValid(false);

throw e;

}

}

 // And skip reads too ("get" methods)

if (ctx.getId() != null)

{ if ( container.isReadOnly() == false )

{

  container.storeEntity(ctx);

}

}

return result;

}

catch (Exception e){

// Exception - force reload on next call

ctx.setValid(false);

throw e;

}

}

Entity State-DB synchronization org jboss ejb plugins EntitySynchronizationInterceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 110/166

 New York, March 2003 9 - Client Side JBoss"11

020032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntitySynchronizationInterceptor (store if no transaction)

public void afterCompletion(int status) {

boolean trace = log.isTraceEnabled();

// This is an independent point of entry. We need to make sure the

// thread is associated with the right context class loader 

ClassLoader oldCl = Thread.currentThread().getContextClassLoader();

Thread.currentThread().setContextClassLoader(container.getClassLoader());

lock.sync();

// If rolled back -> invalidate instance

if (status == Status.STATUS_ROLLEDBACK)

{

// remove from the cache

container.getInstanceCache().remove(ctx.getCacheKey());

}

else

{

switch (commitOption)

{

 public void afterCompletion(int status) {

boolean trace = log.isTraceEnabled();

// This is an independent point of entry. We need to make sure the

// thread is associated with the right context class loader 

ClassLoader oldCl = Thread.currentThread().getContextClassLoader();

Thread.currentThread().setContextClassLoader(container.getClassLoader());

lock.sync();

// If rolled back -> invalidate instanceif (status == Status.STATUS_ROLLEDBACK)

{

// remove from the cache

container.getInstanceCache().remove(ctx.getCacheKey());

}

else

{switch (commitOption)

{

Transactioncompleted

Transaction

completed

Entity State-DB synchronization (24/30) org jboss ejb plugins EntitySynchronizationInterceptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 111/166

 New York, March 2003 9 - Client Side JBoss"11

120032003 ©© JBoss GroupJBoss Group

org.jboss.ejb.plugins.EntitySynchronizationInterceptor (store if no transaction)

switch (commitOption) {

// Keep instance cached after tx commit

case ConfigurationMetaData.A_COMMIT_OPTION:

// The state is still valid (only point of access is us)

ctx.setValid(true);

break;

// Keep instance active, but invalidate state

case ConfigurationMetaData.B_COMMIT_OPTION:

// Invalidate state (there might be other points of entry)

ctx.setValid(false);

break;

// Invalidate everything AND Passivate instance

case ConfigurationMetaData.C_COMMIT_OPTION:

try

{

// Do not call release if getId() is null. This means that

// the entity has been removed from cache.

// release will schedule a passivation and this removed ctx

// could be put back into the cache!

if (ctx.getId() != null) container.getInstanceCache().release(ctx);

}

 switch (commitOption) {

// Keep instance cached after tx commit

case ConfigurationMetaData.A_COMMIT_OPTION:// The state is still valid (only point of access is us)

ctx.setValid(true);

break;

// Keep instance active, but invalidate state

  case ConfigurationMetaData.B_COMMIT_OPTION:

// Invalidate state (there might be other points of entry)ctx.setValid(false);

break;

// Invalidate everything AND Passivate instance

case ConfigurationMetaData.C_COMMIT_OPTION:

try

{

// Do not call release if getId() is null. This means that// the entity has been removed from cache.

// release will schedule a passivation and this removed ctx

// could be put back into the cache!

if (ctx.getId() != null) container.getInstanceCache().release(ctx);

}

Conclusion 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 112/166

 New York, March 2003 9 - Client Side JBoss"11

220032003 ©© JBoss GroupJBoss Group

ß Server side is implemented with

• Interceptors• Plugins

• Services as MBean

ß  You can specify interceptors at the EJB level

• Soon at the Mbean level• Is externalized in standardjboss.xml

ß Interceptors implement any indirection and AOP you want

• Use locking to your advantage (be careful)

• Tweak caching to your advantage

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 113/166

Copyright JBoss GroupCopyright JBoss Group

Java Management eXtension

Specification + Usage in JBoss

What is JMX? 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 114/166

 New York, March 2003 9 - Client Side JBoss"11

420032003 ©© JBoss GroupJBoss Group

ß Defines architecture and API for application management.

ß Instrumentation

• Managed Beans a.k.a MBeans

• Standard and Dynamic MBeans

• Model and Open MBeans

ß

Agent• MBeanServer 

• Standard Services

ß Distribution Layer (not specified in the 1.1 version)

• Connectors and Protocol Adaptors

• HTTP, RMI, SOAP, SNMP, JMS, ...

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 115/166

Why JMX for J2EE ? 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 116/166

 New York, March 2003 9 - Client Side JBoss"11

6

20032003 ©© JBoss GroupJBoss Group

ß In a distributed service-based platform where resources are added, moved and

removed dynamically, the J2EE application management becomes even more difficult.ß Instrumentation of the resources is defined by the JMX spec (uniformity). We have a

standard mechanism to manage all the J2EE services.

ß Ability to build generic management tools that will work on any JMX enabled J2EEplatform.

ß

An integration technology to build the J2EE platform from a selection of separatecomponents made by different vendors.

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 117/166

JMX Architecture (2/4) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 118/166

 New York, March 2003 9 - Client Side JBoss"11

8

20032003 ©© JBoss GroupJBoss Group

Java Virtual Machine

Agent ServiceMBeans

Application

ResourceMBeans

MB 

 e an S  er  v  e

r  

Connector

Protocol

Adaptor

Management

Client

Browser

Proxy

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 119/166

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 120/166

JMX Object Naming (1/2) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 121/166

 New York, March 2003 9 - Client Side JBoss"12

1

20032003 ©© JBoss GroupJBoss Group

ß MBeans are registered in the JMX bus with an ObjectName

ß Any client can invoke operations on an MBean by using its ObjectName

ß Each ObjectName is unique

ß The structure is

<domain> : [ <key>=<value> ] { , <key>=<value> }

Example:

 jboss:service=invoker,type=jrmp

JMX Object Naming (2/2) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 122/166

 New York, March 2003 9 - Client Side JBoss"12

2

20032003 ©© JBoss GroupJBoss Group

ß The [ <key>=<value>] pairs can be used by clients to make queries on

the MBeanServer and get a list of corresponding MBeansß Somehow superior to JNDI naming structure: hierarchical vs. flat

• Sometimes, attributes have no meaningful order 

• Inferior to JNDI in that it quite restrictive on what can be in properties

• Example:

• Querying JBossMX for “service=invoker” will return – JRMP

 – HTTP

 – IIOP

 – Local

 – JBoss.Net

Instrumentation 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 123/166

 New York, March 2003 9 - Client Side JBoss"12

3

20032003 ©© JBoss GroupJBoss Group

ß Instrumentation level specifies the implementation of managed resources.

•  A managed resource can be an application, an implementation of aservice, a device, a user, etc.

ß Basic types:

• Standard MBeans

• Dynamic MBeansß Instrumentation level also defines a notification mechanism.

ß The management interfaces are described with MBean metadata classes.

Instrumentation: MBeans 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 124/166

 New York, March 2003 9 - Client Side JBoss"12

4

20032003 ©© JBoss GroupJBoss Group

ß MBean has a management interface

• management attributes• management operations

• management notifications

• constructors

ß

The MBean Server provides the meta data that describes the management interface for all of its registered MBeans.

ß MBean classes may be stored locally or downloaded from a remote site (MLets).

Instrumentation: MBean Definition 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 125/166

 New York, March 2003 9 - Client Side JBoss"12

5

20032003 ©© JBoss GroupJBoss Group

ß MBean must be a concrete class.

ß MBean must have at least one public constructor.

ß MBean class must implement its own corresponding MBean interface (standard MBean)or the DynamicMBean interface.

ß Note that the MBean instrumentation type (standard or dynamic) does not affect how

the resource is managed. The MBean Server abstracts the instrumentation type.Management applications handle both types in a similar manner.

Instrumentation: Standard MBeans (1/4) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 126/166

 New York, March 2003 9 - Client Side JBoss"12

6

20032003 ©© JBoss GroupJBoss Group

ß Explicitly defines the management interface through a static Javainterface.

ß The MBean interface must be named after the class.

• public class Foo implements FooMBean

ß Attributes are defined via getter and setter methods.

ß Attributes may be read-write, read-only or write-only

depending which methods you declare.

 public <AttributeType> get<AttributeName>()

 public void set<AttributeName>(<AttributeType> 

 value)

Instrumentation: Standard MBeans (2/4) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 127/166

 New York, March 2003 9 - Client Side JBoss"12

720032003 ©© JBoss GroupJBoss Group

public interface MyClassMBean {

public Integer getState();

public void setState(Integer s);public void reset();

}

Instrumentation: Standard MBeans (3/4) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 128/166

 New York, March 2003 9 - Client Side JBoss"12

820032003 ©© JBoss GroupJBoss Group

public class MyClass implements MyClassMBean {

private Integer state = null;

private String hidden = null;

public Integer getState() {

return state;

public Integer setState(Integer s) {

state = s;

Instrumentation: Standard MBeans (4/4) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 129/166

 New York, March 2003 9 - Client Side JBoss"12

920032003 ©© JBoss GroupJBoss Group

public String getHidden() {

return hidden;

public void setHidden(String h) {

hidden = h;

} public void reset() {

state = null;

hidden = null;

Instrumentation: MBean Inheritance (1/3) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 130/166

 New York, March 2003 9 - Client Side JBoss"13

020032003 ©© JBoss GroupJBoss Group

ß The management interface may be inherited by subclasses.

  MyClass MyClassMBean

getState();

setState(Integer);

reset();

getState();

setState(Integer);

reset();

 MySubClass

The MySubClass automatically exposesthe same management interface as its

super class. There is no need to declareMySubClassMBean interface.

Instrumentation: MBean Inheritance (2/3) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 131/166

 New York, March 2003 9 - Client Side JBoss"13

120032003 ©© JBoss GroupJBoss Group

ß The subclass may override the existing management interface.

• Here MySubClass does not have a State R/W attribute

  MyClass MyClassMBean

getState();

setState(Integer);

reset();

getState();

setState(Integer);

reset();

  MySubClass MySubClassMBean

reset();

Instrumentation: MBean Inheritance (3/3) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 132/166

 New York, March 2003 9 - Client Side JBoss"13

220032003 ©© JBoss GroupJBoss Group

ß  You can use inheritance to enable management of existing libraries(even 3rd party libs you don’t have source for).

electric.server.http.HTTP

setMaxThreads(int)

shutdown()

...

 ManagedHTTP

 ManagedHTTPMBean

setMaxThreads(int);

shutdown();

Notification Mechanism 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 133/166

 New York, March 2003 9 - Client Side JBoss"13

320032003 ©© JBoss GroupJBoss Group

ß Allows other MBeans and management applications to react to changesin a managed bean.

ß Follows the design of JavaBean event mechanism.

• Notification class is a subclass of java.util.EventObject

• Observers implement the NotificationListener interface.

• Introduces filters with NotificationFilter interface.

• Broadcasting MBeans implement the NotificationBroadcaster interface.

ß Notifications are part of the MBean’s management interface.

Instrumentation: Dynamic MBeans 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 134/166

 New York, March 2003 9 - Client Side JBoss"13

420032003 ©© JBoss GroupJBoss Group

ß Dynamic MBeans implement the DynamicMBean interface.

ß There is no statically typed Java interface which declares themanagement interface.

• The management interface can be determined at run-time instead of 

compile time.

ß The MBean developer declares the management using the MBean metadata classes.

• For standard MBeans this was done automatically via introspection by the

MBean server.

ß The developer has more control over what management information isavailable in the meta data.

Instrumentation: Dynamic MBean 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 135/166

 New York, March 2003 9 - Client Side JBoss"13

520032003 ©© JBoss GroupJBoss Group

public interface DynamicMBean {

public MBeanInfo getMBeanInfo();

public Object getAttribute(String attribute);

public AttributeList getAttributes(String[] attributes);

public void setAttribute(Attribute attribute);public AttributeList setAttributes(AttributeList attributes);

public Object invoke(String actionName,

Object[] params,

String[] signature);

Dynamic MBean Meta Data 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 136/166

 New York, March 2003 9 - Client Side JBoss"13

620032003 ©© JBoss GroupJBoss Group

ß The agent discovers the management interface through thegetMBeanInfo() method.

ß The meta data consists of the following classes:

• MBeanInfo

• MBeanFeatureInfo

• MBeanAttributeInfo

• MBeanOperationInfo

• MBeanConstructorInfo

• MBeanNotificationInfo

• MBeanParameterInfo

Dynamic MBean Implementation 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 137/166

 New York, March 2003 9 - Client Side JBoss"13

720032003 ©© JBoss GroupJBoss Group

ß The developer is responsible of mapping the management attributesand operations to their corresponding implementations.

public void setAttribute(Attribute attribute) throws ... {

if (attribute.getName().equals(“State”))this.state = (String)attribute.getValue();

}

vThe developer must make sure the MBean implements themanagement interface as advertised.

Instrumentation: What to Use? 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 138/166

 New York, March 2003 9 - Client Side JBoss"13

820032003 ©© JBoss GroupJBoss Group

ß Use standard MBeans if:

• You need to create new managed resources quickly.• You want to rely on the static interface for robustness.

• Performance is not critical (reflection, not true in JDK1.4)

ß Use dynamic MBeans if:

• You need to determine the management interface at run-time.• You anticipate the management interface changing often.

• You need to extend the management meta data.

•  A key extension is human readable descriptions of attributes and 

operations• Performance is important.

Model MBeans: XMBeans in JBoss 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 139/166

 New York, March 2003 9 - Client Side JBoss"13

920032003 ©© JBoss GroupJBoss Group

ß Model MBeans

• Take the pain out of Dynamic MBeans with template MBeans• Implementation of Model MBeans is *per* server implementation

• The server provides the implementation you use it to define new MBeanseasily.

•  Access data through ModelMBean “accesors”• Many services available to MMBeans through mandated interfaces

• PersistentMBean : Persistence of values in MBeans

• DynamicMBean: invoke of target method and MBeanInfo

• ModelMBeanNotificationBroadcaster : attribute change notification

• ModelMBean : setting the managed resource

XMBeans 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 140/166

 New York, March 2003 9 - Client Side JBoss"14

020032003 ©© JBoss GroupJBoss Group

ß XMBeans

• JBossMX implementation of the ModelMBean from the specification• Use it when you want to create DynamicMBean with little work through an

easy XML configuration

ß Persistence:ModelMBeans define persistence for the cached values inthe MBean

• load() and store() api calls from the PersistentMBean interface

• The decision to store: The persist policy• never, OnUpdate, OnTimer, NoMoreOftenThan 

• The decision to load: on creation

ß JBossMX provides a simple serialized representation of the data

Instrumentation: Other Types 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 141/166

 New York, March 2003 9 - Client Side JBoss"14

120032003 ©© JBoss GroupJBoss Group

ß

Open MBeans• “Not finished” in the current version of specification. Not mandatory.

• JBossMX implements the current specification

• Defines basic data types and complex data types.

• Describe custom types using primitives, arrays and tabular (similar to

HashMap)

• Not widely supported by tools, yet…

XMBean DTD (Part 1) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 142/166

 New York, March 2003 9 - Client Side JBoss"14

220032003 ©© JBoss GroupJBoss Group

XMBean DTD (Part 2) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 143/166

 New York, March 2003 9 - Client Side JBoss"14

320032003 ©© JBoss GroupJBoss Group

Agent Layer: Standard Services 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 144/166

 New York, March 2003 9 - Client Side JBoss"14

420032003 ©© JBoss GroupJBoss Group

ß Four mandatory services:

• MLet Service (dynamic classloading)

• Timer Service

• Monitoring Service

• Relation Service

ß In addition, you typically need at least one protocol adaptor or aconnector. Remember that the MBeanServer itself is a local object in theJVM. In order for it to be manageable, at least one protocol adaptor or connector server must be available.

Agent Layer: MBeanServer Interface (1/2) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 145/166

 New York, March 2003 9 - Client Side JBoss"14

520032003 ©© JBoss GroupJBoss Group

public interface MBeanServer {

public ObjectInstance createMBean(String className, ObjectName name) throws ... ;

public ObjectInstance createMBean(String className, ObjectName name,

ObjectName loaderName) throws ... ;

public void unregisterMBean(ObjectName name) throws ... ;

...

public Object getAttribute(ObjectName name, String attribute) throws ... ;

public AttributeList getAttributes(ObjectName name, String[] attributes)

public void setAttribute(ObjectName name, Attribute attribute) throws ... ;

public AttributeList setAttributes(ObjectName name, AttributeList attributes)

...

Agent Layer: MBeanServer Interface (2/2) 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 146/166

 New York, March 2003 9 - Client Side JBoss"14

620032003 ©© JBoss GroupJBoss Group

public Object invoke(ObjectName name, String operation, Object params[],String signature[]) throws ... ;

...public void addNotificationListener(ObjectName name,

NotificationListener listener,NotificationFilter filter,Object handback) throws ... ;

public void removeNotificationListener(ObjectName name,NotificationListener listener) throws ..

...public MBeanInfo getMBeanInfo(ObjectName name) throws ... ;

}

Agent Layer: MLet Service 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 147/166

 New York, March 2003 9 - Client Side JBoss"14

720032003 ©© JBoss GroupJBoss Group

ß Allows dynamic class loading in the MBean server.

ß Includes a configuration mechanism for loading and registering MBeansfrom a remote server.

  <MLET CODE = class | OBJECT = serfile

ARCHIVE = “archivelist”

[CODEBASE = codebaseURL]

[NAME = MBeanName]

[VERSION = version]

>

[arglist]

</MLET>

ß Notice that despite the looks, it’s not well formed XML.

Agent Layer: MLet Service 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 148/166

 New York, March 2003 9 - Client Side JBoss"14

820032003 ©© JBoss GroupJBoss Group

ß With dynamic class loading and MLet configuration you can easily build

truly network managed applications.

Download MBeanconfiguration file

Download MBeancomponents

(NEW) Agent Layer: MLet Service 

ß You can easily build farms of JBoss servers

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 149/166

 New York, March 2003 9 - Client Side JBoss"14

920032003 ©© JBoss GroupJBoss Group

 You can easily build farms of JBoss servers.

Download full serverand configuration file

SERVER FARMSERVER FARM

 Admin Admin

Agent Layer: Timer Service 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 150/166

 New York, March 2003 9 - Client Side JBoss"15

020032003 ©© JBoss GroupJBoss Group

ß Provides notifications to registered listeners on a given date or time

interval.

ß Similar to platform specific cron (Unix) and Task Scheduler (WinNT)services.

ß The J2EE platform does not define a timer service until J2EE 1.4

ß JMX provides a portable mechanism to implement scheduled tasks for J2EE applications.

Agent Layer: Monitoring Service 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 151/166

 New York, March 2003 9 - Client Side JBoss"15

120032003 ©© JBoss GroupJBoss Group

ß Allows you to easily watch the state changes of a managementattribute.

ß Three different basic types:

• Counter monitor for integer types.

• Gauge monitor for numeric types.• String monitor for strings.

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 152/166

JSR 77 UNIFIED NETWORK 

Databases Databases

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 153/166

 New York, March 2003 9 - Client Side JBoss"15

320032003 ©© JBoss GroupJBoss Group

JMX implementation “Spine”JMX implementation “Spine”

JMX implementation “Spine”

Computer 1

Computer 2

Computer 2

http

Web FileFile

 jboss

conf

Oracle

Databases

DB/2

Databases

Containers

Containers

JSR 77

JMX implementation “Spine”

JMX Management Today 

ß HTML Adaptor

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 154/166

 New York, March 2003 9 - Client Side JBoss"15

420032003 ©© JBoss GroupJBoss Group

ß HTML Adaptor 

•  Accessible at http://localhost:8080/jmx-console/• Primitive support for attribute editing using property editors

ß RMI Connector 

•  An RMI Façade for MBeanServer interface methods of interest

ß

EJB Connector • In JBoss 3.0, similar to RMI connector but allows for secured access by

virtue of being an EJB

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 155/166

Copyright JBoss GroupCopyright JBoss Group

Message Driven Beans (MDB)Message Driven Beans (MDB)

Topics 

ß What are MDBs?

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 156/166

 New York, March 2003 9 - Client Side JBoss"15

620032003 ©© JBoss GroupJBoss Group

What are MDBs?

ß How are they used?

What are they? 

ß Introduced in EJB 2.0

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 157/166

 New York, March 2003 9 - Client Side JBoss"15

720032003 ©© JBoss GroupJBoss Group

Introduced in EJB 2.0

ß A convenient way of implementing JMS message consumers.

• No client invocation - MDB is just a consumer of JMS messages.

ß Enable asynchronous invocation of beans.

• Normal EJB calls are synchronous invocations.

• Call blocks while the method is being invoked on the bean.

• MDBs are asynchronous - invoked by JMS messages.ß Client has no direct contact with them.

• They have no home or remote interfaces.

• They are stateless (like stateless session beans).

• Lifecycle is entirely controlled by the container.

ß Invoked through a single, weakly typed method:onMessage(Message m);

MDBs - Asynchronous Bean Invocations 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 158/166

 New York, March 2003 9 - Client Side JBoss"15

820032003 ©© JBoss GroupJBoss Group

1

Home

Remote1

SYNCHRONOUS

1

Container

TOPIC

Client

Client

Container

LISTENER

RegularBean

MDB

Messages

ASYNCHRONOUS

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 159/166

Bean Implementation 

ß MDBs have a dual nature:

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 160/166

 New York, March 2003 9 - Client Side JBoss"16

020032003 ©© JBoss GroupJBoss Group

ß MDBs have a dual nature:

• an EJB side.• a JMS side.

ß Must implement javax.ejb.MessageDrivenBean.

• The EJB container lifecycle contract.

ß Must implement the javax.jms.MessageListener interface.

• Consists of the single onMessage(Message m) method.

• The message argument can be any of the JMS message types.

Bean Implementation 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 161/166

 New York, March 2003 9 - Client Side JBoss"16

120032003 ©© JBoss GroupJBoss Group

import javax.ejb.*;

import javax.jms.MessageListener;

public class AssassinBean implements MessageDrivenBean,MessageListener {

public void onMessage( Message m ) {

   // business logic goes in here …

String text = ((TextMessage)m).getText();

}

// container contract methods

public void setMessageDrivenContext( MessageDrivenContext ctx ) { }

public void ejbCreate() { }public void ejbRemove() { }

}

import javax.ejb.*;

import javax.jms.MessageListener;

public class AssassinBean implements MessageDrivenBean,MessageListener  {

public void onMessage( Message m ) {

   // business logic goes in here …

String text = ((TextMessage)m).getText();…

}

// container contract methods

public void setMessageDrivenContext ( MessageDrivenContext ctx ) { }

public void ejbCreate() { }public void ejbRemove() { }

}

Container Contract Methods 

ß ejbCreate() - signals creation of the bean.

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 162/166

 New York, March 2003 9 - Client Side JBoss"16

220032003 ©© JBoss GroupJBoss Group

ejbC eate() s g a s c eat o o t e bea

ß ejbRemove() - signals destruction, on removal from the pool.

• Not guaranteed to be called.

ß setMessageDrivenContext(MessageDrivenContext ctx)

• Called at creation time.

Transactions and MDB 

ß As with all JMS transactions, the delivery is decoupled from the

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 163/166

 New York, March 2003 9 - Client Side JBoss"16

320032003 ©© JBoss GroupJBoss Group

, y psending.

• Producer and MDB run in separate transactions.

ß If container managed transactions are used:

• Delivery and processing take place in the same transaction.

•  A roll-back or system exception cause the message to be re-

delivered.

• Watch out for messages trapped in the system!

ß CMT attributes must be either Required or NotSupported .

Deployment Descriptor - ejb-jar.xml 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 164/166

 New York, March 2003 9 - Client Side JBoss"16

420032003 ©© JBoss GroupJBoss Group

<ejb-jar>

<display-name>Crime Portal Application</display-name>

<enterprise-beans>

<message-driven>

<display-name>Assassin Bean</display-name>

<ejb-name>AssassinBean</ejb-name>

<ejb-class>crimeportal.implementation.AssassinBean</ejb-class><transaction-type>Container</transaction-type>

<message-driven-destination>

<destination-type>javax.jms.Topic</destination-type>

<subscription-durability>NonDurable</subscription-durability>

</message-driven-destination>

</message-driven>

</enterprise-beans>

<assembly-descriptor/>

</ejb-jar>

<ejb-jar>

<display-name>Crime Portal Application</display-name>

<enterprise-beans>

<message-driven>

<display-name>Assassin Bean</display-name>

<ejb-name>AssassinBean</ejb-name>

<ejb-class>crimeportal.implementation.AssassinBean </ejb-class><transaction-type>Container </transaction-type>

<message-driven-destination>

<destination-type> javax.jms.Topic</destination-type>

<subscription-durability>NonDurable</subscription-durability>

</message-driven-destination>

</message-driven>

</enterprise-beans>

<assembly-descriptor/>

</ejb-jar>

Deployment Descriptor - jboss.xml 

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 165/166

 New York, March 2003 9 - Client Side JBoss"16

520032003 ©© JBoss GroupJBoss Group

ß Obviously you also need to add the destination topic to JBoss.

• Use one of the approaches from the JBossMQ chapter.

• If you don’t, JBossMQ will create a temporary topic for your 

application.

<jboss>

<enterprise-beans>

<message-driven>

<ejb-name>ShipmentBean</ejb-name>

<destination-jndi-name>topic/AssassinBeanTopic</destination-jndi-name>

</message-driven>

</enterprise-beans></jboss>

<jboss>

<enterprise-beans><message-driven>

<ejb-name>ShipmentBean</ejb-name>

<destination-jndi-name> topic/AssassinBeanTopic</destination-jndi-name>

</message-driven>

</enterprise-beans>

</jboss>

Test 

ß What interfaces must an MDB implement?

8/3/2019 Jboss Additional Slides 1

http://slidepdf.com/reader/full/jboss-additional-slides-1 166/166

p

ß If a transaction is rolled back from an MDB, what happens to themessage?

• Is it returned to the client who sent it?