Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label Iterator. Show all posts
Showing posts with label Iterator. Show all posts

Wednesday 3 August 2016

ADF Basics: Iterate over master detail viewObject using view link accessor


Hello All

This post is about iterating over master and it's child view object using view link accessor, this is very basic thing of framework still some find (those who are starting with ADF) it difficult so I thought to write it here

Here I am using Departments and Employees table of HR Schema to create Master-Detail relation and due to view link relation, Department viewObject has view link accessor of Employees viewObject

Monday 3 August 2015

Iterate over HashMap to get Key and Value in Java , Add records to HashMap


Iterating over HashMap is not same as other collections , It's a bit tricky than normal iteration ;)
See in this code -
How to add values to HashMap ?
and How to iterate over HashMap to get Key and Values?






package client;

import java.util.HashMap;
import java.util.Iterator;

public class IterateHashMap {
    public IterateHashMap() {
        super();
    }

    public static void main(String[] args) {
        HashMap<Integer, String> mapVal = new HashMap<Integer, String>();

        //Add values to Map
        mapVal.put(1, "value 1");
        mapVal.put(2, "value 2");
        mapVal.put(3, "value 3");
        mapVal.put(4, "value 4");

        //Create Iterator from keySet
        Iterator iter = mapVal.keySet().iterator();
        //Iterate over hashmap to get key
        while (iter.hasNext()) {
            int key = (Integer) iter.next();
            //Use this key to find value
            String value = mapVal.get(key).toString();
            System.out.println("**KEY**  " + key + " AND VALUE**  " + value);
        }

    }
}


Cheers :) Happy Learning

Wednesday 6 May 2015

Get Value from programmatically created components , Iterate over parent component to get child values in ADF Faces

Sometimes we need to create and add ADF Faces components at runtime , we can do it programmatically
I have posted about this before
Creating dynamic layout (form and UI Component) using ADF Faces

Now this post talks about getting value from programmatically created component, means when user enters value in those component then how to access that value in managed bean

Here i am using Jdev 12.1.3 , Let's see the implementation part

Created a page and added two buttons , one to create component at run time and second one to get values from those components
See page XML source code -

<af:document title="ProgComponent.jspx" id="d1">
            <af:form id="f1">
                <af:spacer width="10" height="10" id="s3"/>
                <af:button text="Create Components " id="b1"
                           actionListener="#{viewScope.GetValueProgCompBean.createComponentsAction}"/>
                <af:spacer width="10" height="10" id="s1"/>
                <af:button text="Get Value" id="b2"
                           actionListener="#{viewScope.GetValueProgCompBean.getValueOfCompAction}"/>
                <af:panelGroupLayout id="pgl1" layout="vertical"
                                     binding="#{viewScope.GetValueProgCompBean.parentGroupBind}">
                    <af:spacer width="10" height="10" id="s2"/>
                </af:panelGroupLayout>
            </af:form>
        </af:document>

To create components at run time i have used same approach described in above blog post
Check the code written on Create Components button



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

import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;


    //Binding of panel group layout , it will be parent of prog. created components
    private RichPanelGroupLayout parentGroupBind;

    public void setParentGroupBind(RichPanelGroupLayout parentGroupBind) {
        this.parentGroupBind = parentGroupBind;
    }

    public RichPanelGroupLayout getParentGroupBind() {
        return parentGroupBind;
    }

    /**Method to add child components to parent
     * @param parentUIComponent
     * @param childUIComponent
     */
    public void addComponent(UIComponent parentUIComponent, UIComponent childUIComponent) {
        parentUIComponent.getChildren().add(childUIComponent);
        AdfFacesContext.getCurrentInstance().addPartialTarget(parentUIComponent);
    }

    /**Method to create Input text at run time
     * @param actionEvent
     */
    public void createComponentsAction(ActionEvent actionEvent) {
        //Create an Object of desired UI Component
        RichInputText ui = new RichInputText();
        //Set properties
        ui.setId("rit1");
        ui.setLabel("Input text 1");
        ui.setContentStyle("font-weight:bold;color:red");
        //Now add this component to any parent component
        addComponent(getParentGroupBind(), ui);

        RichInputText ui1 = new RichInputText();
        ui1.setId("rit2");
        ui1.setLabel("Input text 2");
        ui1.setContentStyle("font-weight:bold;color:red");
        addComponent(getParentGroupBind(), ui1);
    }

Now run application and click on button , you will see two inputText are created


Now to get value of these components follow the steps
1. Get Parent layout
2. Iterate over parent to get all child components
3. Get Value of every child

See the code written on get value button in managed bean

    /**Method to Iterate over parent and get value of all child components
     * @param actionEvent
     */
    public void getValueOfCompAction(ActionEvent actionEvent) {
        RichPanelGroupLayout PF = getParentGroupBind(); // Get Parent Layout
        List<UIComponent> listcomp = PF.getChildren(); // Get all child
        Iterator iter = listcomp.iterator(); // Create an Iteraotr to iterate over childs
        while (iter.hasNext()) {
            UIComponent comp = (UIComponent) iter.next(); // Get next Child Component
            System.out.println("Component is-" + comp + " and value is-" +
                               comp.getAttributes().get("value")); //Get Component detial and it's value
        }
    }

Again check , enter value in both inputText and click on button to get value


Output on console-

Sample ADF Application- Download
Cheers :) Happy Learning

Monday 24 March 2014

Iterating ViewObject vertically (get all attributes of ViewObject) programmatically

Hello All,
This post talks about a requirement of getting all attributes (column names) of a viewObject programmatically

  • Create a fusion web application and business component using department table

  • you can see all attributes in  Departments entity object

  • Now to get ViewObject's attributes name , there is a method written in AMImpl class , see it, i have added a facesMessage to show all names on a Message Board



  •     /**Method to get all attributes of a viewObject
         * */
        public void iterateVoVertically() {
            ViewObjectImpl vo = this.getDepartments1();
            ViewAttributeDefImpl[] attrDefs = vo.getViewAttributeDefImpls();
            int count = 0;
            StringBuilder infoMsg =
                new StringBuilder("<html><body><b><p style='color:red'> Attribute of Department ViewObject are-</p></b>");
            infoMsg.append("<ul>");
    
    
            for (ViewAttributeDefImpl attrDef : attrDefs) {
                byte attrKind =
                    attrDefs[count].getAttributeKind(); //checks attribute kind for each element in an array of AttributeDefs
                if (attrKind != AttributeDef.ATTR_ASSOCIATED_ROW && attrKind != AttributeDef.ATTR_ASSOCIATED_ROWITERATOR) {
                    String columnName = attrDef.getName();
                    infoMsg.append("<li> <b>" + attrDef.getName() + "</b></li>");
                    System.out.println("Column Name-" + columnName);
                }
            }
            infoMsg.append("</ul><br>");
            infoMsg.append("</body></html>");
            FacesMessage msg = new FacesMessage(infoMsg.toString());
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    

  • I have called this method through page binding and AM Client on a button of page

  • now on click of button all attributes of Departments ViewObject are shown in FacesMessage, you can use it in your code
 Cheers :-)

Saturday 27 July 2013

Implementing master/detail tree relation using af:Iterator and af:forEach for better UI designs - Oracle ADF

In ADF Faces tree and tree table is used for hierarchical representation of master/detail form of data,
in this tutorial i will show you that how can we design better UI's using master detail data.
af:iterator and af:ForEach both are used to iterate data as af:table for custom UI component-

here i am taking example of default HR Schema of Oracle database , Departments and Employees table to show master-detail relation

Using af:iterator-

  • Create a Fusion Web Application and prepare model for master detail relationship between departments and employees table, and in your page drop af:showDetailHeader from component palette
  • Go to page binding, add tree binding for Departments (Master) and Employees (Detail)


  • Surround showDetailHeader with an af:iterator,  and set value and var for iterator (master)

  •  Now change text of showDetailHeader to show department name on it, taking reference from iterator's var


  • master part is done, for detail part  drop two output text (for employee's first name and last name) inside showDetailHeader surrounding with an iterator (for detail part)




  • set the value and var for detail iterator taking reference from master iterator 

  • Now to show detail values in output text , set the value in both output text, taking reference from detail iterator


  • See the source of page for more clarification-

  • <af:iterator id="i3" value="#{bindings.Departments1.collectionModel}" var="departments">
                                    <af:showDetailHeader text="#{departments.DepartmentName}" disclosed="true" id="sdh1"
                                                         inlineStyle="width:350px;">
                                        <f:facet name="context"/>
                                        <f:facet name="menuBar"/>
                                        <f:facet name="toolbar"/>
                                        <f:facet name="legend"/>
                                        <f:facet name="info"/>
                                        <af:panelGroupLayout id="pgl2" layout="vertical">
                                            <af:iterator id="i2" var="emp" value="#{departments.Employees}">
                                                <af:separator id="s3"/>
                                                <af:panelFormLayout id="pfl1" rows="1">
                                                    <af:outputText value="#{emp.FirstName}" id="ot2"
                                                                   inlineStyle="font-weight:bold;color:darkblue;"/>
                                                    <af:outputText value="#{emp.LastName}" id="ot3"
                                                                   inlineStyle="font-weight:bold;color:red;"/>
                                                </af:panelFormLayout>
                                                <af:spacer width="10" height="10" id="s1"/>
                                            </af:iterator>
                                        </af:panelGroupLayout>
                                    </af:showDetailHeader>
                                </af:iterator>
    

  • Now Run your page to see UI of this master-detail relationship-


Using af:ForEach-

  •  Drop a panel accordion on page, by default it has one af:showDetailItem , surround it with af:ForEach and set items and var for ForEach

  • change text of showDetailItem to show department name on it, taking reference from ForEach's var 

  • Now drop Employees detail table from data control inside showDetailItem and set its value , taking reference from ForEach 


  • For more clarification see source of page-

  • <af:panelAccordion id="pa1" styleClass="AFStretchWidth" visible="true">
                                    <af:forEach items="#{bindings.Departments1.children}" var="dept">
                                        <af:showDetailItem text="#{dept.DepartmentName}" id="sdi1" inflexibleHeight="200">
                                            <af:table value="#{dept.children}" var="row"
                                                      rows="#{bindings.Employees3.rangeSize}"
                                                      emptyText="#{bindings.Employees3.viewable ? 'No data to display.' : 'Access Denied.'}"
                                                      fetchSize="#{bindings.Employees3.rangeSize}" rowBandingInterval="0"
                                                      filterModel="#{bindings.Employees3Query.queryDescriptor}"
                                                      queryListener="#{bindings.Employees3Query.processQuery}"
                                                      filterVisible="true" varStatus="vs"
                                                      selectedRowKeys="#{bindings.Employees3.collectionModel.selectedRow}"
                                                      selectionListener="#{bindings.Employees3.collectionModel.makeCurrent}"
                                                      rowSelection="single" id="t1" styleClass="AFStretchWidth">
                                                <af:column sortProperty="#{bindings.Employees3.hints.EmployeeId.name}"
                                                           filterable="true" sortable="false"
                                                           headerText="#{bindings.Employees3.hints.EmployeeId.label}"
                                                           id="c1">
                                                    <af:outputText value="#{row.EmployeeId}"
                                                                   shortDesc="#{bindings.Employees3.hints.EmployeeId.tooltip}"
                                                                   id="ot4">
                                                        <af:convertNumber groupingUsed="false"
                                                                          pattern="#{bindings.Employees3.hints.EmployeeId.format}"/>
                                                    </af:outputText>
                                                </af:column>
                                                <af:column sortProperty="#{bindings.Employees3.hints.FirstName.name}"
                                                           filterable="true" sortable="false"
                                                           headerText="#{bindings.Employees3.hints.FirstName.label}"
                                                           id="c2">
                                                    <af:outputText value="#{row.FirstName}"
                                                                   shortDesc="#{bindings.Employees3.hints.FirstName.tooltip}"
                                                                   id="ot5"/>
                                                </af:column>
                                                <af:column sortProperty="#{bindings.Employees3.hints.LastName.name}"
                                                           filterable="true" sortable="false"
                                                           headerText="#{bindings.Employees3.hints.LastName.label}" id="c3">
                                                    <af:outputText value="#{row.LastName}"
                                                                   shortDesc="#{bindings.Employees3.hints.LastName.tooltip}"
                                                                   id="ot6"/>
                                                </af:column>
                                                <af:column sortProperty="#{bindings.Employees3.hints.Email.name}"
                                                           filterable="true" sortable="false"
                                                           headerText="#{bindings.Employees3.hints.Email.label}" id="c4">
                                                    <af:outputText value="#{row.Email}"
                                                                   shortDesc="#{bindings.Employees3.hints.Email.tooltip}"
                                                                   id="ot7"/>
                                                </af:column>
                                            </af:table>
                                        </af:showDetailItem>
                                    </af:forEach>
                                </af:panelAccordion>
    


  • Now run your page to see its UI-


Download Sample workspace here- Download
Happy Jdeveloping..

Monday 26 November 2012

Most Used Codes in ADF (Iterate over ViewObject, get Value from pageFlow Scope variable)

Iterate Over View Object-


Some times we need to iterate in table to check for some validation as we have  to check for duplicate record, we want to delete all data of table with one click.
then we have to get all rows of table- this is a very common use case in ADF, so you can use following snippet of code to do this






1. Using AllRowInRange method to get rows available in range

  ViewObject vo=am.getViewObject();


   // Get All Rows in range of ViewObject in an Array
    Row[] rArray=vo.getAllRowsInRange();
    
    //Loop over array of Rows
    for(Row r:rArray){

       /*your operation code*/

       }


2. Using RowSetIterator-


  ViewObject vo = this.getViewObject();
       
       //Create RowSetIterator
        RowSetIterator rsi = vo.createRowSetIterator(null);
       //Iterate Over this to get all rows
        while (rsi.hasNext()) {
            Row nextRow = rsi.next();
            
        }
        rsi.closeRowSetIterator();


Get Value from taskFlow parameter(Using pageFlow Scope)-

we can get value from TaskFlow parameter using pageflow scope and can use it in Our Bean.
Suppose we have defined a parameter in page to pass Session_Id.
We can get it using pageflow scope




Integer sessionId = Integer.parseInt(resolvEl("#{pageFlowScope.Session_Id}"));

 Code For resolvEl-


    public String resolvEl(String data) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        ValueExpression valueExp = elFactory.createValueExpression(elContext, data, Object.class);
        String Message = valueExp.getValue(elContext).toString();
        return Message;
    }
 

Thursday 25 October 2012

Set on Current row after Rollback Execute or page refresh

Some times we edit a table in form and Save(Commit & Execute) or Cancel(Rollback & Execute)  and table refreshed to its first record means focus is now on first row of table.
And we need the same row again, then we search it and perform another operation, this is really disgusting behavior of table for Developer.

To set on previously selected row after execute we can use this code,
in this scenario we have to get current row key from its IteratorBinding and after Execute we can set it again to show that row as selected.





    /**
     * Generic Method to call operation binding
     **/
     public BindingContainer getBindings() {
      return BindingContext.getCurrent().getCurrentBindingsEntry();
     }


     BindingContainer bindings = getBindings();
     //Get Iterator of table
     DCIteratorBinding parentIter = (DCIteratorBinding)bindings.get("IteratorName");
     //Get current row key
     Key parentKey = parentIter.getCurrentRow().getKey();

     //You can add your operation code here, i have used simple Cancel operation 
     //with Rollback and Execute
     
     
     OperationBinding ob= bindings.getOperationBinding("Rollback");
     ob.execute();
     OperationBinding ob1= bindings.getOperationBinding("Execute");
     ob1.execute();
    
     //Set again row key as current row
     parentIter.setCurrentRowWithKey(parentKey.toStringFormat(true));