Java Reference
In-Depth Information
There are i ve transitional phases: BEFORE _ COMPLETION , AFTER _ COMPLETION , AFTER _ SUCCESS ,
AFTER _ FAILURE , and the default IN _ PROGRESS . In Listing 11‐7, we have not implemented
BEFORE _ COMPLETION . In Listing 11-8 we implement a class that demonstrates event i ring in
successful and failure scenarios.
LISTING 11‐8: Provoke success and failure scenarios
package com.devchronicles.observer;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class Children {
@Resource
SessionContext sc;
@Inject
Event<String> message;
int[] children = new int[3];
public void getSixthChild() {
try {
int sixthChild = children[5]; // Throws an IndexOutOfBounds Exception
} catch (Exception e) {
message.fire("Rollback event occurred.");
System.out.println("Exception caught.");
sc.setRollbackOnly();
}
}
public void getThirdChild() {
int thirdChild = children[2]; // Succeeds
message.fire("Successful event");
}
}
The Children class simulates a successful transaction in the getThirdChild method and an
unsuccessful transaction in the getSixthChild method by causing an IndexOutOfBoundsException .
You'll examine each method to see how the events are observed. The getThirdChild method i res a
String event, passes it the message Successful event , and then i nishes successfully. T he output
from calling this method follows:
Search WWH ::




Custom Search