Saturday, December 1, 2012

Import data from a CSV file into View Object

There is a use case where in you need to import data from a CSV file into a View Object, Here i will explain a use case where in i will be importing the attendance for a particular student.
The CSV file will be in a format as below(first line will be header info and subsequent lines will have attendance data)
SSN,Name,MonHrs,TueHrs,WedHrs,ThuHrs,FriHrs,SatHrs,SunHrs
1234-12-123,Sanjeeb,8,8,8,8,8,8,8 
4567-56-987,XYZ,7,8,5,8,8,7,8

In my page i  have dropped a upload component i.e. <af:inputFile/> which will allow me to select a file from my system and import the data into View object. To achieve the same i have implemented a valueChangeListener method in a managed bean for this component . The code below are self explanatory as i have included comments to understand better.


    public void fileUploaded(ValueChangeEvent valueChangeEvent) {
        //getting the file instance from the event.
        UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
         try {
          //calling a private method to parse the CSV file and import the data into table component
           parseFile(file.getInputStream());
          //Refresh the table component programmatically, importTab is the binding of the table component
           AdfFacesContext.getCurrentInstance().addPartialTarget(importTab);
         } catch (IOException e) {
           // TODO : Handle your exception

         }
    }



    private void parseFile(java.io.InputStream file) {
        BufferedReader reader =
            new BufferedReader(new InputStreamReader(file));
        String strLine = "";
        StringTokenizer st = null;
        int lineNumber = 0, tokenNumber = 0;
        Row rw = null;

        CollectionModel _tableModel = (CollectionModel)impTab.getValue();
        //the ADF object that implements the CollectionModel is JUCtrlHierBinding. It
        //is wrapped by the CollectionModel API
        JUCtrlHierBinding _adfTableBinding =
            (JUCtrlHierBinding)_tableModel.getWrappedData();
        //Acess the ADF iterator binding that is used with ADF table binding
        DCIteratorBinding it = _adfTableBinding.getDCIteratorBinding();

        //read comma separated file line by line
        try {
            while ((strLine = reader.readLine()) != null) {
                lineNumber++;
                // create a new row skip the header  (header has linenumber 1)
                if (lineNumber > 1) {
                    rw = it.getNavigatableRowIterator().createRow();
                    rw.setNewRowState(Row.STATUS_INITIALIZED);
                    it.getNavigatableRowIterator().insertRow(rw);
                }

                //break comma separated line using ","
                st = new StringTokenizer(strLine, ",");
                while (st.hasMoreTokens()) {
                    //display csv values
                    tokenNumber++;

                    String theToken = st.nextToken();
                    System.out.println("Line # " + lineNumber + ", Token # " +
                                       tokenNumber + ", Token : " + theToken);
                    if (lineNumber > 1) {
                        // set Attribute Values
                        switch (tokenNumber) {
                        case 1:
                            rw.setAttribute("Ssn", theToken);
                        case 2:
                            rw.setAttribute("Firstname", theToken);
                        case 3:
                                rw.setAttribute("Monhrs", theToken);
                        case 4:
                                rw.setAttribute("Tuehrs", theToken);
                        case 5:
                                rw.setAttribute("Wedhrs", theToken);
                        case 6:
                                rw.setAttribute("Thrhrs", theToken);
                        case 7:
                                rw.setAttribute("Frihrs", theToken);
                        case 8:
                                rw.setAttribute("Sathrs", theToken);
                        case 9:
                                rw.setAttribute("Sunhrs", theToken);
                     
                        }
                    }
                }
                //reset token number
                tokenNumber = 0;
            }
        } catch (IOException e) {
            // TODO add more
            FacesContext fctx = FacesContext.getCurrentInstance();
            fctx.addMessage(impTab.getClientId(fctx),
                            new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                             "Content Error in Uploaded file",
                                             e.getMessage()));
        } catch (Exception e) {
            FacesContext fctx = FacesContext.getCurrentInstance();
            fctx.addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "Data Error in Uploaded file",
                                             e.getMessage()));
        }
    }


Hope it helps !!!