Please disable your adblock and script blockers to view this page

Search this blog

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

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

Tuesday 29 July 2014

Showing highlighted holiday calendar in af:inputDate date picker (ADF 12.1.3)

Hello All
This post is about showing highlighted days for holidays in af:inputDate and user must not be able to select these dates
here i am using Jdeveloper 12.1.3
you can do this using af:calendar
https://blogs.oracle.com/adf/entry/display_holiday_name_in_af
but i have a requirement to show holidays while user selects date using af:inputDate

so for this requirement first step is easy to do and there is lots of post about disabling specific days in calendar of af:inputDate

Step 1. Disable specific days -
  • you can see there is property in af:inputDate for setting disabled days, this filed takes a value of type List supported by DateListProvider interface




  • for this purpose i have created a bean that implements methods of DateListProvider , in Overridden method i have defined a list that contains dates of holidays that i want to disable in af:inputDate

  • package holiday.view.bean;
    
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    
    import javax.faces.context.FacesContext;
    
    import org.apache.myfaces.trinidad.model.DateListProvider;
    
    public class HolidayBean implements DateListProvider {
        public HolidayBean() {
        }
    
        @Override
        public List<Date> getDateList(FacesContext facesContext, Calendar calendar, Date date, Date date2) {
            List<java.util.Date> holiDay = new ArrayList();
            holiDay.add(new Date("27-July-2014"));
            holiDay.add(new Date("29-July-2014"));
            holiDay.add(new Date("10-Aug-2014"));
            holiDay.add(new Date("25-Dec-2014"));
            holiDay.add(new Date("01-Jan-2015"));
            holiDay.add(new Date("22-Oct-2014"));
            holiDay.add(new Date("23-Oct-2014"));
            holiDay.add(new Date("24-Oct-2014"));
    
            return holiDay;
            //return Collections.emptyList();
        }
    }
    

  • attached this bean to disabledDays property of af:inputDate


  • now first part is done we can see all holidays as disabled in calendar of af:inputDate

Step 2. Highlight disabled holidays -
  • but it is not easy to find holidays as all are in grey, so i have to highlight all disabled days , so for this requirement , create a skin in viewController project and write this

  • af|chooseDate::regular-day:disabled{
        background-color: red;
        color: ButtonFace;
    }
    

  • af:chooseDate is used because internally af:inputDate opens af:chooseDate as date picker so i have to change property of af:chooseDate, now run your application

Happy Learning :)

Wednesday 23 July 2014

Search on (Filtering) child nodes of af:treeTable using viewCriteria in Oracle ADF (11g,12c)

Hello all
this post is about filtering treeTable on basis of child nodes in Oracle ADF
in this tutorial i have used Departments and Employees table of HR schema to create treeTable
see how to create treeTable-
http://www.awasthiashish.com/2012/11/tree-table-component-in-oracle.html
http://www.awasthiashish.com/2013/08/tree-table-component-with-declarative.html

treeTable look like this-


now next is to search on Employee Names



  • i have dropped a input text for search string and a button to search on page , here i am searching on first name of employees 


  • now created a view Criteria in Employee viewObject to search on first name


  • This viewCriteria doesn't work directly on Employee viewObject, to search in treeTable we have to override createViewLinkAccessorRS method in Departments (master vo) VOImpl class, and in this method we have to call Employees ViewCriteria explicitly , this will filter Employee Vo Rowset as per bind-variable value when a node is disclosed at runtime

  •     /**
         * @param associationDefImpl
         * @param viewObjectImpl
         * @param row
         * @param object
         * @return
         */
        protected ViewRowSetImpl createViewLinkAccessorRS(AssociationDefImpl associationDefImpl,
                                                          ViewObjectImpl viewObjectImpl, Row row, Object[] object) {
    
    
            ViewRowSetImpl viewRowSetImpl = super.createViewLinkAccessorRS(associationDefImpl, viewObjectImpl, row, object);
    
            String firstName = getFirstNm();
            ViewCriteriaManager vcm = viewObjectImpl.getViewCriteriaManager();
            ViewCriteria vc = vcm.getViewCriteria("EmployeesVOCriteria");
            VariableValueManager vvm = vc.ensureVariableManager();
            vvm.setVariableValue("BindFirstNm", firstName);
            viewObjectImpl.applyViewCriteria(vc);
            return viewRowSetImpl;
    
    
            // return super.createViewLinkAccessorRS(associationDefImpl, viewObjectImpl, row, object);
        }
    

  • to pass bind-variable value i have created a variable and it's accessors in VoImpl and exposed set method to client that is further used by managed bean

  •     private String firstNm;
        public void setFirstNm(String firstNm) {
            this.firstNm = firstNm;
        }
    
        public String getFirstNm() {
            return firstNm;
        }
    

  • now this setter method is called in managed bean search button action to set bind variable value

  •     /**Method to search in treeTable childs
         * @param actionEvent
         */
        public void searchAction(ActionEvent actionEvent) {
            if (firstNmBind.getValue() != null) {
                OperationBinding ob = executeOperation("setFirstNm");
                // firstNmBind is binding of inputText
                ob.getParamsMap().put("firstNm", firstNmBind.getValue().toString());
                ob.execute();
                /* Method Expand treeTable after Search see- 
                 http://www.awasthiashish.com/2013/10/expand-and-collapse-aftreetable.html*/
                expandTreeTable();
                AdfFacesContext.getCurrentInstance().addPartialTarget(treeTabBind);
    
            }
        }
    

  • Run your application and see-
    Cheers- Happy Learning
    Download Sample ADF Application

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)