The billpayment Example: Using Events and Interceptors
The billpayment example shows how to use both events and interceptors.
The example simulates paying an amount using a debit card or credit card. When the user chooses a payment method, the managed bean creates an appropriate event, supplies its payload, and fires it. A simple event listener handles the event using observer methods.
The example also defines an interceptor that is set on a class and on two methods of another class.
The PaymentEvent Event Class
The event class, event.PaymentEvent, is a simple bean class that contains a no-argument constructor. It also has a toString method and getter and setter methods for the payload components: a String for the payment type, a BigDecimal for the payment amount, and a Date for the timestamp.
public class PaymentEvent implements Serializable { ... public String paymentType; public BigDecimal value; public Date datetime; public PaymentEvent() { } @Override public String toString() { return this.paymentType + " = $" + this.value.toString() + " at " + this.datetime.toString(); } ...
The event class is a simple bean that is instantiated by the managed bean using new and then populated. For this reason, the CDI container cannot intercept the creation of the bean, and hence it cannot allow interception of its getter and setter methods.
The PaymentHandler Event Listener
The event listener, listener.PaymentHandler, contains two observer methods, one for each of the two event types:
@Logged @SessionScoped public class PaymentHandler implements Serializable { ... public void creditPayment(@Observes @Credit PaymentEvent event) { logger.log(Level.INFO, "PaymentHandler - Credit Handler: {0}", event.toString()); // call a specific Credit handler class... } public void debitPayment(@Observes @Debit PaymentEvent event) { logger.log(Level.INFO, "PaymentHandler - Debit Handler: {0}", event.toString()); // call a specific Debit handler class... } }
Each observer method takes as an argument the event, annotated with @Observes and with the qualifier for the type of payment. In a real application, the observer methods would pass the event information on to another component that would perform business logic on the payment.
The qualifiers are defined in the payment package, described in The billpayment Facelets Pages and Managed Bean.
Like PaymentEvent, the PaymentHandler bean is annotated @Logged, so that all its methods can be intercepted.
The billpayment Facelets Pages and Managed Bean
The billpayment example contains two Facelets pages, index.xhtml and the very simple response.xhtml. The body of index.xhtml looks like this:
<h:body> <h3>Bill Payment Options</h3> <p>Type an amount, select Debit Card or Credit Card, then click Pay.</p> <h:form> <p> <h:outputLabel value="Amount: $" for="amt"/> <h:inputText id="amt" value="#{paymentBean.value}" required="true" requiredMessage="An amount is required." maxlength="15" /> </p> <h:outputLabel value="Options:" for="opt"/> <h:selectOneRadio id="opt" value="#{paymentBean.paymentOption}"> <f:selectItem id="debit" itemLabel="Debit Card" itemValue="1"/> <f:selectItem id="credit" itemLabel="Credit Card" itemValue="2" /> </h:selectOneRadio> <p><h:commandButton id="submit" value="Pay" action="#{paymentBean.pay}" /></p> <p><h:commandButton value="Reset" action="#{paymentBean.reset}" /></p> </h:form> ... </h:body>
The input text field takes a payment amount, passed to paymentBean.value. Two radio buttons ask the user to select a Debit Card or Credit Card payment, passing the integer value to paymentBean.paymentOption. Finally, the Pay command button’s action is set to the method paymentBean.pay, while the Reset button’s action is set to the paymentBean.reset method.
The payment.PaymentBean managed bean uses qualifiers to differentiate between the two kinds of payment event:
@Named @SessionScoped public class PaymentBean implements Serializable { ... @Inject @Credit Event<PaymentEvent> creditEvent; @Inject @Debit Event<PaymentEvent> debitEvent;
The qualifiers, @Credit and @Debit, are defined in the payment package along with PaymentBean.
Next, the PaymentBean defines the properties it obtains from the Facelets page and will pass on to the event:
public static final int DEBIT = 1; public static final int CREDIT = 2; private int paymentOption = DEBIT; @Digits(integer = 10, fraction = 2, message = "Invalid value") private BigDecimal value; private Date datetime;
The paymentOption value is an integer passed in from the radio button component; the default value is DEBIT. The value is a BigDecimal with a Bean Validation constraint that enforces a currency value with a maximum number of digits. The timestamp for the event, datetime, is a Date object initialized when the pay method is called.
The pay method of the bean first sets the timestamp for this payment event. It then creates and populates the event payload, using the constructor for the PaymentEvent and calling the event’s setter methods using the bean properties as arguments. It then fires the event.
@Logged public String pay() { this.setDatetime(Calendar.getInstance().getTime()); switch (paymentOption) { case DEBIT: PaymentEvent debitPayload = new PaymentEvent(); debitPayload.setPaymentType("Debit"); debitPayload.setValue(value); debitPayload.setDatetime(datetime); debitEvent.fire(debitPayload); break; case CREDIT: PaymentEvent creditPayload = new PaymentEvent(); creditPayload.setPaymentType("Credit"); creditPayload.setValue(value); creditPayload.setDatetime(datetime); creditEvent.fire(creditPayload); break; default: logger.severe("Invalid payment option!"); } return "/response.xhtml"; }
The pay method returns the page to which the action is redirected, response.xhtml.
The PaymentBean class also contains a reset method that empties the value field on the index.xhtml page and sets the payment option to the default:
@Logged public void reset() { setPaymentOption(DEBIT); setValue(BigDecimal.ZERO); }
In this bean, only the pay and reset methods are intercepted.
The response.xhtml page displays the amount paid. It uses a rendered expression to display the payment method:
<h:body> <h:form> <h2>Bill Payment: Result</h2> <h3>Amount Paid with <h:outputText id="debit" value="Debit Card: " rendered="#{paymentBean.paymentOption eq 1}" /> <h:outputText id="credit" value="Credit Card: " rendered="#{paymentBean.paymentOption eq 2}" /> <h:outputText id="result" value="#{paymentBean.value}" > <f:convertNumber type="currency"/> </h:outputText> </h3> <p><h:commandButton id="back" value="Back" action="index" /></p> </h:form> </h:body>
The LoggedInterceptor Interceptor Class
The interceptor class, LoggedInterceptor, and its interceptor binding, Logged, are both defined in the interceptor package. The Logged interceptor binding is defined as follows:
@Inherited −@InterceptorBinding @Retention(RUNTIME) @Target({METHOD, TYPE}) public @interface Logged { }
The LoggedInterceptor class looks like this:
@Logged @Interceptor public class LoggedInterceptor implements Serializable { ... public LoggedInterceptor() { } @AroundInvoke public Object logMethodEntry(InvocationContext invocationContext) throws Exception { System.out.println("Entering method: " + invocationContext.getMethod().getName() + " in class " + invocationContext.getMethod().getDeclaringClass().getName()); return invocationContext.proceed(); } }
The class is annotated with both the @Logged and the @Interceptor annotations. The @AroundInvoke method, logMethodEntry, takes the required InvocationContext argument, and calls the required proceed method. When a method is intercepted, logMethodEntry displays the name of the method being invoked as well as its class.
To enable the interceptor, the beans.xml file defines it as follows:
<interceptors> <class>billpayment.interceptor.LoggedInterceptor</class> </interceptors>
In this application, the PaymentEvent and PaymentHandler classes are annotated @Logged, so all their methods are intercepted. In PaymentBean, only the pay and reset methods are annotated @Logged, so only those methods are intercepted.
Running the billpayment Example
You can use either NetBeans IDE or Ant to build, package, deploy, and run the billpayment application.
To Build, Package, and Deploy the billpayment Example Using NetBeans IDE
- From the File menu, choose Open Project.
- In the Open Project dialog, navigate to:
tut-install/examples/cdi/
- Select the billpayment folder.
- Select the Open as Main Project check box.
- Click Open Project.
- In the Projects tab, right-click the billpayment project and select Deploy.
To Build, Package, and Deploy the billpayment Example Using Ant
- In a terminal window, go to:
tut-install/examples/cdi/billpayment/
- Type the following command:
ant
This command calls the default target, which builds and packages the application into a WAR file, billpayment.war, located in the dist directory.
- Type the following command:
ant deploy
To Run the billpayment Example
- In a web browser, type the following URL:
http://localhost:8080/billpayment
The Bill Payment Options page opens.
- Type a value in the Amount field.
The amount can contain up to 10 digits and include up to 2 decimal places. For example:
9876.54
- Select Debit Card or Credit Card and click Pay.
The Bill Payment: Result page opens, displaying the amount paid and the method of payment:
Amount Paid with Credit Card: $9,876.34
- (Optional) Click Back to return to the Bill Payment Options page.
You can also click Reset to return to the initial page values.
- Examine the server log output.
In NetBeans IDE, the output is visible in the GlassFish Server 3+ output window. Otherwise, view domain-dir/logs/server.log.
The output from each interceptor appears in the log, followed by the additional logger output defined by the constructor and methods.