Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label creating. Show all posts
Showing posts with label creating. Show all posts

Saturday 30 April 2016

Create ADF Choice List and apply selectItems to it programmatically

I hope we all know how to create selectOneChoice using Model layer and previously I have posted about populating selectOneChoice programmatically from bean using ArrayList

Programmatically populate values in a af:selectOneChoice component in ADF

But this post is slight different - It is about creating selectOneChoice component and applying selectItems to it programmatically
There is nothing complicated in this , Just a piece of code is required
Here I have used an ArrayList to set SelectItems and created component binding for af:form to add selectOneChoice as it's child 

Thursday 28 August 2014

Create taskFlow and region binding at run-time , show n numbers of regions using multiTaskFlow- Oracle ADF

This is very specific development requirement to create taskFlow and region binding at run-time to show n numbers of region in page
In this case initially you don't know how much regions required in page as it depends on user activity .

you can see in http://irctc.co.in/ (Indian Railways) site
when user search for a train and check berth availability then a tab is generated at run-time with berth and fare details and it continues for each action , every time a new tab with new information is generated (n- number of tab and taskFlow)

A very good article is published in Oracle Magazine (July – August 2014) by Frank Nimphius on this requirement , article contains very good description of each and every step and a sample application with whole functionality
I found it very interesting and good so giving a quick overview of TaskFlow on Fly

this functionality is implemented using multiTaskFlow element that uses taskFlow binding from managed bean , taskFlow bindings in managed bean created using TaskFlowBindingAttributes
this class is used to set all properties of taskFlow binding at runtime



See Oracle docs (TaskFlowBindingAttributes)-
Set of attributes that define a TaskFlowBinding object. The taskFlowList attribute of the multiTaskFlow element of the page definition uses a list of object of this type to describe each taskflowBinding that the multiTaskflow binding contains. The order of this list defines the order of the region objects in the multiTaskflow binding. 

So in this post i am using Departments and Employees table of HR Schema(Oracle) to create business components for Model part


Create viewCriteria in both viewObjects (Departments and Employees) to filter data using DepartmentId




Applied viewCriteria to viewObject at AM level (Edit Vo instance and shuttle viewCriteria to selected side)
After this created methods in AMImpl class to set value in both viewCriteria's bind variables


    /**Method to filter Department ViewObject
     * @param deptId
     */
    public void filterDepartmentData(Integer deptId) {
        this.getDepartments1().setNamedWhereClauseParam("BindDeptId", deptId);
        this.getDepartments1().executeQuery();

    }

    /**Method to filter Employees Data
     * @param deptId
     */
    public void filterEmployeesData(Integer deptId) {
        this.getEmployees1().setNamedWhereClauseParam("BindDeptId", deptId);
        this.getEmployees1().executeQuery();

    }

Expose both methods to use in clientInterface

Now viewController part-

Created two bounded taskFlow with one input parameter for DepartmentId (this id will be used to filter Departments and Employess viewObject)
One for Departments and Second for Employees-

First taskFlow has a .jsff (facelets) page that has Departments viewObject as a form , just to show date with navigation buttons
filterDepartmentData method of AMImpl is used as Default Activity of this taskFlow
to filter data before entering in page
 
 
 

Second taskFlow has a .jsff (facelets) page that has Employees viewObject as a table
filterEmployeesData method of AMImpl is used as Default Activity of this taskFlow
to filter data before entering in page



Now basic configuration is complete, model is ready and bounded taskFlows are ready
then create a jsf page and manged bean (pageFlowScope) in adfc-config.xml, this page will make use of these two bounded taskFlows  and managed bean is responsible to generate taskFlow binding at runtime

Next Step is to prepare manged bean to hold taskFlowBinding-
Create a List of type TaskFlowBindingAttributes and it's accessors


import oracle.adf.controller.binding.TaskFlowBindingAttributes;    
private List<TaskFlowBindingAttributes> taskFlowBinding = new ArrayList<TaskFlowBindingAttributes>(5);

    public void setTaskFlowBinding(List<TaskFlowBindingAttributes> taskFlowBinding) {
        this.taskFlowBinding = taskFlowBinding;
    }

    public List<TaskFlowBindingAttributes> getTaskFlowBinding() {
        return taskFlowBinding;
    }

Create multiTaskFlow binding in executables of pgae-

  • Open jsf page, click on bindings tab of page editor
  • click on green plus icon of executables section
  • Select ADF TaskFlow Bindings in category and select multiTaskFlow


  • click on ok and provide an unique value for id attribute and reference of List created in managed bean as value for taskFlowList attribute


  • Configuration of  multiTaskFlow for this page is complete and now time to design page to render multiple regions. For this purpose add af:ForEach and a region inside it, forEach is responsible to add regions at run-time. here a little change i am using panelTabbed  to create tab at runtime and inside tab there will be region 
  • See this xml code- here nothing simple panelTabbed and forEach iterates over to list to identify number of items and varStatus of forEach is used to create id of showDetailItem at runtime as id must be unique. regionModel is referenced from var attributes of forEach as part of taskFlowBinding 

  •  <af:panelTabbed position="above" id="pt1" partialTriggers="b1">
                <af:forEach items="#{bindings.mtf1.taskFlowBindingList}" var="multiTF" varStatus="vs">
                   <af:showDetailItem id="Tab#{vs.index+1}" text="#{multiTF.name}" partialTriggers="b1">
                      <af:region value="#{multiTF.regionModel}" id="r1#{vs.index}" partialTriggers="::b1"/>
                   </af:showDetailItem>
                </af:forEach>
             </af:panelTabbed>
    

  • Now page is ready to show unknown (n) number of regions, here i am using two list and a button on page First List is of all departments and second one is static list to select information type (if user want to see Only Departments or Departments Wise Employees) and button to execute and add taskFlow from managed bean as per selected Department and 
  • Again a map is created in managed bean to store input parameters for taskFlow and it will used while setting and creating taskFlowBinding

  •     HashMap<String, Object> tfParam = new HashMap<String, Object>();
        public void setTfParam(HashMap<String, Object> tfParam) {
            this.tfParam = tfParam;
        }
    
        public HashMap<String, Object> getTfParam() {
            return tfParam;
        }
    

  • finally we will create taskFlow binding and set properties on button click (actionEvent of button), See this code-

  •     /**Method to create and set properties in TaskFlowBinding
         * @param actionEvent
         */
        public void displayDepartmentAction(ActionEvent actionEvent) {
            //Clear List to show newly created regions only
            taskFlowBinding.clear();
            System.out.println("List Cleared -Size>" + taskFlowBinding.size());
            //Check that user selects value in both List (Uses component binding to check)
            if (deptIdBindVal.getValue() != null && showTypeBind.getValue() != null) {
                //Put value in TaskFLow Parameter map, deptIdBindVal is binding of list of departments on page
                tfParam.put("DeptIdParam", deptIdBindVal.getValue());
    
                //Only Shows Departments taskFlow, if user selectes "Only Departments"
                if ("Only Departments".equalsIgnoreCase(showTypeBind.getValue().toString())) {
                    //Setting taskFlow properties
                    TaskFlowBindingAttributes tfAttr = new TaskFlowBindingAttributes();
                    //Creating Unique Id
                    tfAttr.setId("Department_" + deptIdBindVal.getValue());
                    //See bounded taskFlow name in WEB-INF and use here
                    tfAttr.setTaskFlowId(new TaskFlowId("/WEB-INF/DepartmentsBTF.xml", "DepartmentsBTF"));
                    //This EL refers parameter map created in this managedBean
                    tfAttr.setParametersMap("#{pageFlowScope.MultiTaskFlowBean.tfParam}");
                    //Finally add taskFlow to List
                    taskFlowBinding.add(tfAttr);
                } else { // Show both Departments and Employees
                    //Creating Departments TaskFlow binding
                    TaskFlowBindingAttributes tfAttr = new TaskFlowBindingAttributes();
                    tfAttr.setId("Department_" + deptIdBindVal.getValue());
                    tfAttr.setTaskFlowId(new TaskFlowId("/WEB-INF/DepartmentsBTF.xml", "DepartmentsBTF"));
                    tfAttr.setParametersMap("#{pageFlowScope.MultiTaskFlowBean.tfParam}");
                    taskFlowBinding.add(tfAttr);
                    //Creating Employee TaskFlow biniding
                    tfAttr = new TaskFlowBindingAttributes();
                    tfAttr.setId("Employees_" + deptIdBindVal.getValue());
                    tfAttr.setTaskFlowId(new TaskFlowId("/WEB-INF/EmployeesBTF.xml", "EmployeesBTF"));
                    tfAttr.setParametersMap("#{pageFlowScope.MultiTaskFlowBean.tfParam}");
                    taskFlowBinding.add(tfAttr);
                }
            }
        }
    

  • So Application with multiTaskFlow is ready , in this post i have used these two bounded taskFlow to show in two tabs at run-time, in same way you can call multiple TFs or a single taskFlow multiple time. Now runt application and see how it works

Initial page with two lists


Select Department and show type -click on button


Select Department and show type -click on button


  • Refer this post Region Extreme: Multi-Task-Flow Binding to learn more about multiTaskFlow binding. In this Frank also told about how to use dynamic viewObject instance to show different data at run-time, because if we use same instance of viewObject in multiple taskFlow at same time then it will not maintain state for each region to it is necessary to use dynamic instance and it's binding in pageDef
  • Read more about regions and taskFlows- Using Task Flows as Regions
Thanks - Happy Learning :) Sample ADF Application

Friday 1 August 2014

Exporting viewObject data in text file using af:fileDownloadActionListener in Oracle ADF (12.1.3)

Hello All
This post is about using af:fileDownloadActionListener to generate file on run-time, suppose i have a viewObject and i want to export it's data in CSV or plain text so for this requirement we can generate file at run-time and send it to client UI to download

What is af:fileDownloadActionListener-
as per oracle docs-
The fileDownloadActionListener tag is a declarative way to allow an action source (<commandButton>, <commandLink>, etc.) to programatically send the contents of a file to the user, optionally with a specific content type and filename. Since file downloads must be processed with an ordinary request - not XMLHttp AJAX requests - this tag forces partialSubmit to be false on the parent component, if it supports that attribute.
The fileDownloadActionListener uses the native (browser built-in) filedownload popup, so this popup cannot be configured.

In this post i am using Departments table of HR schema



  • Prepare model part using Departments table and drop it on page as a table and add a button to UI for downloading


  • drop af:fileDownloadActionListener as child of button and set it's property as contentType, method , fileName 


  • Now see code written in download Listener-

  •     /**Method to get BindingsContainer for current page
         * @return
         */
        public BindingContainer getBindingsCont() {
            return BindingContext.getCurrent().getCurrentBindingsEntry();
        }
    
        /**Method to download ViewObject's data in plain text file
         * @param facesContext
         * @param outputStream
         * @throws UnsupportedEncodingException
         * @throws IOException
         */
        public void fileDownloadListener(FacesContext facesContext,
                                         OutputStream outputStream) throws UnsupportedEncodingException, IOException {
            OutputStreamWriter w = new OutputStreamWriter(outputStream, "UTF-8");
            //Get itertaor from bindings
            DCIteratorBinding deptIter = (DCIteratorBinding) getBindingsCont().get("Departments1Iterator");
            //Get ViewObject from Iterator
            ViewObjectImpl vo = (ViewObjectImpl) deptIter.getViewObject();
            ViewAttributeDefImpl[] attrDefs = vo.getViewAttributeDefImpls();
            int count = 0;
            RowSetIterator rsi = vo.createRowSetIterator(null);
            while (rsi.hasNext()) {
                Row nextRow = rsi.next();
                if (nextRow != null) {
                    // Code to iterate over ViewObject's column to get all columns value at runtime
                    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();
                            w.write(columnName + " - " + nextRow.getAttribute(columnName) + "  ");
                        }
                    }
                    // Code to create new line text line for new Row
                    w.write(System.getProperty("line.separator"));
                }
            }
            //Flush the writer after wrting file
            w.flush();
        }
    }
    

  • Run this application and click on download button, browser download box appears , open downloaded file and see how your data appears in text file, to export data in a pdf file you have to generate PDF file using some API then you can download it in same way


Cheers:) Happy Learning

Saturday 5 July 2014

Populate af:treeTable programatically using POJO in Oracle ADF (11g & 12c)

Hello All
This post is about creating & populating af:treeTable programmatically in ADF 11g and 12c
treeTable is basically a hierarchical representation of data, using ADF model layer we can create treeTable very easily by defining master-detail relation between viewObjects
see my previous posts on treeTable-
Tree Table Component in Oracle ADF(Hierarchical Representation)
Tree Table Component with declarative presentation in ADF, Access childs without custom selection listener
Expand and Collapse an af:treeTable programmatically in ADF Faces (Oracle ADF)
Refreshing Child Nodes of an af:treeTable / af:tree in Oracle ADF



to populate treeTable programmatically we need to configure data set that fits to tree hierarchy
thanks to Chris Muir's post about programmatic creation of treeTable
http://one-size-doesnt-fit-all.blogspot.in/2007/05/back-to-programming-programmatic-adf.html

there is 4-5 simple steps to do-
  • Create a fusion web application and drop a af:treeTable on page , in treeTable creation wizard select "bind later" 


  • now create managed bean to populate data in treeTable, create a simple List in managed bean of type POJO class (a java class that contains attributes and their accessor  )
  • so in this app i am going to Tv Serial and respective character names in treeTable, for that i have created a class that contains POJO for treeTable

  • import java.util.ArrayList;
    import java.util.List;
    
    
    public class Seasons {
        public Seasons(String name) {
            this.name = name; // To Store Header Values (Storing Seasons Name :))
            characters = new ArrayList<Seasons>(); // To Store Detail Values (Storing Season's Charatcers)
        }
    
        public void setCharacters(List<Seasons> empDet) {
            this.characters = empDet;
        }
    
        public List<Seasons> getCharacters() {
            return characters;
        }
        private String name;
        private List<Seasons> characters;
    
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    // This methods directly add characters value in list
        public void addEmp(Seasons employee) {
            characters.add(employee);
        }
    
    }
    

  • In this class the characters list behaves as child of seasons, so in managed bean define a top-level list (that contains both master and detail) and add values

  • See managed Bean Code-
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.myfaces.trinidad.model.ChildPropertyTreeModel;
    
    public class ProgrammaticTreeTabBean {
        List<Seasons> seasonList = new ArrayList<Seasons>();
    
        ChildPropertyTreeModel charatcerVal;
    
        public ProgrammaticTreeTabBean() {
            super();
            // Creating tree for Seasons and Characters details
            // Adding Master Values (seasons)
            Seasons season1 = new Seasons("Game of Thrones");
           // Adding Detail Values (Child Node-Characters)
            Seasons character = new Seasons("Tywin Lannister");
            season1.addCharaters(character);
            character = new Seasons("Tyrion Lannister");
            season1.addCharaters(character);
            character = new Seasons("Jaime Lannister");
            season1.addCharaters(character);
            character = new Seasons("Cersie Lannister");
            season1.addCharaters(character);
            character = new Seasons("Ned Stark");
            season1.addCharaters(character);
    
            // Adding Master Values (seasons)
            Seasons season2 = new Seasons("Arrow");
            // Adding Detail Values (Child Node-Characters)
            character = new Seasons("Oliver Queen");
            season2.addCharaters(character);
            character = new Seasons("Moira Queen");
            season2.addCharaters(character);
            character = new Seasons("Laurel Lance");
            season2.addCharaters(character);
            character = new Seasons("Sara Lance");
            season2.addCharaters(character);
    
            // Adding Master Values (seasons)
            Seasons season3 = new Seasons("Vikings");
          // Adding Detail Values (Child Node-Characters)
            character = new Seasons("Ragnar Lothrak");
            season3.addCharaters(character);
    
            // Adding all list to topList
            seasonList.add(season1);
            seasonList.add(season2);
            seasonList.add(season3);
            // Filtering Child Data, ChildPropertyTreeModel creates a TreeModel from a List of beans, see
            // https://myfaces.apache.org/trinidad/trinidad-api/apidocs/org/apache/myfaces/trinidad/model/ChildPropertyTreeModel.html
            charatcerVal = new ChildPropertyTreeModel(seasonList, "characters");
        }
    
        public ChildPropertyTreeModel getCharatcerVal() {
            return charatcerVal;
        }
    }
    

  • Now code part is complete, now configure your treeTable to show data, see XML source of af:treeTable

  • <af:treeTable rowBandingInterval="0" id="tt1"
                                  value="#{pageFlowScope.ProgrammaticTreeTabBean.charatcerVal}" var="node"
                                  rowSelection="single" initiallyExpanded="true">
                        <f:facet name="nodeStamp">
                            <af:column headerText="Node Stamp" id="c1" width="250">
                                <af:outputText value="#{node.name}" id="ot1" inlineStyle="font-weight:bold;"/>
                            </af:column>
                        </f:facet>
                    </af:treeTable>
    

  • Now run your application and check , what you have done ;)
Happy Learning :) Sample ADF Application (12.1.3)

Monday 16 June 2014

Creating and Exporting hierarchical data to excel using dvt:pivotTable & dvt:exportPivotTableData in Oracle ADF

Hello All,
This post is about exporting tree structured(hierarchical ) data to an excel file.
suppose we have export department wise detail of employees , we can achieve this in ADF using pivot table (<dvt:pivotTable>)

What is pivot tabel (oracle docs)- 
 
UIComponent class: oracle.adf.view.faces.bi.component.pivotTable.UIPivotTable
Component type: oracle.dss.adf.pivotTable.PivotTable
The Pivot Table supports the display of multiple nested attributes on a row and column header. In addition, the Pivot Table supports the ability to dynamically change the layout of the attributes displayed in the row or column headers via drag and drop pivoting.
now see the implementation part -



  • Create a Fusion Web Application using HRSchema , for this sample app i have created a view (Department Wise Employees) to export data

  • CREATE OR REPLACE FORCE EDITIONABLE VIEW "APP_USR"."DEPT_EMP" ("DEPARTMENT_NAME", "EMPLOYEE_NAME", "SALARY") AS 
      SELECT A.DEPARTMENT_NAME, B.FIRST_NAME,B.SALARY FROM DEPARTMENTS A, EMPLOYEES B WHERE A.DEPARTMENT_ID=B.DEPARTMENT_ID (+);
    

  • Prepare model using this view


  • Create a page and drop this view as pivot table (ADF Faces component) from data control


  • Now configure pivot table (set row & column attributes, insert appropriate drilling) - see the snaps




  • Now run your page and see working pivot table - here pivot table is created successfully 


  • Drop a button  and a <dvt:exportPivotTableData> under button to export pivot table

  • <af:commandButton text="Export" id="b1">
                        <dvt:exportPivotTableData type="excelHTML" exportedId="pt1" filename="Dep_Empl.xls"
                                                  title="PivotTable export"/>
                    </af:commandButton>
    

  • Run your page and click on export button and see your tree structured data in exported excel file


Cheers :) Happy Learning Sample ADF Application

Sunday 19 January 2014

Creating new object in list (af:inputListOfValues) using 'createPopupId' feature- ADF 11g & 12c

Hello All ,
This post is about a good feature provided with inputListOfValues in ADF .
inputListOfValues is used where large and complex data is populated in list, this component supports search in list values
Suppose on opening list values you want to add one more value in list generally to do that you will  close the list and add a value in source table then again open list but this feature provide instant creation of list values

this functionality can be achieved in Combo Box with List of Values using customActions facet, i have posted about it
Create new look up data using List of Values (LOVs) in Oracle ADF

so this time it is about  inputListOfValues, see the steps to do

  • Created a fusion web application and business components  using Departments and Employees table of HR Schema

  • now i have created list of values on DepartmentId of Employees ViewObject referenced from Department ViewObject, display type is Input Text with List of Values



  •  drop Employees VO on page and run, it looks like this

  • Now i have dropped a popup on page and to create new value in list, i have dropped form of Departments ViewObject and a link to create it on dialog inside popup
     

  • select list of values component (Employee VO) in structure window and go to property inspector and set popUp id in a property called 'createPopupId'
  • After setting 'createPopupId' ,on running a commandToolbarButton appears in the LOV popup dialog box with a icon, this button's action triggers custom popUp (i have added before)
        on clicking on this icon-

  •  on create link i have just called createInsert for Departments ViewObject and on dialogListener , Execute

  • import oracle.adf.model.BindingContext;
    import oracle.binding.BindingContainer;
    import oracle.binding.OperationBinding;
    
    
    
        /**Method to get Bindings of current page
         * @return
         */
        public BindingContainer getBindings(){
            return BindingContext.getCurrent().getCurrentBindingsEntry();
        }
    
        /**Method to execute OperationBinding
         * @param operation
         * @return
         */
        public OperationBinding executeOperation(String operation){
            return getBindings().getOperationBinding(operation);
        }
    
        /**Method to create new Department
         * @param actionEvent
         */
        public void createDeptAction(ActionEvent actionEvent) {
           executeOperation("CreateInsert").execute();
        }
    

  • now created a new department using 'create' link and you can see value is appeared in list values

 Cheers :-)

Friday 9 August 2013

Creating pdf file using Apache PDFBox API in ADF Faces and opening it in new window -Oracle ADF

Apache PDFBox library is an open source java tool for working with PDF documents, go to http://pdfbox.apache.org/ for API docs and download jar (pdfbox-app-1.8.2) from there.

  •  Now create a fusion web application and add jar to view controller project's library and class-path
  •  To convert text to pdf format, i have used an input text and bind it to bean (to get value)
  •  Now see the button code that converts text to pdf file format using Apache PDFBox

  •         PDDocument document = new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);
    
            // Create a new font object selecting one of the PDF base fonts
            PDFont font = getFontDef();
    
            // Start a new content stream which will "hold" the to be created content
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
    
            // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
    
            contentStream.beginText();
            contentStream.setFont(font, 10);
            contentStream.moveTextPositionByAmount(50, 700);
            contentStream.drawString(textToConvert.getValue().toString());
            contentStream.endText();
    
            // Make sure that the content stream is closed:
            contentStream.close();
    
            // Save the results and ensure that the document is properly closed:
            try {
                document.save("D:/Test_pdf.pdf");
            } catch (COSVisitorException e) {
            }
            document.close();
    

  • now your pdf is generated in fixed path, and if user want to open it immediately , try to do this



  •         if ((new File("D:\\Hello World.pdf")).exists()) {
    
                Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler D:\\Hello World.pdf");
                p.waitFor();
    
            } else {
    
                System.out.println("File is not exists");
    
            }
    

  • this code invokes File Protocol using Runtime class
  • Run this application and see-
 Click on generate button-


For more details and functionality visit Apache PDFBox site
Sample ADF Application-Download