How to create your custom ExceptionHandler in Oracle ADF

Steps:

  • Create a Java class that extends oracle.adf.view.rich.context.ExceptionHandler
  • Create a textfile with the name “oracle.adf.view.rich.context.Exceptionhandler” (without the quotes) and store it in .adfMETA-INFservices (you need to create the “services” folder)
  • In the file, add the absolute name of your custom exception handler class (package name and class name without the “.class” extension)

 

import oracle.adf.view.rich.context.ExceptionHandler;
public class MyCustomExceptionHandler extends ExceptionHandler {

public MyCustomExceptionHandler() {
     super();
}
public void handleException(FacesContext facesContext, 
                            Throwable throwable, PhaseId phaseId) 
                            throws Throwable{
   String error_message;
   error_message = throwable.getMessage();
   //check error message and handle it if you can
   if( … ){  
       //handle exception
       …
   }
   else{
      //delegate to the default ADFc exception handler
       throw throwable;}
   }
}

it is recommended to first try and handle exceptions with the ADF Controller default exception handling mechanism.

Various Scopes in Oracle ADF

Various Scopes in Oracle ADF:

Scope Description
application The application scope lasts until the application stops. Values that you store in a managed bean with this scope are available to every session and every request that uses the application.

Avoid using this scope in a task flow because it persists beyond the life span of the task flow.

session The session scope begins when a user first accesses a page in the application and ends when the user’s session times out due to inactivity, or when the application invalidates the session.

Use this scope only for information that is relevant to the whole session, such as user or context information. Avoid using it to pass values from one task flow to another. Instead, use parameters to pass values between task flows. Using parameters gives your task flow a clear contract with other task flows that call it or are called by it. Another reason to avoid use of session scope is because it may persist beyond the life span of the task flow.

pageFlow Choose this scope if you want the managed bean to be accessible across the activities within a task flow. A managed bean that has a pageFlow scope shares state with pages from the task flow that access it. A managed bean that has a pageFlow scope exists for the life span of the task flow.If another task flow’s page references the managed bean, the managed bean creates a separate instance of this object and adds it to the pageFlow scope of its task flow.
view Use this scope for managed bean objects that are needed only within the current view activity and not across view activities. It defines scope for each view port that ADF Controller manages, for example, a root browser window or an ADF region.

The life span of this scope begins and ends when the current viewId of a view port changes. If you specify view, the application retains managed bean objects used on a page as long as the user continues to interact with the page. These objects are automatically released when the user leaves the page.

request Use request scope when the managed bean does not need to persist longer than the current request.
backingBean A backing bean is a convention to describe a managed bean that stores accessors for UI components and event handling code on a JSF page. It exists for the duration of a request and should not be used to maintain state.

Use this scope if it is possible that your task flow appears in two ADF regions on the same JSF page and you want to isolate each instance of ADF region.

Source: Oracle Docs

Creating a re-organizable list of Items using Drag and Drop in Oracle ADF

Sometimes the requirement is to create a list of UI Items which can be rearranged using Drag and Drop in Oracle ADF, similar to the one in jQuery.

Oracle ADF Drag and Drop doesn’t provide the ability to identify, where the drag object is being dropped in the drag target. Thus we cannot know where to place the dropped element in the list.

here is the solution to the same:
Assumption:
–each element is same and is being iterated in a for loop over a list.
–Here dummy data is being used
Here is the below jsff segment:

<af:forEach var="v" varStatus="vi" begin="0" end="10">
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertAbove}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
    <h:panelGroup styleClass="" id="pg1232">
              <af:outputText value="#{vi.index}" id="ot1"><af:componentDragSource/></af:outputText>
    </h:panelGroup>
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertBelow}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
</af:forEach>

below is the Java Code for the managed bean:

needed imports:

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.datatransfer.DataFlavor;
import oracle.adf.view.rich.datatransfer.Transferable;
import oracle.adf.view.rich.dnd.DnDAction;
import oracle.adf.view.rich.event.DropEvent;

import org.apache.myfaces.trinidad.change.ChangeManager;
import org.apache.myfaces.trinidad.change.MoveChildComponentChange;
import org.apache.myfaces.trinidad.context.RequestContext;

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertBelow(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex + 1, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertAbove(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        //        System.out.println(dropTarget.getParent());
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

this code allows you place rearrange the list of items using drag and drop:

I1
I2
I3
I4
I5
I6
I7
I8

can be converted to by picking up I3 and placing it between I5 and I6 :

I1
I2
I4
I5
I3
I6
I7
I8

ADF – Displaying Multi-Line Text with outputText Component

To display multi-line text, the basic idea is applying the white-space CSS property to the element with one of following values: pre, pre-wrap and pre-line. This property controls the processing of whitespace inside an element. The exact value you need depends on the behavior you want. In this post, I’m using pre-wrap as the example, which means “Sequences of whitespace are preserved. Lines are broken at newline characters, at
, and as necessary to fill line boxes.”. Here’s the code snippet from the skin of the sample application:


.PreWrap {
white-space: -moz-pre-wrap; /* Mozilla /
white-space: pre; /
CSS 2.0 /
white-space: pre-wrap; /
CSS 2.1 /
word-wrap: break-word; /
IE 5.5-7 */
}

In this rule, the word-wrap CSS property specifies whether the break within a word is allowed to prevent overflow when an otherwise-unbreakable string is too long to fit within line box. The property is applies only when the white-space property allows wrapping. The value of break-word means “Normally unbreakable words may be broken at arbitrary points if there are no otherwise acceptable break points in the line.” This property is useful for the cases, such as really long URLs.

Applying Programmatically View Criteria based on Like “%String%” and with IN Clause in Oracle ADF

Use the method below code to apply a view criteria programmatically that has IN clause and Like clause:

        
//Retrieving application module
String filterList="Comma,Separated,List"
ApplicationModule applicationModule =
    Configuration.createRootApplicationModule("","AppModuleLocal");
//retrieving view object

ViewObjectImpl vo =
    (ViewObjectImpl)applicationModule.findViewObject("");
    
//creating a view criteria
ViewCriteria criteria = vo.createViewCriteria();
//creating a view criteria row from criteria to set the condition(ViewCriteriaItem)
ViewCriteriaRow viewRow = criteria.createViewCriteriaRow();

String[] filerItemList = filterList.split(",");

ViewCriteriaItem viewObjectVCRowItem =
    viewRow.ensureCriteriaItem("");
viewObjectVCRowItem.setOperator(JboCompOper.OPER_IN);

for (int i = 0; i < filerItemList.length; i++) {
    viewObjectVCRowItem.setValue(i, filerItemList[i]);
}

ViewCriteriaItem secondVCRowItem =
    viewRow.ensureCriteriaItem("Status");
secondVCRowItem.setOperator(JboCompOper.OPER_LIKE);
    secondVCRowItem.setValue(status);
criteria.addElement(viewRow);
vo.applyViewCriteria(criteria);
vo.executeQuery();

Further manipulations can be done accordingly.

 Courtesy: Krishna Reddy Tumati

ADF – Programatically Applying and Creating View Criteria

Apply an existing View Criteria Programmatically:

public void applyViewCriteria(ViewObjectImpl vo,HashMap criterias) 
{ ViewCriteria vc = vo.getViewCriteria("ViewCriteriaName"); vo.applyViewCriteria(vc); Iterator i = criterias.keySet().iterator(); String key=""; while (i.hasNext()) { key=i.next; vo.setNamedWhereClauseParam(key, criterias.get(key)); } vo.executeQuery(); }

Create a View Criteria Programmatically:

public void createViewCriteria(ViewObjectImpl vo, HashMap criterias)
    {
        ViewCriteria vc = vo.createViewCriteria();
        ViewCriteriaRow vcRow = vc.createViewCriteriaRow();
        Iterator i = criterias.keySet().iterator();
        String key="";
        while (i.hasNext()) {
           key=i.next;
           vcRow.setAttribute(key, criterias.get(key));
           vc.addRow(vcRow);
        }
        vo.applyViewCriteria(vc);
        vo.executeQuery();
    }

Reference Source

Programmatically Populate View Objects Based on ArrayList of custom Bean Class In Oracle ADF

Lets say you have a Custom Bean Class EmpData defined as:

EmpData

And you wish to use the same as a View Object, Then below is the method for the same:

First create a Proxy View Object Class:
ProxyDataSourceObject

Now Create a View Object where it is populated programmatically:
Programmatic_VO

Programmatic_VO_attribs

Programmatic_VO_Java

EmpDataCustomVO

Now Edit the View Object Impl Class:

EmpDataCustomVOImpl

Now you can easily use the View Objects as a normal View Object to be used in View Controller.

Cons: The getDataFromService method will be called again and again whenever the View Object is needed. So try to keep the source separate and apply some tuning logic to the same in order to improve performance of system.

Original Referrence Source

ADFUtils Class: Best for Accessing Components in from the Managed Bean

import java.util.Iterator;
import java.util.Map;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression;

import javax.faces.application.ViewHandler;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import oracle.adf.model.BindingContext;
import oracle.adf.model.DataControlFrame;
import oracle.adf.view.rich.context.AdfFacesContext;

import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;


public class ADFUtils {
    private ADFUtils() {
    }

    /**
     * This method returns any UI component whose id is passed.
     * @param id the id of the component
     * @return the UIComponent
     */
    public static UIComponent getUIComponent(String id) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (facesContext != null) {
            UIViewRoot viewRoot = facesContext.getViewRoot();
            if (viewRoot != null) {
                return viewRoot.findComponent(id);
            }
        }
        return null;
    }


    /**
     * Refreshes the page/viewRoot.
     * @return the viewId of the current page
     */
    public static String refreshViewRoot() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String viewId = facesContext.getViewRoot().getViewId();
        ViewHandler viewHandler =
            facesContext.getApplication().getViewHandler();
        UIViewRoot viewroot = viewHandler.createView(facesContext, viewId);
        viewroot.setViewId(viewId);
        facesContext.setViewRoot(viewroot);
        return viewId;
    }

    /**
     * Invokes the specified function with the specified params.
     * @param functionName the name of the js function
     * @param params the params to be passed
     */
    public static void runJsFunction(String functionName, String params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExtendedRenderKitService extRenderKitSvc =
            Service.getRenderKitService(facesContext,
                                        ExtendedRenderKitService.class);
        extRenderKitSvc.addScript(facesContext,
                                  functionName + "('" + params + "');");
    }

    /**
     * Invokes the specified function with the specified params.
     * @param functionName the name of the js function
     */
    public static void runJsFunction(String functionName) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExtendedRenderKitService extRenderKitSvc =
            Service.getRenderKitService(facesContext,
                                        ExtendedRenderKitService.class);
        extRenderKitSvc.addScript(facesContext, functionName + "();");
    }

    // Get the Component based on given UIComponent ID and refresh the component

    public static void refreshComponent(String pComponentID) {
        UIComponent component = findComponentInRoot(pComponentID);
        refreshComponent(component);
    }


    // Get Faces Context, Get Root Component, Find the given Component From the root component

    public static UIComponent findComponentInRoot(String pComponentID) {
        UIComponent component = null;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (facesContext != null) {
            UIComponent root = facesContext.getViewRoot();
            component = findComponent(root, pComponentID);
        }
        return component;
    }


    // Refresh the Component

    public static void refreshComponent(UIComponent component) {
        if (component != null) {
            AdfFacesContext.getCurrentInstance().addPartialTarget(component);
        }
    }

    // Get the specific  component from a root component tree.

    public static UIComponent findComponent(UIComponent root, String id) {
        if (id.equals(root.getId()))
            return root;

        UIComponent children = null;
        UIComponent result = null;
        Iterator childrens = root.getFacetsAndChildren();
        while (childrens.hasNext() && (result == null)) {
            children = (UIComponent)childrens.next();
            if (id.equals(children.getId())) {
                result = children;
                break;
            }
            result = findComponent(children, id);
            if (result != null) {
                break;
            }
        }
        return result;
    }
  
    /**
     * Programmatic evaluation of EL.
     *
     * @param el EL to evaluate
     * @return Result of the evaluation
     */
    public static Object evaluateEL(String el) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression exp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);

        return exp.getValue(elContext);
    }

    /**
     * Programmatic invocation of a method that an EL evaluates to.
     * The method must not take any parameters.
     *
     * @param el EL of the method to invoke
     * @return Object that the method returns
     */
    public static Object invokeEL(String el) {
        return invokeEL(el, new Class[0], new Object[0]);
    }

    /**
     * Programmatic invocation of a method that an EL evaluates to.
     *
     * @param el EL of the method to invoke
     * @param paramTypes Array of Class defining the types of the parameters
     * @param params Array of Object defining the values of the parametrs
     * @return Object that the method returns
     */
    public static Object invokeEL(String el, Class[] paramTypes,
                                  Object[] params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        MethodExpression exp =
            expressionFactory.createMethodExpression(elContext, el,
                                                     Object.class, paramTypes);

        return exp.invoke(elContext, params);
    }

    /**
     * Sets a value into an EL object. Provides similar functionality to
     * the  tag, except the from is
     * not an EL. You can get similar behavior by using the following...

     * setEL(to, evaluateEL(from))
     *
     * @param el EL object to assign a value
     * @param val Value to assign
     */
    public static void setEL(String el, Object val) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression exp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);

        exp.setValue(elContext, val);
    }
}

Source: Forum

Alternate Link:Alternate, includes Application Module and Binding Utils as well