Thursday, June 14, 2012

How to intercept Oracle ADF lifecycle using ADF Phase Listener

The Oracle ADF lifecycle integrates with the JavaServer Faces request lifecycle. Developers who need to listen and interact with the request cycle may use an ADF Phase Listener to do so. Unlike the standard Phase Listener you define in the faces-config.xml file, the ADF Phase Listener allows you to listen to both of the standard JSF and the ADF phases.
The ADF Phase Listener is defined in a Java class  and configured in the adf-settings.xml file (which you may need to create). To create an ADF Phase Listener, all it takes is to start from a template like shown below and add your logic. 
package listeners;
import oracle.adf.controller.v2.lifecycle.PagePhaseEvent;
import oracle.adf.controller.v2.lifecycle.PagePhaseListener;
import oracle.adf.controller.v2.lifecycle.Lifecycle;


public class PageAdfListener implements PagePhaseListener{  
  public PageAdfListener() { }
  public void afterPhase(PagePhaseEvent pagePhaseEvent) {
    System.out.println("AFTER PHASE" + pagePhaseEvent.getPhaseId() + " " + pagePhaseEvent.getDebugValue());   
    //for example, to listen for the prepare render phase
       int PREPARE_RENDER_ID = Lifecycle.PREPARE_RENDER_ID;
       if (pagePhaseEvent.getPhaseId() == PREPARE_RENDER_ID){
            //...
      }      
  }
  public void beforePhase(PagePhaseEvent pagePhaseEvent) {
  }
}
As shown in the code sample above, you can listen for any phase you are interested in. In this exemple, we want to globally change the PREPARE RENDER phase.

The last step to create an ADF Phase Listener is to configure the adf-settings.xml file. Create the file as shown below in the Application Sources\META-INF directory of your View controller project

<?xml version="1.0" encoding="windows-1252" ?>
<adf-settings xmlns="http://xmlns.oracle.com/adf/settings">
   <adf-controller-config xmlns="http://xmlns.oracle.com/adf/controller/config">
        <lifecycle>
            <phase-listener>
                <listener-id>PageVisitorID</listener-id>
                <class>listeners.PageAdfListener</class>
            </phase-listener>
        </lifecycle>
    </adf-controller-config>
</adf-settings>