13.9. Examples

The events mechanism is quite powerful, in this section of the chapter we will see few simple examples to explain how it works.

13.9.1. UserAuthenticationEvent example

In this example, we will create a simple counter of the number of logged-in registered users. In order to do that we just need to keep track of Sign-in and Sign-out events.
First, let's write our listener. It just a class that will implement org.jboss.portal.api.event.PortalEventListener and its unique method void onEvent(PortalEventContext eventContext, PortalEvent event). Here is such an example:
package org.jboss.portal.core.portlet.test.event;


public class UserCounterListener implements PortalEventListener
   /** Thread-safe long */
   private final SynchronizedLong counter = new SynchronizedLong(0);

   /** Thread-safe long */
   private final SynchronizedLong counterEver = new SynchronizedLong(0);
   public void onEvent(PortalEventContext eventContext, PortalEvent event)
      if (event instanceof UserAuthenticationEvent)
         UserAuthenticationEvent userEvent = (UserAuthenticationEvent)event;
         if (userEvent.getType() == UserAuthenticationEvent.SIGN_IN)
         else if (userEvent.getType() == UserAuthenticationEvent.SIGN_OUT)
         System.out.println("Counter     : " + counter.get());
         System.out.println("Counter ever: " + counterEver.get());
On this method we simply filter down to UserAuthenticationEvent then depending on the type of authentication event we update the counters. counter keeps track of the registered and logged-in users, while counterEver only counts the number of times people logged-in the portal.
Now that the Java class has been written we need to register it so that it can be called when the events are triggered. To do so we need to register it as an MBean. It can be done by editing the sar descriptor file: YourService.sar/META-INF/jboss-service.xml so that it looks like the following:
<?xml version="1.0" encoding="UTF-8"?>
      <attribute name="RegistryId">counter_listener</attribute>
      <attribute name="ListenerClassName">
This snippet can be kept as it is, providing you change the values:
  • name: Must follow the pattern: portal:service=ListenerService,type={{UNIQUENAME}}
  • RegistryId: Must match the type (here: counter_listener)
  • ListenerClassName: Full path to the listener (here: org.jboss.portal.core.portlet.test.event.UserCounterListener).
That's it - we now have a user counter that will display it states each time a user logs-in our logs-out.