Tuesday, October 30, 2012

How to store values into various scopes in ADF

Subject :  How to store various values into various scopes(Application, PageFlow, Session, Request) in ADF

Solution

Setting values into various scopes


FacesContext fx =FacesContext.getCurrentInstance();

// Set Into Application Scope
ExternalContext exContext =fx.getExternalContext();
exContext.getApplicationMap().put("key","value");

// Set Into Request Scope
ExternalContext exContext =fx.getExternalContext();
exContext.getRequestMap().put("key","value");


// Set Into Session Scope
ExternalContext exContext =fx.getExternalContext();
exContext.getSessionMap().put("key","value");


// Set Into PageFlow Scope
RequestContext.getCurrentInstance().getPageFlowScope().put("key","value);

Retrieving Values.

RequestContext.getCurrentInstance().getPageFlowScope().get(name);

exContext.getApplicationMap().get("key");


Thursday, October 25, 2012

How to pass parameters to Popup Window in ADF


Subject :  How to pass parameters to a popup window. For eg : Page fragment displays employee details in a <af:table> format , By selecting any employee name for a specific row we are launching a popup and we need to pass the selected row specific employee name to popup window

Solution



<af:column id="c2" headerText="EmpName">
// Set clientComponent vlaue = true, define clientAttribute and set emp Name value
  <af:outputText value="EmpName" id="ot1" clientComponent="true">
     <af:clientAttribute name="empName" value="#{row.lastName}"/>
// Show popup when mou mouse Hover
     <af:showPopupBehavior popupId="::p1" triggerType="mouseHover"  
                           align="endAfter" alignId="ot1"/>
  </af:outputText>
</af:column>




<af:popup id="p1" launcherVar="source" contentDelivery="lazyUncached" eventContext="launcher">
     <af:panelFormLayout id="pfl1">
<af:panelLabelAndMessage label="EmployeeName" id="plam1">
<af:outputText value="#{viewScope.ename}" id="ot5"/>
</af:panelLabelAndMessage>
</af:panelFormLayout>
<af:setPropertyListener from="#{source.attributes.empName}" 
                           to="#{viewScope.ename}" type="popupFetch"/>
</af:popup>


Monday, October 22, 2012

How to get Filtered Rows in View Object using ADF


Subject :
 If you need to get a collection of rows from a view object based on some filtered criteria, Follow the below solution , To explain in detail For eg : You could have got 100 rows after performing a search on EmployeeROVO , But if you want to get rows from the EmployeeROVO only where employee status equals 'Active' , then you don't need to re query the view object , You can filter the rows from the row set itself

Solution #1


// Status & Qualification - Attribute name        
RowQualifier rq =
          new RowQualifier("Status= '" + row1.getEmpStatus() +
                           "' AND Qualification= '" +
                           row1.getQualification() + "'");

        Row[] rows = empVO.getFilteredRows(rq);

Solution #2

// First parameter is attribute name , Second attribute is value of the attribute that you want to filter
Row[] rows = empVO.getFilteredRows("Status","Active");

How to use findByKey() in ADF


Subject : 

   To find a specific row from a Row Set Iterator using findByKey() and setting the row as a current Row to a specific view object

Solution#1 - To get a specific row in Application Module Impl class


//Primary key value , Specify the data type accordingly
    String empID= "EMP001";
   
    // 1. Get the View Object instance
       EmployeeVO empVO = getEmployeeVO();
 
    // 2. Create a Key object
    Key key = new Key(new Object[] { empID });
   
    //3. Get the RowSetIterator Object
    RowSetIterator rsi = empVO.createRowSetIterator(null);
   
    //4. Find the row in the Iterator using findByKey funtion by passing Key object
    Row row = rsi.findByKey(key, 1)[0];
   
   // 6. Set the Current row in Iterator (findByKey does not Navigate to current row)
    rsi.setCurrentRow(row);


Solution#2 - To get a specific row in Managed Bean


//Primary key value , Specify the data type accordingly
    String empID= "EMP001";
   
    // 1. Access the binding container
    DCBindingContainer bc = (DCBindingContainer)getBindings();
 
   // 2. Find a named iterator binding
    DCIteratorBinding iter =
      (DCIteratorBinding)bc.findIteratorBinding("EmployeeVOIterator");
 
    // 3. Create a Key object
    Key key = new Key(new Object[] { empID});
   
    //4. Get the RowSetIterator Object
    RowSetIterator rsi = iter.getRowSetIterator();
   
    //5. Find the row in the Iterator using findByKey funtion by passing Key object
    Row row = rsi.findByKey(key, 1)[0];
   
   // 6. Set the Current row in Iterator (findByKey does not Navigate to current row)
    rsi.setCurrentRow(row);


 


Friday, October 19, 2012

How to Refresh an UI Component from Backing bean in ADF






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

    private 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

    private 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

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

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

    private 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;
    }



Thursday, October 18, 2012

to_char() and to_date() functions in SQL



Very common usage especially while dealing with Date/Time columns while querying from database.

To update a specific date column with a specific Date and Time,


update employee set hire_date= to_date('101812 19:16:16', 'MMDDYY HH24:MI:SS' ) where emp_id=12

Similarly, If you want to to query Date column with Time stamp,

select to_char(hire_date,'MMDDYY HH24:MI:SS') from emp

Monday, October 8, 2012

If you are not seeing Top Line Filter for af:table

Though you have set sortable=true and filterable =true to your <af::table> component, sometimes you may still not find top line filters for <af:table> columns.

Below are the points, you may have to validate.

1.Define searchRegion in respective Page Definition


<searchRegion Binds="EmpViewIterator" Criteria=""
                  Customizer="oracle.jbo.uicli.binding.JUSearchBindingCustomizer"
                  id="EmpViewQuery"/>

2. Make sure <af:table> component should have below two attributes


       filterModel="#{bindings.EmpViewQuery.queryDescriptor}"
       queryListener="#{bindings.EmpViewQuery.processQuery}"


Tuesday, October 2, 2012

How to get Application Module Instance in Non ADF Projects



If you have a requirement to get instance of  an application module in Non ADF Projects , Follow the below code



import oracle.jbo.ApplicationModule;
import oracle.jbo.client.Configuration;


ApplicationModule am =Configuration.createRootApplicationModule("com.fm.model.emp.appmodule.EmployeeAppModule","EmployeeAppModuleLocal")


Note : This is not a best standard to follow in any of ADF related projects, This can be followed most likely in Web services or Junits.

Saturday, September 29, 2012

Error -Could not create the Java virtual machine" in Jdeveloper 11g

If you notice below error while starting Weblogic server using Jdeveloper 11g, Try below options, It may resolve the issue.

"Could not create the Java virtual machine" in Jdeveloper 11g"

Right click on My Computer, go to properties->Advanced->Environment Variables.
In user Variables add a New variables with below details:

Variable name: EXTRA_JAVA_PROPERTIES
Variable Valute: -Xms256m -Xmx256m

Thursday, September 27, 2012

How to determine the selected tab name with component


Use Case :  If there are multiple <af:showDetailTab> components in <af::pnaelTabbed> , How to identify what tab has been selected ?

Solution :   Use <af:setPropertyListener> component inside <af:showDetailTab> and specify 'type =disclosure' and set a specific value to a page flow scope variable or any binding attribute.



            <af:showDetailItem text="Employee" id="sdi2" >
                <af:setPropertyListener from="EMP"
                                        to="#{bindings.TabName.inputValue}"
                                        type="disclosure"/>
              </af:showDetailItem>


#{bindings.TabName.inputValue} - View object attribute Or you can also specify #{pageFlowScope.tabName}

Tuesday, September 25, 2012

How to use returnListener in ADF


Use case : If you have to invoke a method before any 'Return' activity from any event (eg : Popup, dialog, etc..)

Solution : Use 'returnListener' component as below


     <af:commandButton text="Employee Lookup" id="cb4"
         rendered="true" 
         action="planlookup" 
         windowEmbedStyle="window" useWindow="true" 
         windowModalityType="modeless" windowHeight="480" 
         windowWidth="650"
         returnListener="#{pageFlowScope.empBean.onReturn}"/>

                                           

AFStretchWidth



Specify below styleClass for <af::panelCollection> and <af:panelStrechLayout> components to automatically adjust the width of containing UI Components

 styleClass="AFStretchWidth"


Saturday, September 22, 2012

How to enable Content Style to 'Upper Case' while typing in Input text box


Use Case : Always enable 'Upper Case' while typing for any input text component

Solution :  Set 'contentStyle' attribute value to 'text-transform:uppercase' for all input components.


Wednesday, September 19, 2012

How to keep track of history data using 'Effective Dated Entities' using ADF


Usecase :   How to keep track of database entries with all the previous changes from the time when the row got created
   - > How many times a specific row has been modified ?
   - > Who are all modified a specific row when and what modified ?

Approach
              - Create below four columns in Database table, synchronize the respective entity to reflect these attributes.




 - Modify the Entity Object to 'EffectiveDated' , Open the Entity, Select 'General' , Modify the 'Effective Date Type' attribute to 'EffectiveDated' using property inspector.


 - Set 'Sequece' attribute value to 'true' for 'EffectiveSeq' attribute using Property Inspector

 - Set 'Sequece Flag' attribute value to 'true' for EffectiveSeqFlag' attribute using Property Inspector


 - Set 'Start Date' attribute value to 'true' for 'StartDate' attribute using Property Inspector
 - Set 'End Date' attribute value to 'true' for 'EndDate' attribute using Property Inspector

- Set 'Effective Dated' attribute of corresponding View Object to 'true' using property inspector

- Finally, Set the 'EffeciveDateMode' at row level, You can set this property wherever needed based on the requirement, In this example, I am setting this at constructor of the Row Impl class, so whenever new row inserted/updated/deleted/created this will be invoked and set the value accordingly.
                  
-  Below shows what exactly meant for each mode level in ADF, Mode level can be set based on the requirement.

Row.EFFDT_UPDATE_MODE: When an effective dated row is updated in "update" mode, the modified row is end dated on the effective date and a new row is created with the changed values.

Row.EFFDT_UPDATE_CHANGE_INSERT_MODE: When an effective dated row is updated in "change insert" mode, the modified row is end dated on the effective date and a new row is inserted that fits between the effective date and the start date of the next row in the effective date time line.

Row.EFFDT_UPDATE_CORRECTION: When an effective dated row is updated in "correction" mode, the effective start date and effective end date is left unchanged.

Row.EFFDT_UPDATE_NEW_EARLIEST_CHANGE_MODE: Updating in "new earliest change" mode is supported only in Multiple Changes Per Day.

Row.EFFDT_UPDATE_OVERRIDE_MODE: When an effective dated row is updated in "override" mode, the modified row is end dated on the effective date and the start date of the next row in the effective date time line is set to effective date + 1 day.  

Row.EFFDT_NONE_MODE: Default state of the effective date mode on the row.
ADF Framework automatically updates for all the above attributes upon Create/Update/Delete operations

- All set, Run the app module, Create new row and see how the values are populated in DB table automatically.. ADF will take care of populating these values based on 'EffectiveDateMode'

   Thanks - I hope this may help.
             

How to generate Sequence Number using Groovy expression



Usecase : Generate a sequence number at entity level using Groovy expression
Solution : Goto Entity -> Select the attribute with 'Number' as data type -> Default Values -> Choose expression -> Paste below groovy expression ( Modify with your sequence name)

       

            (new oracle.jbo.server.SequenceImpl("XXATDTPR_AA_DET_S", adf.object.getDBTransaction())).getSequenceNumber()
       
 
(new oracle.jbo.server.SequenceImpl("EMPLOYEES_SEQ",adf.object.getDBTransaction())).getSequenceNumber()

Tuesday, September 18, 2012

How to use

Use case - Upon clicking on some button, Set a value to specific attribute

Solution : <af:setPropertyListener> component allows you to set a specific value to a attribute upon clicking on a button or changing a value for any component.

Ex :


              <af:commandButton text="Save" id="cb1"
                                action="#{pageFlowScope.EmployeeBean.addEmployee}"
                                immediate="true">
                <af:setPropertyListener from="#{bindings.EmpName.inputValue}"
                                        to="#{sessionScope.EmpName}"
                                        type="action"/>
              </af:commandButton>

from/to - This value can be anything, hard coded value, binding value or from any scope variable.


Wednesday, September 12, 2012

Filtering af:table Without Using ADF Model



I would like to share below URL, This is very useful especially if you want to perform 'Filter' on <af:table> component without using ADF Model.

http://jobinesh.blogspot.in/2012/03/filtering-aftable-without-using-adf.html


Tuesday, September 4, 2012

How to invoke various methods using Groovy Expressions

One of the interesting feature in ADF is using 'Groovy Expressions' , Using these expressions we can invoke various methods defined in ViewObjectImpl or Application Module Impl or access Application Module UserData session object

1. How to invoke a method defined in ViewObjectImpl class for a given specific attribute which is part of the same view object

You can define any method in ViewObject Impl something like as below

             public String getEmployeeName(){
                         return "EMP123"
             }

Define an attribute in a view object and modify its value (Groovy expression) as below
        adf.object.viewObject.getEmployeeName() - This will invoke the method defined in ViewObjectImpl class and hold the returned value.

2. How to access userData session object using Groovy expressions

Get the userData hash table in AM Impl class, and store whatever values you need as shown below

             Hashtable userData = getDBTransaction().getSession().getUserData();
             userData.put("employeeID","1234");

Use below groovy expression in any of the View objects which are part of respective application module , and access the data stored in userData session object.

          adf.userSession.userData.employeeID
Below is sample code how to get the user Session Data in App Module
Hashtable userdata = getDBTransaction().getSession().getUserData();

3. How to access a method defined in Application Module in any view object

    use below groovy expression in any of the view object which is part of respective application module
        adf.object.applicationModule.getEmployeeIDByName()

Monday, September 3, 2012

Jdeveloper Shortcut Keys

Below Jdeveloper Shortcut keys may helpful during development

1.If you have a larger application and you don't know specific class/object located , Go to Source of the file, then press Alt+Home button - This will take you to the corresponding project & Package where the selected file belongs.

Friday, August 24, 2012

How to increase Local weblogic server log level


If you have to see the more detailed logs in your  local weblogic server ( Jdeveloper) logs, set the below -D property in a project


- Right click on the project, ( If you are running any UI component, then choose ViewController) Project Properties -> Run/Debug/Profile -> Select 'Default' Configuration -> Edit
- Paste below -D command as shown below.

-Djbo.debugoutput=console


How to change the Log level in EM

login to EM via:  https://fortunemindssoa.com/em

2) navigate on the left side:  WebCenter -> Portal -> Spaces

3) select WebCenter Portal (11.1.1) (WC_Spaces1)

4) from pulldown menu at top navigate:  Logs -> Log Configuration

5) Make sure Runtime Loggers view is selected

6) For  Root Logger  change from  TRACE:32 (FINEST) to WARNING:1 (WARNING)

7) click APPLY

8) select WebCenter Portal (11.1.1) (WC_Spaces2)

9) from pulldown menu at top navigate:  Logs -> Log Configuration

10) Make sure Runtime Loggers view is selected

11) For  Root Logger  change from  TRACE:32 (FINEST) to WARNING:1 (WARNING)

Monday, August 6, 2012

How to create a new row at specific index

Greetings !!

  I would like to briefly explain about inserting a new row in a view object at a specified index.


Create a method like below in VOImpl, and invoke this method by passing 'Row' and index.


  public void insertRow(EmpVORowImpl pRow,int pIndex)
  {
    int rangesize = getViewObject().getRangeSize();
    getViewObject().setRangeSize(-1);
    super.insertRowAtRangeIndex( pIndex , pRow);
    getViewObject().setCurrentRow(pRow);
    getViewObject().setRangeSize(rangesize);
  }



 

Wednesday, August 1, 2012

How to identify whether a row has been modified or not

There is an easy way to find whether a row has been modified/deleted/created in ADF framework, This works only for Entity based view objects which are based on entity object.


      Iterator tbiter =
        EmployeeEOImpl.getDefinitionObject().getAllEntityInstancesIterator(getDBTransaction());
      while (tbiter.hasNext())
      {
        
EmployeeEOImpl eoImpl = (EmployeeEOImpl) tbiter.next();
if (eoImpl.getEntityState() == Entity.STATUS_NEW || eoImpl.getEntityState() == Entity.STATUS_MODIFIED || eoImpl.getEntityState() == Entity.STATUS_DELETED) {
                  // Add your logic here
        }

Monday, July 30, 2012

How to configure a specific browser in Jdeveloper

Greetings,


There is a cool feature in Jdeveloper, you can configure any type of browser that you want to launch when your web application starts up,


How to get a UI component in Backing bean without binding to a backing bean

Hello,

I thought of sharing useful tip, how to get a UI component ( SelectOneChoice, InputText, etc..) instance in a backing bean without exactly binding a UI component to a backing bean. This is very useful especially building complex UI screens and avoid binding too many UI components to a backing bean

Follow the below code in your backing bean


    UIComponent comp = null;
    FacesContext facesCtx = FacesContext.getCurrentInstance();
    if (facesCtx != null)
    {
      UIComponent root = facesContext.getViewRoot();
      comp = findUIComponent(root, pComponentId);
}


    public UIComponent findUIComponent(UIComponent pBase, String pID) {
        if (pID.equals(pBase.getId()))
            return pBase;


        UIComponent child = null;
        UIComponent result = null;
        Iterator childrens = pBase.getFacetsAndChildren();
        while (childrens.hasNext() && (result == null)) {
            child = (UIComponent)childrens.next();
            if (pID.equals(child.getId())) {
                result = child;
                break;
            }
            result = findUIComponent(child, pID);
            if (result != null) {
                break;
            }
        }
        return result;
    }

Thursday, July 26, 2012

How to Display Error/Warning/Information Messages

This blog explains about printing error/waring/information messages from backing bean & application module impl class

Step1: Displaying error message from backing bean


       

import javax.faces.context.FacesContext;
import javax.faces.application.FacesMessage
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error while Saving","Error while saving")
facesContext.addMessage(null,msg);




Step2: Displaying Information message from backing bean



       
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Saved Successfully",
                                    "Saved Successfully")
facesContext.addMessage(null,msg);





Step3: Displaying Warning message from backing bean


       
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Saved Successfully",
                                    "Saved Successfully")
facesContext.addMessage(null,msg);
Step4: Displaying Error Messages from Application Module
throw new JboException("Error");
Step5: Displaying Warning message from Application Module
getDBTransaction().addWarning(new JboWarning("Warning"));










Wednesday, July 25, 2012

How to invoke Application Module method from backing bean

It would be common requirement to invoke a application module method from the backing bean. Unless if it is really required then only advisable to write a separate method in backing bean to invoke application module method. Follow the below steps to achieve this

Step1 :  Define the application module method in respective page definition as shown in below screen shot
 - Expose the method that you invoke in client interface, Goto Page Definition bindings and add the method bindings as shown below


Step2:  Write the below code in backing bean to invoke application module method

       

import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.binding.BindingContainer;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import oracle.binding.OperationBinding;

  FacesContext facesContext = FacesContext.getCurrentInstance();
  Application app = facesContext.getApplication();
  ExpressionFactory elFactory = app.getExpressionFactory();
  ELContext elContext = facesContext.getELContext();
  ValueExpression valueExp =
    elFactory.createValueExpression(elContext, "#{bindings}", Object.class);
  BindingContainer binding= (BindingContainer)valueExp.getValue(elContext);
  OperationBinding operationBinding=binding.getOperationBinding("createCurrentCustomerRow");
  // Set the Input parameters to the operation bindings as below
     operationBinding.getParamsMap().put("pCustomerID", "100");  
  // Invoke the Application module method
  operationBinding.execute();
  // Get the result from operation bindings
  Object obj =operationBinding.getResult();
       
 


Alternative approach
import oracle.binding.OperationBinding;
   /**
    * This method returns the Operation Bindings based on given input opeation name
    */
    public static OperationBinding getOperationBinding(String pOperationName) {
        BindingContainer bc = BindingContext.getCurrent().getCurrentBindingsEntry();
        return bc.getOperationBinding(pOperationName);
    }

// Below is the code snippet to invoke above method

                OperationBinding oBindings =
                    getOperationBinding("getEmployeeDetails");
// Pass Input parameters
                oBindings.getParamsMap().put("empID", locRow.getDealerId());
                oBindings.getParamsMap().put("empLocID",
                                             locRow.getDealerLocationId());
                oBindings.execute();



How to get RowImpl class in backing bean

It would be common requirement in ADF to get an instance for a RowImpl class in backing bean, Backing bean is associated to a page fragment, Page fragment page definition binds to a respective VOIterator.

Below are the steps to get get Row Instance in backing bean.

Step1:  Bind the view object to page definition as shown in below screen shot


Step2:   Follow the below code in Backing bean


import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.binding.BindingContainer;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;


private Row getRowFromBinding(){
FacesContext facesContext = FacesContext.getCurrentInstance();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
 elFactory.createValueExpression(elContext, "#{bindings}", Object.class);
DCBindingContainer binding= (DCBindingContainer)valueExp.getValue(elContext);

 // Here you have to pass the VOIterator name and get the corresponding Iteratorbinding

DCIteratorBinding itrBinding=binding.findIteratorBinding("LoactionPoolViewIterator")
Row row =itrBinding.getCurrentRow();
}

How to progrmatically List of Values in SelectOneChoice

This blog explains about how to programatically populate list of values dynamically in a <af:SelectOneChoice> component


Step1 : Drag <af:selectOneChoice> component from component pallet to page

Step2 : JSFF - Bind <f:selectItems> to a backing bean method as shown below.

 <af:selectOneChoice value="#{bindings.CustomerID.inputValue}"
             label=""
             required="#{bindings.CustomerID.hints.mandatory}"
             shortDesc="#{bindings.CustomerID.hints.tooltip}"
             id="cusID" autoSubmit="true"
             valuePassThru="true">
       <f:selectItems 
                value="#{pageFlowScope.EquipmentPoolBean.customerList}"
                id="si2"/>
       </af:selectOneChoice>
           
 Step2:  Implement corresponding backing bean method to return List<SelectItem> as shown below
   

       

   public List getCustomerList()
  {
// Prepare list of values based on your requirement
    List customerList = new ArrayList();
    customerList.add(new SelectItem("CUST1","Customer1");
    customerList.add(new SelectItem("CUST2","Customer2");
    customerList.add(new SelectItem("CUST3","Customer3");
    return customerList;
  }
       
 




Monday, July 23, 2012

How to get a selected row from af:table component in backing bean

Hello,
  This might be very common requirement for any ADF developer , to get a selected row(s) from <af:table> component in a backing bean.

// Table Binding
<af:table value="#{bindings.EmpVO.collectionModel}" var="row"
          rows="#{bindings. EmpVO .rangeSize}"
          emptyText="#{bindings. EmpVO .viewable ? 'No data to display.' : 'Access Denied.'}"
          fetchSize="#{bindings. EmpVO .rangeSize}"
          rowBandingInterval="0"
          rowSelection="multiple" id="t1"
          styleClass="AFStretchWidth" columnSelection="multiple"
          first="0" contentDelivery="immediate" autoHeightRows="10"
          binding="#{pageFlowScope.ExampleBean.employeeTable}">

Below approach is advisable, If multiple selection rows required 

       

// Get the instance for table component in backing bean
UIXTable table = getEmployeeTable();
// Get the Selected Row key set iterator
Iterator selectionIt = table.getSelectedRowKeys().iterator();
while(selectionIt.hasNext()){
Object  rowKey = selectionIt.next();
 table.setRowKey(rowKey);
 int index = table.getRowIndex(); 
      FacesCtrlHierNodeBinding row =
        (FacesCtrlHierNodeBinding) table.getRowData(index);
Row selectedRow = row.getRow();
}
       
 


-- Below approach is advisable if there is only single row selection is enabled.


       

// Get the instance for table component in backing bean
UIXTable table = getEmployeeTable();
// Get the Selected Row key set iterator
Iterator selectionIt = table.getSelectedRowKeys().iterator();
while(selectionIt.hasNext()){
Object  rowKey = selectionIt.next();
table.setRowKey(rowKey); int index = table.getRowIndex();
FacesCtrlHierNodeBinding row = (FacesCtrlHierNodeBinding) table.getRowData(index);
Row selectedRow = row.getRow();
}
       
 




Tuesday, July 10, 2012

How to get Selected Value or Selected Index from SelectManyChoice ADF Component



af:selectManyChoice : This component is very useful especially if you have a requirement to display a list values and provide the option to select more than one value from the drop down. For each item displayed as part of List will have a Check box, so that user can select more than one check box from the drop down list.






How to make this component on Page fragment ?  Create a View Object on model layer, and drag it as selectManyChoice on to the page fragment.








Write a java method in backing bean as below to fetch selected values or indices.

    BindingContext bc = BindingContext.getCurrent();
    DCBindingContainer binding =
      (DCBindingContainer) bc.getCurrentBindingsEntry();
    JUCtrlListBinding splHandlBinding =
      (JUCtrlListBinding) binding.get("SpecialHndlgLOVVA");
    Object[] splHandling = splHandlBinding.getSelectedValues();


Here is the code to get selected indices values



    BindingContext bc = BindingContext.getCurrent();
    DCBindingContainer binding =
      (DCBindingContainer) bc.getCurrentBindingsEntry();
    JUCtrlListBinding splHandlBinding =
      (JUCtrlListBinding) binding.get("SpecialHndlgLOVVA");
    Object[] splHandling = splHandlBinding.getSelectedIndices();






Monday, June 18, 2012

ADF : MDS-00013: no metadata found for metadata object

Problem : ADF : MDS-00013: no metadata found for metadata object
Solution : Make sure when you refactor Model project especially package names, Jdeveloper ignores to refactor the updated package names in Model.jpx and some other xml files, so you have to manually correct those package names, Remove the EAR file from JDeveloper\system11.1.1.4.37.59.23\o.j2ee\drs folder, Clean All, Make All and run your application. These steps resolved my problem.


Thursday, April 12, 2012

Save/Delete Master Detail Data using ADF 11g

Requirement # Save both Master and Detail data in a single transaction without throwing any error.
Solution : Open Entity association.xml ->Relationships->Behavior->Check 'Composition association' option
Requirement # All the child related data should get deleted from database upon deleting the parent record from database table
Solution:Open Entity association.xml ->Relationships->Behavior->Check 'Composition association' option, check ' Implement Cascade Delete'

Usage of overriding postChanges() in EntityImpl class.

push the middle-tier changes to the database without actually committing.
Scenario # You have a Master and detail tables and there is no foregin key relation ship, You may have to get the Master Primary key and set to child Entity, DBTransaction.commit() should first save the master record into Database then upon successful saving master recrod it should save the child recrod. So that dbTransaction.commit() shound't throw any 'Key Not found' related exceptions while saving both master and detail data in a single trascation.
Solution : postChange() override this method in EntityImpl class, what this will do is Push the middle-tier database related changes to database without actually performing commit, so that when child record gets inserted into database without any errors.
Refer below for more information http://docs.oracle.com/cd/B14099_19/web.1012/b14022/oracle/jbo/server/EntityImpl.html#postChanges_oracle_jbo_server_TransactionEvent_ Override below two methods in both master and child EOImpl classes
MasterEOImpl.java
public void postChanges(TransactionEvent TransactionEvent) {
if (getPostState() == STATUS_NEW) {
mNewServiceProviderCostsBeforePost = (RowSet) getServiceProviderCostEO();
}
super.postChanges(TransactionEvent);
}
ChildEOImpl.java
public void postChanges(TransactionEvent e)
{
if (getPostState() == STATUS_NEW getPostState() == STATUS_MODIFIED) {
MasterEOImpl masterEO= getMasterEO();
if (masterEO!= null) {
if (masterEO.getPostState() == STATUS_NEW) {
masterEO.postChanges(e);
}
}
}
super.postChanges(e);
}
and also override below methods in MasterEOImpl.java
refreshFKInNewContainees() - Iterate the child RowSet and set the primary key then close the rowSetIterator.
handlePostChangesError() - Override this method , If any error happens this will get invoked and close row set iterator.






Monday, April 9, 2012

How to Configure AM Pool size

By default AM pool size is '25', So all the AM instances can be shared across multiple sessions, If you want to see how an UI application behaves in Prod base environments when number of users logged more than expected, You can make the AM pool size to as minimum as and access the applications in multiple browsers, and AM instances can be shared across multiple sessions and you will see how application performs.

Right click on UI Project ->Project Properties-> Run/Debug/Profile->Select Default and click on Edit -> Enter the below -D command and click on ok


-Djbo.ampool.minavailablesize=1 -Djbo.recyclethreshold=1 -Djbo.failover=true

Thursday, March 15, 2012

How to get selected rows from View object in an Application Module based on specific value on an attribute

I have noticed many times while developing ADF applications, Most of us having a common requirement for instance - How to get selected rows from View object in an Application Module based on specific value on an attribute ?

The view object might be having 50K rows displayed on screen out of it user could have selected less number of rows. Instead of iterating all the rows to determine 2 selected rows out of it, We can always use getFilteredRows() method on VO and get the array of selected rows.

Row[] selRowArr = vo.getFilteredRows("RowChkFlg", Boolean.TRUE);

In this example, RowChkFlg is one of the boolean attribute dragged onto the screen and allows to select row.

Monday, March 5, 2012

How to get a specific component in Backing bean without binding to backing bean using ADF ?

Below snippet provides a way to get a selected ADF UI RichComponent in backing bean without actually binding the component to a backing bean or managed bean. This will help you to avoid too many bindings in any managed or backing bean

private static UIComponent findUIComponent(UIComponent pRootComponentString pComponentId)
{
if (pComponentId.equals(pRootComponent.getId()))
return pRootComponent;
UIComponent kid = null;

UIComponent result = null;
Iterator kids = pRootComponent.getFacetsAndChildren();
while (kids.hasNext() && (result == null))
{
kid = (UIComponent) kids.next();
if (pComponentId.equals(kid.getId()))
{
result = kid;
break;
}
result = findComponent(kid, pComponentId);
if (result != null)
{
break;
}
}
return result;
}

How to get a Value of SelectOneChoice Component in Backing bean?

There is a no way to get the short code of selected Value for component using ADF framework in Managed bean or backing bean, It always returns 'Index' instead actual value, This is a bug with ADF framework. The easy workaround to achieve this functionality is as below

// This will set the new Index value 

JSFUtils.setExpressionValue("#{bindings.FuelSrchrgRateUom.inputValue}",
                                valueChangeEvent.getNewValue());
// Get thhe value associated to new Index which already set in above step
String shortCd= (String) JSFUtils.resolveExpression("# {bindings.FuelSrchrgRateUom.inputValue} ");Here "bindings.ExecuteWithParams_BindComponent" is defined in Page def binding.

public static Object resolveExpression(String expression)
{
FacesContext fc = getFacesContext();
Application application = fc.getApplication();
ELContext elCtx = fc.getELContext();
ExpressionFactory elFact = application.getExpressionFactory();
ValueExpression valExp = elFact.createValueExpression(elCtx, expression, Object.class);
return valExp.getValue(elCtx);
}


Alternative way is