You are on page 1of 30

Business Component Development Using EJB Technologies

Objectives

In this session, you will learn to:


Describe interceptors and interceptor classes
Create a business interceptor method in the enterprise bean
class
Create an interceptor class
Associate multiple business interceptor methods with an
enterprise bean
Include life-cycle callback interceptor methods in an interceptor
class
Create entity life-cycle callback methods

Ver. 1.0

Slide 1 of 30

Business Component Development Using EJB Technologies


Introducing Interceptors and Interceptor Classes

An interceptor is a class that works in conjunction with a


bean class to:
Interpose on business method invocations.
Receive life-cycle callback notifications.

Interceptors are classified as:


Business interceptor method
Life-cycle callback interceptor methods

Interceptors are supported by the following types of


enterprise bean types:
Session beans
Message-driven beans

Ver. 1.0

Slide 2 of 30

Business Component Development Using EJB Technologies


Introducing Interceptors and Interceptor Classes (Contd.)

The method signature of a business interceptor method is:


@AroundInvoke
public Object anyMethodName(InvocationContext ic)
throws Exception

The method signature of life-cycle callback interceptor


method is:
@anyCallbackAnnotation
anyAccessModifier void anyMethodName(InvocationContext
ic)

Ver. 1.0

Slide 3 of 30

Business Component Development Using EJB Technologies


Introducing Interceptors and Interceptor Classes (Contd.)

The following code shows the API for the InvocationContext


object:
1 public interface InvocationContext {
2
public Map<String, Object> getContextData();
3
public Method getMethod();
4
public Object[] getParameters();
5
public void setParameters(Object[] params);
6
public Object getTarget();
7
public Object proceed() throws Exception;
8 }

Ver. 1.0

Slide 4 of 30

Business Component Development Using EJB Technologies


Creating a Business Interceptor Method in the Enterprise Bean Class

To add an interceptor method to an enterprise bean, perform


the following tasks:
1. Declare an interceptor method in the bean class that conforms
to the following signature:
@AroundInvoke
public Object anyMethodName(InvocationContext ic)
throws Exception

2. Ensure the return from the interceptor method invokes the


InvocationContext objects proceed method. For example:
return ic.proceed();

Ver. 1.0

Slide 5 of 30

Business Component Development Using EJB Technologies


Creating a Business Interceptor Method in the Enterprise Bean Class (Contd.)

The following code shows a stateless session bean


AccountManagementBean, which contains an interceptor
method called profile:
1
2
3
4
5
6
}
7
8
9
10
11

Ver. 1.0

@Stateless
public class AccountManagementBean implements
AccountManagement {
public void createAccount(int accountNumber,
AccountDetails details) { ... }
public void deleteAccount(int accountNumber) { ... }
public void activateAccount(int accountNumber) { ...
public void deactivateAccount(int accountNumber) {
... }

@AroundInvoke public Object


profile(InvocationContext inv)
throws Exception {
long time = System.currentTimeMillis();

Slide 6 of 30

Business Component Development Using EJB Technologies


Creating a Business Interceptor Method in the Enterprise Bean Class (Contd.)

12
13
14
15
16
17
18
19

Ver. 1.0

try {
return inv.proceed(); }
finally {
long diffTime = time - System.currentTimeMillis();
System.out.println(inv.getMethod() + " took " +
diffTime + " milliseconds.");
}
}

Slide 7 of 30

Business Component Development Using EJB Technologies


Creating an Interceptor Class

To create an Interceptor class and associate it with an


enterprise bean, perform the following tasks:
1. Declare a Java technology class.
2. Include a public no-arg constructor.
3. Declare an interceptor method in the Java technology class
that conforms to the following signature:
@AroundInvoke
public Object anyMethodName(InvocationContext ic)
throws Exception

4. Ensure the interceptor method invokes the InvocationContext


objects proceed method.
5. Annotate the enterprise bean with the Interceptors annotation.
Include the name of the inceptor class as an attribute of the
Interceptors annotation.

Ver. 1.0

Slide 8 of 30

Business Component Development Using EJB Technologies


Creating an Interceptor Class (Contd.)

The following code shows a stateless session bean


AccountManagementBean that is associated with one
interceptor class, AccountAudit:
1
2
3
4
5

@Stateless
@Interceptors({
com.acme.AccountAudit.class,
})
public class AccountManagementBean implements
AccountManagement {
6
public void createAccount(int accountNumber,
7
AccountDetails details) { ... }
8
public void deleteAccount(int accountNumber) { ...
}
9
public void activateAccount(int accountNumber) {
... }
10 public void deactivateAccount(int accountNumber) {
...}
Ver. 1.0

Slide 9 of 30

Business Component Development Using EJB Technologies


Creating an Interceptor Class (Contd.)
11 }
12
13 public class AccountAudit {
14 @AroundInvoke public Object auditAccountOperation
15 (InvocationContext inv) throws Exception {
16 try {
17
Object result = inv.proceed();
18
Auditor.audit(inv.getMethod().getName(),
19
inv.getParameters()[0]);
20
return result;
21
} catch (Exception ex) {
22
Auditor.auditFailure(ex);
23
throw ex;
24
}
25 }
26 }
Ver. 1.0

Slide 10 of 30

Business Component Development Using EJB Technologies


Associating Multiple Business Interceptor Methods With an Enterprise Bean

The following steps provides a multi-step process to define


multiple business interceptor methods for an enterprise
bean:
1. Define each business interceptor method in its own interceptor
class.
2. Optionally, define a business interceptor method in the bean
class.
3. Use the Interceptors metadata annotation to associate the
method interceptors with bean class.

Ver. 1.0

Slide 11 of 30

Business Component Development Using EJB Technologies


Associating Multiple Business Interceptor Methods With an Enterprise Bean (Contd.)

The following code shows a stateless session bean


AccountManagementBean that is associated with two
interceptor classes (AccountAudit and CustomSecurity):
1
2
3
4
5
6

@Stateless
@Interceptors({
com.acme.AccountAudit.class,
com.acme.CustomSecurity.class
})
public class AccountManagementBean implements
AccountManagement {
7
public void createAccount(int accountNumber,
8
AccountDetails details) { ... }
9
public void deleteAccount(int accountNumber) { ...
}
10 public void activateAccount(int accountNumber) {
... }
Ver. 1.0

Slide 12 of 30

Business Component Development Using EJB Technologies


Associating Multiple Business Interceptor Methods With an Enterprise Bean (Contd.)

11

public void deactivateAccount(int


accountNumber){... }

12
13 @AroundInvoke public Object
profile(InvocationContext
inv)
14 throws Exception {
15 long time = System.currentTimeMillis();
16 try {
17
return inv.proceed(); }
18 finally {
19
long diffTime = time System.currentTimeMillis();
20
System.out.println(inv.getMethod() + " took " +
diffTime + "21 milliseconds.");
22
}

Ver. 1.0

Slide 13 of 30

Business Component Development Using EJB Technologies


Associating Multiple Business Interceptor Methods With an Enterprise Bean (Contd.)

23 }
24 }
25
26 public class AccountAudit {
27 @AroundInvoke public Object auditAccountOperation
28
(InvocationContext inv) throws Exception {
29
try {
30
Object result = inv.proceed();
31
Auditor.audit(inv.getMethod().getName(),
32
inv.getParameters()[0]);
33
return result;
34
} catch (Exception ex) {
35
Auditor.auditFailure(ex);
36
throw ex;
37
}
38 }
Ver. 1.0

Slide 14 of 30

Business Component Development Using EJB Technologies


Associating Multiple Business Interceptor Methods With an Enterprise Bean (Contd.)

39 }
40
41 public class CustomSecurity {
42 @AroundInvoke public Object
customSecurity(InvocationContext inv)
43
throws Exception {
44
doCustomSecurityCheck(inv.getEJBContext().
getCallerPrincipal());
45
return inv.proceed();
46 }
47 private void doCustomSecurityCheck(Principal
caller)
48 throws SecurityException {
49 //...
50 }
51 }

Ver. 1.0

Slide 15 of 30

Business Component Development Using EJB Technologies


Including Life-Cycle Callback Interceptor Methods in an Interceptor Class

The life-cycle events generated by session and


message-driven beans are:
PostConstruct event
PreDestroy callback
PostActivate callback
PrePassivate callback

Ver. 1.0

Slide 16 of 30

Business Component Development Using EJB Technologies


Creating a Life-Cycle Callback Interceptor Method

To create a life-cycle callback interceptor method, perform


the following tasks:
1. Declare a Java technology class.
2. Include a public no-arg constructor.
3. Declare a method in the Java technology class that conforms
to the following signature:
anyAccessModifier void
anyMethodName(InvocationContext ic)

4. Annotate the method using one of the following lifecycle


callback event annotations:
i.
ii.
iii.
iv.

Ver. 1.0

PostConstruct
PreDestroy
PostActivate
PreActivate

Slide 17 of 30

Business Component Development Using EJB Technologies


Creating a Life-Cycle Callback Interceptor Method (Contd.)

5. Ensure the interceptor method invokes the InvocationContext


objects proceed method.
6. Annotate the enterprise bean with the Interceptors annotation.

Ver. 1.0

Slide 18 of 30

Business Component Development Using EJB Technologies


Creating a Life-Cycle Callback Interceptor Method (Contd.)

The following code shows the definition of a life-cycle


callback interceptor method in an interceptor class:
1 public class CartCallbackListener {
2 public CartCallbackListener() {} // public
// no-arg constructor
3
// callback interceptor method
4
@PreDestroy
5
private void endShoppingCart
(InvocationContext ic) {...}
6 }

Ver. 1.0

Slide 19 of 30

Business Component Development Using EJB Technologies


Creating a Life-Cycle Callback Interceptor Method (Contd.)

The following code shows the use of the Interceptors


annotation that associates the interceptor class:
1 @Interceptors({CartCallbackListener.class})
2 @Stateful public class ShoppingCartBean
implements ShoppingCart {
3 private float total;
4 private Vector productCodes;
5 public int someShoppingMethod(){...};
6 //...
7 }

Ver. 1.0

Slide 20 of 30

Business Component Development Using EJB Technologies


Defining Entity Classes: Adding Life-Cycle Event Handlers

An entity class generates the following life-cycle events:


PrePersist callback
PostPersist callback
PreRemove callback
PostRemove callback
PreUpdate callback
PostUpdate callback
PostLoad callback

Ver. 1.0

Slide 21 of 30

Business Component Development Using EJB Technologies


Defining Life-Cycle Event Handlers

You can define the event handler in either of the following


locations:
In the entity class
In a callback listener class

Ver. 1.0

Slide 22 of 30

Business Component Development Using EJB Technologies


Defining a Callback Handler in the Entity Class

The following steps outline a process to add callback


handler to a entity class:
1. Define a callback method in the entity class that conforms to
the following signature:
public void methodName()

2. Annotate the method with the appropriate callback annotation.

Ver. 1.0

Slide 23 of 30

Business Component Development Using EJB Technologies


Defining a Callback Handler in the Entity Class (Contd.)

The following code shows life-cycle event handler methods,


validateCreate and adjustPreferredStatus, defined within an
entity class:
1 @Entity
2 public class Account {
3 @Id
4 Long accountId;
5 Integer balance;
6 boolean preferred;
7 public Long getAccountId() { ... }
8 public Integer getBalance() { ... }
9 @Transient // because status depends upon
non-persistent context
10 public boolean isPreferred() { ... }
11 public void deposit(Integer amount) { ... }

Ver. 1.0

Slide 24 of 30

Business Component Development Using EJB Technologies


Defining a Callback Handler in the Entity Class (Contd.)
12 public Integer withdraw(Integer amount) throws
NSFException {... }
13 @PrePersist
14 public void validateCreate() {
15 if (getBalance() < MIN_REQUIRED_BALANCE) throw
new
16 AccountException("Insufficient balance to open
an account");
17}
18 @PostLoad
19 public void adjustPreferredStatus() {
20 preferred =
21 (getBalance() >=
AccountManager.getPreferredStatusLevel());
22 }
23 }

Ver. 1.0

Slide 25 of 30

Business Component Development Using EJB Technologies


Defining a Callback Handler in a Callback Listener Class

The following steps outline a process, you can follow to


define callback handlers in a callback listener class:
1.
2.
3.

Declare a class for use as the callback listener class.


Declare a public no-arg constructor in the callback listener
class.
Define a callback method in the callback listener class that
conforms to the following signature:
public void methodName(EntityClassType b)

4.

Ver. 1.0

Annotate the method with the appropriate callback


annotation.

Slide 26 of 30

Business Component Development Using EJB Technologies


Defining a Callback Handler in a Callback Listener Class (Contd.)

The following code shows the definition of a callback


handler method in a callback listener class:
1 public class AlertMonitor {
2 @PostPersist
3 public void newAccountAlert(Account acct) {
4 Alerts.sendMarketingInfo(acct.getAccountId(),
acct.getBalance());
5 }
6 }

Ver. 1.0

Slide 27 of 30

Business Component Development Using EJB Technologies


Defining a Callback Handler in a Callback Listener Class (Contd.)

The following code shows an entity class associated with


callback listener class:
1 @Entity
2 @EntityListener(com.acme.AlertMonitor.class)
3 public class Account {
4 @Id
5 Long accountId;
6 Integer balance;
7 boolean preferred;
8 public Long getAccountId() { ... }
9 public Integer getBalance() { ... }
10 @Transient // because status depends upon
non-persistent context
11 public boolean isPreferred() { ... }

Ver. 1.0

Slide 28 of 30

Business Component Development Using EJB Technologies


Defining a Callback Handler in a Callback Listener Class (Contd.)
12 public void deposit(Integer amount) { ... }
13 public Integer withdraw(Integer amount) throws
NSFException {... }
14 @PrePersist public void validateCreate() {
15 if (getBalance() < MIN_REQUIRED_BALANCE) throw new
16 AccountException("Insufficient balance to open an
account");
17 }
18
19 @PostLoad
20 public void adjustPreferredStatus() {
21 preferred =
22 (getBalance() >=
AccountManager.getPreferredStatusLevel());
23 }
24 }

Ver. 1.0

Slide 29 of 30

Business Component Development Using EJB Technologies


Summary

In this session, you learned that:


Interceptors enable the developers to define code that can be
executed before and/or after the execution of an action.
Interceptors are classified as:
Business interceptor method
Life-cycle callback interceptor methods

The life-cycle events generated by session and


message-driven beans are:
PostConstruct event
PreDestroy callback
PostActivate callback
PrePassivate callback

Ver. 1.0

Slide 30 of 30

You might also like