Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label 11g. Show all posts
Showing posts with label 11g. Show all posts

Monday 4 August 2014

Uploading and downloading files from absolute server path in Oracle ADF (12.1.3)

Hello all
this post is about a very simple requirement -file handling (uploading and downloading various types of file) in ADF and it is needed very often to store file in absolute server path (actual path) and download from there

see step by step implementation -
  • I have created a simple table in HR schema to store uploaded file name ,path and content type
  • See sql script for this table-

     CREATE TABLE "FILE_UPD_DWN" 
       ( "FILE_NAME" VARCHAR2(50 BYTE), 
     "PATH" VARCHAR2(100 BYTE), 
     "CONTENT_TYPE" VARCHAR2(500 BYTE)
       )
    

  • Then prepare model using this table and drop on page as af:table, and an af:inputFile to select and upload file is used in page


  • Then create a ValueChangeListener on inputFile component to upload file to an actual path on server, and after upload a row is inserted in table to keep record of uploaded files

  • Bean Method to Upload File-


        /**Method to upload file to actual path on Server*/
        private String uploadFile(UploadedFile file) {
    
            UploadedFile myfile = file;
            String path = null;
            if (myfile == null) {
    
            } else {
                // All uploaded files will be stored in below path
                path = "D://FileStore//" + myfile.getFilename();
                InputStream inputStream = null;
                try {
                    FileOutputStream out = new FileOutputStream(path);
                    inputStream = myfile.getInputStream();
                    byte[] buffer = new byte[8192];
                    int bytesRead = 0;
                    while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                    out.flush();
                    out.close();
                } catch (Exception ex) {
                    // handle exception
                    ex.printStackTrace();
                } finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
    
            }
            //Returns the path where file is stored
            return path;
        }
    

    AMImpl method to insert record in table for Uploaded file




        /**Method to set file path and name
         * @param name
         * @param path
         */
        public void setFileData(String name, String path,String contTyp) {
            ViewObject fileVo = this.getFileUpdDwn1();
            Row newRow = fileVo.createRow();
            newRow.setAttribute("FileName", name);
            newRow.setAttribute("Path", path);
            newRow.setAttribute("ContentType", contTyp);
            fileVo.insertRow(newRow);
            this.getDBTransaction().commit();
            fileVo.executeQuery();
        }
    

    ValueChangeListener to execute all methods -




        /*****Generic Method to Get BindingContainer**/
        public BindingContainer getBindingsCont() {
            return BindingContext.getCurrent().getCurrentBindingsEntry();
        }
    
        /**
         * Generic Method to execute operation
         * */
        public OperationBinding executeOperation(String operation) {
            OperationBinding createParam = getBindingsCont().getOperationBinding(operation);
            return createParam;
    
        }
    
        /**Method to Upload File ,called on ValueChangeEvent of inputFile
         * @param vce
         */
        public void uploadFileVCE(ValueChangeEvent vce) {
            if (vce.getNewValue() != null) {
                //Get File Object from VC Event
                UploadedFile fileVal = (UploadedFile) vce.getNewValue();
                //Upload File to path- Return actual server path
                String path = uploadFile(fileVal);
                System.out.println(fileVal.getContentType());
                //Method to insert data in table to keep track of uploaded files
                OperationBinding ob = executeOperation("setFileData");
                ob.getParamsMap().put("name", fileVal.getFilename());
                ob.getParamsMap().put("path", path);
                ob.getParamsMap().put("contTyp", fileVal.getContentType());
                ob.execute();
                // Reset inputFile component after upload
                ResetUtils.reset(vce.getComponent());
            }
        }
    

  • Now run application and select files and see- 


  • See uploaded files in folder


  • I have seen that developers often use servlet to download and open file in browser window using HTTP response , but no need to to do this as ADF provides built in component for this <af:fileDownloadActionListener> that automatically generate http response
  • Now Upload part is complete , for download functionality added a link in table column and dropped an af:fileDownloadActionListener inside link and set properties for DownloadActionListener



  • See the code in Download Listener

  •     /**Method to download file from actual path
         * @param facesContext
         * @param outputStream
         */
        public void downloadFileListener(FacesContext facesContext, OutputStream outputStream) throws IOException {
            //Read file from particular path, path bind is binding of table field that contains path
            File filed = new File(pathBind.getValue().toString());
            FileInputStream fis;
            byte[] b;
            try {
                fis = new FileInputStream(filed);
    
                int n;
                while ((n = fis.available()) > 0) {
                    b = new byte[n];
                    int result = fis.read(b);
                    outputStream.write(b, 0, b.length);
                    if (result == -1)
                        break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            outputStream.flush();
        }
    

  • Now run application and see how Upload and download works 

Happy Learning :) Sample ADF Application

Next Post is this series - (Must Read)
Uploading mulitiple files to server path in Oracle ADF using af:inputFile
Uploading and downloading files from database (BLOB) in Oracle ADF

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 23 June 2014

Navigating to (open) specific tab in af:panelTabbed programmatically -Oracle ADF

Hello All,
This post is about a development requirement - how to move (navigate or open) to a specific tab in panel tabbed  in Oracle ADF?
Suppose i have to open second tab of af:panelTabbed on a button click, so see how to do this using ADF Faces
  • Create a Fusion Web application and a page to drop panel tabbed and a button


  • now bind panel tabbed and it's showDetailItem to managed bean, in order to use disclosed property and to get client id
  • See the code to open (disclose) a specific tab of af:panelTabbed
        //Binding of Panel Tabbed
        private RichPanelTabbed panelTabBind;
    
        public void setPanelTabBind(RichPanelTabbed panelTabBind) {
            this.panelTabBind = panelTabBind;
        }
    
        public RichPanelTabbed getPanelTabBind() {
            return panelTabBind;
        }
    
        /**
         * @Method to disclose (open) specific tab
         * Pass the binding of af:showDetailItem that you want to open
         */
        public void setDisclosedFirstTab(RichShowDetailItem tabBind) {
            RichPanelTabbed richPanelTabbed = getPanelTabBind();
            for (UIComponent child : richPanelTabbed.getChildren()) {
                RichShowDetailItem sdi = (RichShowDetailItem) child;
                if (sdi.getClientId().equals(tabBind.getClientId())) {
                    sdi.setDisclosed(true);
                } else {
                    sdi.setDisclosed(false);
                }
            }
            AdfFacesContext.getCurrentInstance().addPartialTarget(panelTabBind);
        }
    

  • Now see the code written on button action- here i have checked that which tab is currently disclosed? and based on that i have passed next tab binding to this method



  •     /**Method to be called on Navigate Button
         * @param actionEvent
         */
        public void naviGateButtonAction(ActionEvent actionEvent) {
            if (firstTabBind.isDisclosed()) {
                setDisclosedFirstTab(secTabBind);
            } else if (secTabBind.isDisclosed()) {
                setDisclosedFirstTab(thirdTabBind);
            } else {
                setDisclosedFirstTab(firstTabBind);
            }
        }
    

  • now run your page and see navigation in af:panelTabbed

 Cheers Happy Learning :) Sample ADF Application

Sunday 8 June 2014

ADF Basics: Using CSS to change appearance of application (Skins and Styles in ADF Faces)

Hello All
This is a basic post about using CSS in ADF applications, how can you change appearance of ADF application using Skins (.css file)
See the steps to create and apply css in your ADF applications
  • Create a Fusion Web Application and create a page
  • Add Some ADF Faces component (input text,button,panel box, panel collection etc)
  • Now to change appearance of default ADF Faces components , create an ADF Skin
  •  Right click on ViewController--->New--->Web Tier--->JSF/Facelets--->ADF Skin 


  • By default ADF Skin name is like skin1,2 etc



  • After creating ADF Faces skin open it and, on left you will see all components as Button, Layouts, Output text and so on. this is ADF Skin Editor


  • Now expand the components that you want to change , change it's color(on active, focus , hover etc) and other properties. See in image below


  • After creating your ADF Skin ,open trinidad-config.xml file in Jdeveloper editor and your will see like this

  • <skin-family>skin1</skin-family>
    
    This means that skin1 is applied on Application

  • now if you another ADF Skin file- skin2 then in trinidad-config.xml, it will be changed to

  • <skin-family>skin2</skin-family>
    

  • ADF automatically choose the most recent skin, so here this is done , now create and configure your ADF Skin and customize appearance of application
  • For more details see Oracle Docs- http://docs.oracle.com/cd/E16764_01/web.1111/b31973/af_skin.htm
Cheers :-) Happy Learning

Wednesday 4 June 2014

ADF Basics : Implementing auto suggest behavior in ADF Faces lov (list of values)


Auto Suggest behavior is best understand by Google Instant, as in google when we type something and it starts showing suggestion instantly.

 This effect can be implemented in ADF using autoSuggestBehaviour
To use the auto-suggest functionality in a declarative way you need to define a model-driven list of values on your model project, which will be the base for the suggestedItems list. Select the Department Name attribute from the Department VO and create a List of Values. here i am using HR schema and predefined table Department to implement this

  • Create a Fusion Web Application
  • Now create EO and VO of Department table.(Business Components)


  • Now create List of values(LOVs)on DepartmentName



  • Create page in ViewController and drag the DepartmentName on page as ADF Lov ChoiceList or Lov Input

  • Now go to Component Palette and select Auto Suggest Behaviour and drop it inside DepartmentName Lov


  • Now select af:autoSuggestBehavior from Page structure and go to PropertyInspector and Open Expression Builder at SuggestedItems and select from bindings #{bindings.DepartmentName.suggestedItems} if you are using different tables and Lov select according to that



  • Now run your page and enjoy autosuggest behavior (ADF Instant) 
Cheers :-) Happy Learning

Read Next Post in Series- Implement contains/endswith behavior in model based autoSuggest Lov (Input list and combo box)

Thursday 15 May 2014

Overriding Reset button action (QueryOperationListener) of af:query, Changing query mode, Handling QueryOperationEvent programmatically-Oracle ADF

Hello All ,
previously i had a requirement of validating af:query fields so i have found two ways to do that
see -Overriding default query listener ,field validation of af:query- Oracle ADF

now i have to set some values in af:query when user clicks on Reset button of query so to do that i have to override default QueryOperationListener in order to handle QueryOperationEvent  



Oracle docs says-

af:query- The query component provides the user the ability to perform a query based on a saved search or personalize saved searches in Oracle ADF. The component displays a search panel with various elements, each of which help the user to accomplish various tasks. 

QueryOperationListener- QueryOperationListener class. A registered queryOperationListener is invoked when the user's action results a queue and broadcast of QueryOpertionEvent on the component. For example, click the delete icon in the QuickCriteria component or click "Save", "Reset" etc buttons in Query component to perform a Query Operation.

 QueryOperationEvent-A user can perform various operations on saved searches while interacting with a query component. These actions include creating, overriding, deleting, duplicating, selecting, resetting and updating a saved search

want to read more-  
http://docs.oracle.com/cd/E17904_01/apirefs.1111/e10684/oracle/adf/view/rich/event/QueryOperationListener.html
http://jdevadf.oracle.com/adf-richclient-demo/docs/apidocs/oracle/adf/view/rich/event/QueryOperationEvent.html  

so i have created a QueryOperationListener in managed bean that communicates with QueryOperationEvent

in this method we can capture various events of af:query as reset,update
so for this use-case i have to capture reset and set desired values in query attribute (viewObject's bind variable) , here i am using Departments table of HR Schema



now see the code (i have to set Human Resource department on reset in search panel) - how to capture raised event when user clicks on Reset button of af:query


    /**Custom QueryOperationListener that hadles variois events raised by af:query
     * @param queryOperationEvent
     */
    public void deptSeacrhQueryOperationList(QueryOperationEvent queryOperationEvent) {
        //Invoke default operation listener
        invokeEL("#{bindings.DepartmentsVOCriteriaQuery.processQueryOperation}", Object.class,
                 QueryOperationEvent.class, queryOperationEvent);

        System.out.println("Query Event is-" + queryOperationEvent.getOperation().name());
        //Check that current operation is RESET
        if (queryOperationEvent.getOperation().name().equalsIgnoreCase("RESET")) {
            DCIteratorBinding iter = (DCIteratorBinding) getBindings().get("Departments1Iterator");

            ViewObjectImpl vo = (ViewObjectImpl) iter.getViewObject();
            // Setting the value of bind variable
            vo.ensureVariableManager().setVariableValue("BindDeptNm", "Human Resource");
        }
    }

to invoke Expression use this method


    /**
     * @param expr
     * @param returnType
     * @param argTypes
     * @param args
     * @return
     */
    public Object invokeMethodExpression(String expr, Class returnType, Class[] argTypes, Object[] args) {
        FacesContext fc = FacesContext.getCurrentInstance();
        ELContext elctx = fc.getELContext();
        ExpressionFactory elFactory = fc.getApplication().getExpressionFactory();
        MethodExpression methodExpr = elFactory.createMethodExpression(elctx, expr, returnType, argTypes);
        return methodExpr.invoke(elctx, args);
    }

    /**
     * @param expr
     * @param returnType
     * @param argType
     * @param argument
     * @return
     */
    public Object invokeEL(String expr, Class returnType, Class argType, Object argument) {
        return invokeMethodExpression(expr, returnType, new Class[] { argType }, new Object[] { argument });
    }

now run this page and check on click of reset button this listener is invoked and sets the value of af:query field
Default page view -on-load


 after click on Reset-


other than this reset we can handle other events of af:query (for saved search there are various events based on corresponding operations) as DELETE, UPDATE, CREATE


on clicking various button of this personalized search box we get respective operation  name in managed bean and can handle as  done for RESET operation

Changing mode of default search panel (af:query) of ADF-
this is nothing but  2 lines that changes the mode of af:query - Basic to Advanced & Advanced to Basic

so dropped a button on page to change af:query search mode and see the code of ActionListener for this


//Binding of af:query in managed bean  
  private RichQuery queryPanelDept;
    
    public void setQueryPanelDept(RichQuery queryPanelDept) {
        this.queryPanelDept = queryPanelDept;
    }
    public RichQuery getQueryPanelDept() {
        return queryPanelDept;
    }


    private String current_mode = "B";

    /**Method Action to change mode of af:query
     * @param actionEvent
     */
    public void changeModeAction(ActionEvent actionEvent) {
        if (current_mode == "B") {
            getQueryPanelDept().getValue().changeMode(QueryDescriptor.QueryMode.ADVANCED);
            current_mode = "A";
        } else if (current_mode == "A") {
            getQueryPanelDept().getValue().changeMode(QueryDescriptor.QueryMode.BASIC);
            current_mode = "B";
        }
    }

now run page and see-



Cheers - Happy learning :-) Download Sample ADF App

Tuesday 6 May 2014

ADF Basics : Selecting and showing time-stamp in ADF Faces using af:inputDate & af:convertDateTime

Hello All
This post is about a very common & basic requirement of developers ,
how to show & select time with date in ADF Faces ?
We use af:inputDate to show and select Date & Timestamp type of attributes, by default it looks like this



ADF provides a default converter (af:convertDateTime) to format date & timestamp field, we can define a pattern to change it's format & to show time selector in calendar box



Suppose pattern is- dd-MMM-yyy HH:mm:ss , now see there is a hour/minute/second selector appears in calendar box



you can change this pattern as per your format , suppose you want to show AM or PM after time just use dd-MMM-yyy HH:mm:ss a



see xml source of af:inputDate-


<af:inputDate label="Label 1" id="id1" contentStyle="width:250px;padding:5px;">
                        <af:convertDateTime pattern="dd-MMM-yyy HH:mm:ss a"/>
                    </af:inputDate>

this is how we can change format of Date & Timestamp - Cheers :-)

Friday 2 May 2014

Pre-populate selected values in viewObject based shuttle component (multiple selection)- Oracle ADF

Hello All,
This post talks about a common development requirement
while using shuttle component sometimes we need to show some values on selected side of af:selectManyShuttle , so to do this normally we use a custom shuttle component that is populated from managed bean code
but when i have all data in a viewObject so why should i iterate viewObject to get all data in managed bean and then set some values in an arrayList to populate selected shuttle values.
it is time consuming and requires lot of coding, so for viewObject based shuttle we can do it in efficient way.

  • In this example I'm using Departments table of HR schema to populate af:selectManyShuttle, i think you all know how to create a shuttle in ADF
  • So next is to populate selected shuttle values on some event, created a fusion web application using Departments table

  • It's time to drop Departments ViewObject on page as shuttle component

  • <af:selectManyShuttle value="#{bindings.Departments1.inputValue}" label="#{bindings.Departments1.label}"
                                          id="sms1" size="15" binding="#{pageFlowScope.ShuttleSelectBean.shuttleBind}"
                                          partialTriggers="b1">
                        <f:selectItems value="#{bindings.Departments1.items}" id="si1"/>
                        <f:validator binding="#{bindings.Departments1.validator}"/>
                    </af:selectManyShuttle>
    

  • So suppose on a button click i want to set selected values in shuttle, so i have created a actionEvent for button in managed bean and binding of af:selectManyShuttle, so basic structure of page is like this




  • See the code of actionEvent , create an arrayList and add all values in it that you want to set as selected values and then just set the value in shuttle using binding

  •     /**Method to set selected values in af:selectManyShuttle
         * @param actionEvent
         */
        public void selectValuesShuttle(ActionEvent actionEvent) {
            DCIteratorBinding iter = (DCIteratorBinding) getBindingsCont().get("Departments1Iterator");
            ViewObject vo = iter.getViewObject();
            RowSetIterator rsi = vo.createRowSetIterator(null);
            ArrayList listVal = new ArrayList(20);
    
            while (rsi.hasNext()) {
                Row nextRow = rsi.next();
                if (nextRow.getAttribute("DepartmentId") != null) {
                    listVal.add(nextRow.getAttribute("DepartmentId"));
                }
            }
            shuttleBind.resetValue();// Reset Shuttle Component
            System.out.println("Setting values -" + listVal);
            shuttleBind.setValue(listVal.toArray()); // Setting selected values 
            AdfFacesContext.getCurrentInstance().addPartialTarget(shuttleBind);
        }
    

  • Now run this page and test your shuttle component



  • Cheers- Happy Coding

  • But this method works only when you have to set values on some action or other event after page load, because before page load , binding of shuttle component will not be accessible
  • So if you have a requirement of setting selected values on page load then you must use a list defined in managed bean and bind it to  value property of shuttle component, value property denotes selected values of shuttle 


  • And just write same code on getter of List, in this case selected values in shuttle are populated on page load

  •     List pageLoad = new ArrayList(20);
        public void setPageLoad(List pageLoad) {
            this.pageLoad = pageLoad;
        }
    
        public List getPageLoad() {
            DCIteratorBinding iter = (DCIteratorBinding) getBindingsCont().get("Departments1Iterator");
            ViewObject vo = iter.getViewObject();
            RowSetIterator rsi = vo.createRowSetIterator(null);
            while (rsi.hasNext()) {
                Row nextRow = rsi.next();
                if (nextRow.getAttribute("DepartmentId") != null) {
                    pageLoad.add(nextRow.getAttribute("DepartmentId"));
                }
            }
            return pageLoad;
        }
    

    Cheers- Use both method as per your requirement :-) Download Sample App