Sunday 9 November 2014

ADFUtil.java useful class for pro-grammatically handling things in ADF

Hi All,

In ADF, when we are handling things pro-grammatically, we will extensively use  ADFUtility class and here  i am documenting same for my reference and hope that  it may help others as well.



  import java.util.Map;

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

  import javax.faces.context.FacesContext;

  import oracle.adf.model.BindingContext;
  import oracle.adf.model.DataControlFrame;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import java.util.Map;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.model.SelectItem;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.model.binding.DCParameter;

import oracle.adf.share.ADFContext;
import oracle.adf.share.logging.ADFLogger;

import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.component.rich.data.RichTreeTable;
import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.adf.view.rich.util.FacesMessageUtils;

import oracle.binding.AttributeBinding;
import oracle.binding.BindingContainer;

import oracle.binding.ControlBinding;

import oracle.binding.OperationBinding;


import oracle.jbo.ApplicationModule;
import oracle.jbo.Key;
import oracle.jbo.Row;
import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding;
import oracle.jbo.uicli.binding.JUCtrlValueBinding;

import org.apache.myfaces.trinidad.component.UIXTable;
import org.apache.myfaces.trinidad.model.RowKeySet;
import javax.faces.application.FacesMessage.Severity;

import oracle.adf.view.rich.component.rich.RichPopup;



import oracle.javatools.resourcebundle.BundleFactory;
import oracle.javatools.resourcebundle.NamedMessageFormat;


/**
* Provides various utility methods that are handy to
* have around when working with ADF.
*/
  public class ADFUtil {

  /**
  * When a bounded task flow manages a transaction (marked as requires-transaction,.
  * requires-new-transaction, or requires-existing-transaction), then the
  * task flow must issue any commits or rollbacks that are needed. This is
  * essentially to keep the state of the transaction that the task flow understands
  * in synch with the state of the transaction in the ADFbc layer.
  *
  * Use this method to issue a commit in the middle of a task flow while staying
  * in the task flow.
  */
  public static void saveAndContinue() {
  Map sessionMap =
  FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
  BindingContext context =
  (BindingContext)sessionMap.get(BindingContext.CONTEXT_ID);
  String currentFrameName = context.getCurrentDataControlFrame();
  DataControlFrame dcFrame =
  context.findDataControlFrame(currentFrameName);

  dcFrame.commit();
  dcFrame.beginTransaction(null);
  }

  /**
  * 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 <af:setActionListener> 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);
  }
 
 
    public static Object executeOperationBinding(String methodAction,
                                                               Map param) {
            OperationBinding ob = ADFUtil.findOperation(methodAction);

            if (param != null) {
                Map paramOps = ob.getParamsMap();
                paramOps.putAll(param);
            }
            Object result = ob.execute();
            return result;
        }
   
    public static Object executeOperationBinding(String pageDefName, String methodAction,
                                                               Map param) {
            OperationBinding ob = ADFUtil.findOperation(pageDefName,methodAction);

            if (param != null) {
                Map paramOps = ob.getParamsMap();
                paramOps.putAll(param);
            }
            Object result = ob.execute();
            return result;
        }
   
    /**
        * Find an operation binding in the current binding container by name.
        *
        * @param name operation binding name
        * @return operation binding
        */
       public static OperationBinding findOperation(String name) {
           OperationBinding op =
               getDCBindingContainer().getOperationBinding(name);
           if (op == null) {
               throw new RuntimeException("Operation '" + name + "' not found");
           }
           return op;
       }
   
    /**
        * Find an operation binding in the current binding container by name.
        *
        * @param name operation binding name
        * @return operation binding
        */
       public static OperationBinding findOperation(String pageDefName, String name) {
           OperationBinding op =
               findBindingContainer(pageDefName).getOperationBinding(name);
           if (op == null) {
               throw new RuntimeException("Operation '" + name + "' not found");
           }
           return op;
       }
   
    /**
        * Return the Binding Container as a DCBindingContainer.
        * @return current binding container as a DCBindingContainer
        */
       public static DCBindingContainer getDCBindingContainer() {
           return (DCBindingContainer)getBindingContainer();
       }
   
    /**
        * Return the current page's binding container.
        * @return the current page's binding container
        */
       public static BindingContainer getBindingContainer() {
           return (BindingContainer)evaluateEL("#{bindings}");
       }

    /**
        * Find the BindingContainer for a page definition by name.
        *
        * Typically used to refer eagerly to page definition parameters. It is
        * not best practice to reference or set bindings in binding containers
        * that are not the one for the current page.
        *
        * @param pageDefName name of the page defintion XML file to use
        * @return BindingContainer ref for the named definition
        */
       private static BindingContainer findBindingContainer(String pageDefName) {
           BindingContext bctx = getDCBindingContainer().getBindingContext();
           BindingContainer foundContainer =
               bctx.findBindingContainer(pageDefName);
           return foundContainer;
       }
   
   
    /**
     * This method would return the pageFlowScope
     **/
   
    public static Map getPageFlowScope(){
      AdfFacesContext facesCtx=  AdfFacesContext.getCurrentInstance();
      return facesCtx.getPageFlowScope();
    }
   
    /**
     * This method would return the requestScope
     **/
   
    public static Map getRequestFlowScope(){
      ADFContext adfContext = ADFContext.getCurrent();
       return adfContext.getRequestScope();
    }
 
    /**
     * This method will be used to refresh UI component
     **/
   
    public static void refreshUI(UIComponent uiComponent){
      AdfFacesContext adfctx = AdfFacesContext.getCurrentInstance();
      adfctx.addPartialTarget(uiComponent);
    }
   
 
    /**This method returns list of return attribute values of selected rows. It applies additional filter on selected Rows
     * @param pUITable Table component.
     * @param pReturnAttributeName Attribute
     * @return List of attribute values of selected rows.
     */
    public static ArrayList getAttributeValuesOfSelectedFilteredRows(UIXTable pUITable,
                                                             String pReturnAttributeName, String pFilterAttributeName, Object pFilterAttributeValue) {
        RowKeySet selectedRowKeys = null;
        selectedRowKeys = pUITable.getSelectedRowKeys();

        ArrayList objectList = new ArrayList();
        Object selectedObject = null;
        Iterator<Object> iter = selectedRowKeys.iterator();
        while (iter.hasNext()) {
            selectedObject = (List)iter.next();
            JUCtrlHierNodeBinding valBinding = null;
            pUITable.setRowKey(selectedObject);
            valBinding = (JUCtrlHierNodeBinding)pUITable.getRowData();
            Row row = valBinding.getRow();
            Object object = row.getAttribute(pFilterAttributeName);
            if(object.equals(pFilterAttributeValue))
                objectList.add(row.getAttribute(pReturnAttributeName));

        }
        pUITable.setRowKey(null);
        return objectList;
    }
   
    /** This method returns value of an attribute of a selected row. Useful if attribute is not a key attribute.
     * @param pUITable Table component
     * @param pAttributeName
     * @return
     */
    public static Object getAttributeValueOfSelectedRow(UIXTable pUITable,
                                                        String pAttributeName) {
        RowKeySet selectedRowKeys = null;
        selectedRowKeys = pUITable.getSelectedRowKeys();

        Object selectedObject = null;
        Iterator<Object> iter = selectedRowKeys.iterator();
        if (iter.hasNext()) {
            selectedObject = (List)iter.next();
            JUCtrlHierNodeBinding valBinding;
            pUITable.setRowKey(selectedObject);
            valBinding = (JUCtrlHierNodeBinding)pUITable.getRowData();
            Row row = valBinding.getRow();
            pUITable.setRowKey(null);
            return row.getAttribute(pAttributeName);

        }
        return null;
    }
   
    /** This method checks if any row is selected in Tree/Table. Useful to throw error while performing
     * an action on rows but user forget to select rows.
     * @param pUIComponent Tree/Table on which we want to check row selection.
     * @return true if row is selected. false if no row selected.
     */
    public static boolean isRowSelected(UIComponent pUIComponent) {
        RowKeySet selectedRowKeys = null;
        if (pUIComponent instanceof RichTreeTable)
            selectedRowKeys =
                    ((RichTreeTable)pUIComponent).getSelectedRowKeys();
        else if (pUIComponent instanceof RichTable)
            selectedRowKeys = ((RichTable)pUIComponent).getSelectedRowKeys();
        if (selectedRowKeys.size() > 0)
            return true;
        else
            return false;
    }
   

    /**This method adds a message in FacesContext and message would appear in UI.
     * @param pResBundle bundle name like "cnc.pay.invoice.XXCCFringeSetupViewBundle"
     * @param pMessageKey array of message keys.
     * @param pSeverity Severity
     * @param pTokenMap Map of tokens.
     */
    public static void showMessage(String pResBundle, String pMessageKey,
                                   Severity pSeverity, Map<String,Object> pTokenMap) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        String formattedMessage =  getFormattedMessage(pResBundle, pMessageKey, pTokenMap);
       
        FacesMessage fcMessage = null;
        if (FacesMessage.SEVERITY_ERROR.equals(pSeverity) || FacesMessage.SEVERITY_WARN.equals(pSeverity) || FacesMessage.SEVERITY_INFO.equals(pSeverity)){
            fcMessage =  new FacesMessage(pSeverity, formattedMessage, null);
        }
        else{
            fcMessage = FacesMessageUtils.getConfirmationMessage(new FacesMessage(formattedMessage));
        }
        ctx.addMessage(null, fcMessage);
       
    }
   
    /**
     * This method returns bundle message.
     *
     * @param pResBundle bundle name like "cnc.pay.fringe.view.XXCCFringeSetupViewBundle"
     * @param pMessageKey message key.
     * @param pTokenMap Map of tokens.
     * @return
     */
    public static String getFormattedMessage(String pResBundle,
                                             String pMessageKey,
                                             Map<String, Object> pTokenMap) {
        String formattedMessage = null;
        try {
            ResourceBundle rsBundle = BundleFactory.getBundle(pResBundle);
            if (pTokenMap == null)
                formattedMessage = rsBundle.getString(pMessageKey);
            else {
                formattedMessage =
                        (new NamedMessageFormat(pMessageKey)).formatMsg(rsBundle.getString(pMessageKey),
                                                                        pTokenMap);
            }
        } catch (Exception ex) {
            formattedMessage = pMessageKey;
           
        }
        return formattedMessage;
    }
   
    /**
     * This method is used to launch a popup.
     *
     * @param popup popup component which you want to launch.
     * @param alignComponent component with which you want to align.
     * @param alignType
     * @param additionalHints
     * @return
     */
    public static void showPopup(RichPopup popup,UIComponent alignComponent,RichPopup.PopupHints.AlignTypes alignType,RichPopup.PopupHints additionalHints ){
      FacesContext context = FacesContext.getCurrentInstance();
      if(additionalHints == null)
            additionalHints = new RichPopup.PopupHints();
      String alignId = null;
      if(alignComponent != null){
          alignId = alignComponent.getClientId(context);
          additionalHints.add(RichPopup.PopupHints.HintTypes.HINT_ALIGN_ID, alignId);
      }
     
        if(alignType != null){
            additionalHints.add(RichPopup.PopupHints.HintTypes.HINT_ALIGN,  alignType);
        }
     
     
      popup.show(additionalHints);
    }

      public static void showErrorMessage(String msg){
          FacesMessage fm = new FacesMessage(msg);
          fm.setSeverity(FacesMessage.SEVERITY_ERROR);
          FacesContext context = FacesContext.getCurrentInstance();
          context.addMessage(null, fm);
      }
     
    public static void showMessage(String msg){
        FacesMessage fm = new FacesMessage(msg);
        fm.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, fm);
    }

  }

No comments:

Post a Comment