Uploading CSV files into dynamic ADF Faces tables – programmtically creating columns

4

In a recent article – ADF Faces File Uploading – It is really that simple! – I described how to set up file uploading with ADF Faces. Using the inputFile component, it is dead easy to develop a JSF page in which the user can upload a file and that then displays some file properties.

As a next step, I will look into the processing of CSV (comma separated values) files. In this article I will show how it is almost as easy to turn a CSV file into an ADF Faces table: columns are based on the comma separated values, table rows correspond with the records in the file, the first row can be used for column headers and each column is sortable:

When the checkbox Use first row values as Headers is checked:

When we click on the Content column, the records are sorted:....

 

The JSF page itself is very similar to the page we discussed in the previous article. The main differences are the checkbox and the table component. However, you will rarely have seen a less interesting af:table: all of the actual table content is programmatically set, so you see no columns at all in the jspx file:

        &lt;af:form usesUpload=&quot;true&quot;&gt;<br />          &lt;af:panelPage title=&quot;Upload and Process CSV File&quot;&gt;<br />            &lt;af:objectSpacer width=&quot;10&quot; height=&quot;25&quot;/&gt;<br />            &lt;af:inputFile label=&quot;File to Upload&quot; columns=&quot;90&quot;<br />                          value=&quot;#{FileProcessor.uploadedFile}&quot;/&gt;<br />            &lt;af:objectSpacer width=&quot;10&quot; height=&quot;15&quot;/&gt;<br />            &lt;af:commandButton text=&quot;Start Upload&quot;/&gt;<br />            &lt;af:objectSpacer width=&quot;10&quot; height=&quot;25&quot;/&gt;<br />            &lt;af:objectSeparator/&gt;<br />            &lt;af:panelBox&gt;<br />              &lt;af:panelForm&gt;<br />                &lt;af:inputText label=&quot;File Name&quot;<br />                              value=&quot;#{FileProcessor.filename}&quot;<br />                              readOnly=&quot;true&quot;/&gt;<br />                &lt;af:inputText label=&quot;File Size&quot;<br />                              value=&quot;#{FileProcessor.filesize}&quot;<br />                              readOnly=&quot;true&quot;/&gt;<br />                &lt;af:inputText label=&quot;File Type&quot;<br />                              value=&quot;#{FileProcessor.filetype}&quot;<br />                              readOnly=&quot;true&quot;/&gt;<br />                &lt;af:selectBooleanCheckbox id=&quot;useFirstAsHeader&quot;<br />                                          label=&quot;Use first row values as Headers&quot;<br />                                          autoSubmit=&quot;true&quot;<br />                                          value=&quot;#{CsvProcessor.useFirstRowAsHeaders}&quot;/&gt;<br />              &lt;/af:panelForm&gt;<br />            &lt;/af:panelBox&gt;<br />            &lt;af:objectSpacer width=&quot;10&quot; height=&quot;25&quot;/&gt;<br />            &lt;af:table value=&quot;#{CsvProcessor.rows}&quot; var=&quot;row&quot;<br />                      varStatus=&quot;rowStatus&quot; binding=&quot;#{CsvProcessor.table}&quot;<br />                      partialTriggers=&quot;useFirstAsHeader&quot;&gt;<br />              &lt;f:facet name=&quot;header&quot;&gt;<br />                &lt;af:outputText value=&quot;Contents Extracted from CSV file&quot;/&gt;<br />              &lt;/f:facet&gt;<br />            &lt;/af:table&gt;<br />          &lt;/af:panelPage&gt;<br />        &lt;/af:form&gt;<br />&nbsp;

The FileProcessor bean that is referenced from the inputFile component is configured in the faces-config.xml file:

    &lt;managed-bean&gt;<br />        &lt;managed-bean-name&gt;FileProcessor&lt;/managed-bean-name&gt;<br />        &lt;managed-bean-class&gt;nl.amis.adffaces.files.FileProcessor&lt;/managed-bean-class&gt;<br />        &lt;managed-bean-scope&gt;request&lt;/managed-bean-scope&gt;<br />        &lt;managed-property&gt;<br />            &lt;property-name&gt;tablecreator&lt;/property-name&gt;<br />            &lt;property-class&gt;nl.amis.adffaces.files.CSVtoADFTableProcessor&lt;/property-class&gt;<br />            &lt;value&gt;#{CsvProcessor}&lt;/value&gt;<br />        &lt;/managed-property&gt;<br />    &lt;/managed-bean&gt;<br />    &lt;managed-bean&gt;<br />        &lt;managed-bean-name&gt;CsvProcessor&lt;/managed-bean-name&gt;<br />        &lt;managed-bean-class&gt;nl.amis.adffaces.files.CSVtoADFTableProcessor&lt;/managed-bean-class&gt;<br />        &lt;managed-bean-scope&gt;session&lt;/managed-bean-scope&gt;<br />    &lt;/managed-bean&gt;<br />&nbsp;

It has a managed property tablecreator that gets injected. This property referes to an instance of class CSVtoADFTableProcessor, a class that takes the file contents and turns it into columns and rows for display in an ADF Faces table component. Let’s first look at the FileProcessor:

package nl.amis.adffaces.files;<br /><br />import java.io.IOException;<br />import oracle.adf.view.faces.model.UploadedFile;<br /><br />public class FileProcessor {<br /><br />    private CSVtoADFTableProcessor tablecreator;<br />    private UploadedFile uploadedFile;<br />    private String filename;<br />    private long filesize;<br />    private String filecontents;<br />    private String filetype;<br /><br /><br />    public FileProcessor() {<br />    }<br /><br />    public void setUploadedFile(UploadedFile uploadedFile) {<br />        this.uploadedFile = uploadedFile;<br />        this.filename = uploadedFile.getFilename();<br />        this.filesize = uploadedFile.getLength();<br />        this.filetype = uploadedFile.getContentType();<br />        try {<br />            tablecreator.processCSV(uploadedFile.getInputStream());<br />        } catch (IOException e) {<br />            // TODO<br />        }<br />    }<br /><br />    public UploadedFile getUploadedFile() {<br />        return uploadedFile;<br />    }<br /><br />    public void setFilename(String filename) {<br />        this.filename = filename;<br />    }<br /><br />    public String getFilename() {<br />        return filename;<br />    }<br /><br />    public void setFilesize(long filesize) {<br />        this.filesize = filesize;<br />    }<br /><br />    public long getFilesize() {<br />        return filesize;<br />    }<br /><br />    public void setFilecontents(String filecontents) {<br />        this.filecontents = filecontents;<br />    }<br /><br />    public String getFilecontents() {<br />        return filecontents;<br />    }<br /><br />    public void setFiletype(String filetype) {<br />        this.filetype = filetype;<br />    }<br /><br />    public String getFiletype() {<br />        return filetype;<br />    }<br /><br />    public void setTablecreator(CSVtoADFTableProcessor tablecreator) {<br />        this.tablecreator = tablecreator;<br />    }<br /><br />    public CSVtoADFTableProcessor getTablecreator() {<br />        return tablecreator;<br />    }<br />}<br />&nbsp;

Most of it is trivial bean properties with getters and setters, including the reference to the CSVtoADFTableProcess instance. The setUploadedFile() method is invoked whenever the user uploads a file. This method then sets the other FileProcessor bean properties and gives an opportunity to the tablecreator to step in, process the file contents and manipulate the table based on the contents.

The next class to discuss is of course the CSVtoADFTableProcessor. The binding attribute of the af:table component refers to this class instance. One of the things it does is take the uploaded file (InputStream) and parse it into rows and columns based on the CSV format (newlines to demarcate records, commas to delimit fields in records). For this generic parsing operation, I make use of one of the Ostermiller Java Utilities – the CSV Parser. To use this utility, I have downloaded the JAR (750Kb), copied it to the WEB-INF/lib directory of my project and set up the JAR as a project library in JDeveloper.

I can now leverage the CSV parsing capabilities of this utility with very little effort:

    public void processCSV(InputStream csvFile)
{<br /
>        // Parse the data, using http://ostermiller.org/utils/download.html<br />        String[][] csvvalues=null;<br />        try {<br />            csvvalues = CSVParser.parse(new InputStreamReader(csvFile));<br />        } catch (IOException e) {<br />            // TODO<br />        }<br />        ....<br />&nbsp;

The class as a whole is as follows:

package nl.amis.adffaces.files;<br /><br />import com.Ostermiller.util.CSVParser;<br /><br />import java.io.IOException;<br />import java.io.InputStream;<br />import java.io.InputStreamReader;<br /><br />import java.util.ArrayList;<br />import java.util.HashMap;<br />import java.util.List;<br /><br />import java.util.Map;<br /><br />import javax.faces.application.Application;<br />import javax.faces.context.FacesContext;<br /><br />import oracle.adf.view.faces.component.core.data.CoreColumn;<br />import oracle.adf.view.faces.component.core.data.CoreTable;<br />import oracle.adf.view.faces.component.core.output.CoreOutputText;<br /><br />public class CSVtoADFTableProcessor {<br />    private CoreTable table;<br />    private List rows = new ArrayList();<br />    private boolean useFirstRowAsHeaders = false;<br />    private int numberOfColumns;<br /><br />    public CSVtoADFTableProcessor() {<br />    }<br /><br /><br />    public void processCSV(InputStream csvFile) {<br />        // Parse the data, using http://ostermiller.org/utils/download.html<br />        String[][] csvvalues = null;<br />        try {<br />            csvvalues = CSVParser.parse(new InputStreamReader(csvFile));<br />        } catch (IOException e) {<br />            // TODO<br />        }<br />        rows = new ArrayList();<br /><br />        numberOfColumns = 0;<br />        for (int i = 0; i &lt; csvvalues.length; i++) {<br />            Map tablerow = new HashMap();<br />            for (int j = 0; j &lt; csvvalues[i].length; j++) {<br />                if (j &gt; numberOfColumns)<br />                    numberOfColumns = j;<br />                tablerow.put(&quot;cell&quot; + (j + 1), csvvalues[i][j]);<br />            } // for cells<br />            rows.add(tablerow);<br />        } // for rows<br /><br /><br />        setupTableColumns();<br /><br />    }<br /><br />    private void setupTableColumns() {<br />        // take parsed data and create the columns for the ADF Faces table<br />        // as well as the rows list of table backing data set<br />        FacesContext fc = FacesContext.getCurrentInstance();<br />        Application app = fc.getApplication();<br />        table.getChildren().clear();<br />        CoreColumn col = <br />            (CoreColumn)app.createComponent(CoreColumn.COMPONENT_TYPE);<br />        col.setId(&quot;rowheader&quot;);<br />        CoreOutputText cell = <br />            (CoreOutputText)app.createComponent(CoreOutputText.COMPONENT_TYPE);<br />        cell.setId(&quot;rowcell&quot;);<br />        cell.setValueBinding(&quot;value&quot;, <br />                             app.createValueBinding(&quot;#{rowStatus.index}&quot;));<br /><br />        col.getChildren().add(cell);<br />        col.setHeaderText(&quot;^&quot;);<br />        table.getChildren().add(col);<br /><br /><br />        for (int i = 0; i &lt; numberOfColumns + 1; i++) {<br />            col = (CoreColumn)app.createComponent(CoreColumn.COMPONENT_TYPE);<br />            col.setId(&quot;col&quot; + i);<br />            cell = <br />(CoreOutputText)app.createComponent(CoreOutputText.COMPONENT_TYPE);<br />            cell.setId(&quot;cell&quot; + i);<br />            cell.setValueBinding(&quot;value&quot;, <br />                                 app.createValueBinding(&quot;#{row['cell&quot; + <br />                                                        (i + 1) + &quot;']}&quot;));<br /><br />            col.getChildren().add(cell);<br />            col.setValueBinding(&quot;headerText&quot;, <br />                                app.createValueBinding(&quot;#{CsvProcessor.columnHeaders['&quot; + <br />                                                       i + &quot;']}&quot;));<br />            col.setSortable(true);<br />            col.setSortProperty(&quot;cell&quot; + (i + 1));<br />            table.getChildren().add(col);<br />        }<br />    }<br /><br />    public void setTable(CoreTable table) {<br />        this.table = table;<br />    }<br /><br />    public CoreTable getTable() {<br />        return table;<br />    }<br /><br />    public void setRows(List rows) {<br />        this.rows = rows;<br />    }<br /><br />    public List getRows() {<br />        return rows.subList(useFirstRowAsHeaders ? 1 : 0, rows.size());<br />    }<br /><br />    public Map getColumnHeaders() {<br />        Map columnHeaders = new HashMap();<br />        if (useFirstRowAsHeaders) {<br />            for (int i = 0; i &lt; numberOfColumns + 1; i++)<br />                columnHeaders.put(Integer.toString(i), <br />                                  ((Map)rows.get(0)).get(&quot;cell&quot; + (i + 1)));<br /><br />        } else<br />            for (int i = 0; i &lt; numberOfColumns + 1; i++)<br />                columnHeaders.put(Integer.toString(i), <br />                                  String.valueOf((char)('A' + i)));<br />        return columnHeaders;<br />    }<br /><br />    public void setUseFirstRowAsHeaders(boolean useFirstRowAsHeaders) {<br />        this.useFirstRowAsHeaders = useFirstRowAsHeaders;<br />    }<br /><br />    public boolean isUseFirstRowAsHeaders() {<br />        return useFirstRowAsHeaders;<br />    }<br />}<br /><br />&nbsp;

The interesting bits and pieces are first of all in processCSV (a method that could do with a little refactoring – I leave that as an exercise to the readerSmiley). It turns the file content into a multi dimensional array. Then it call setupTableColumns() to manipulate the table: it removes the current list of children from the table component. Next it creates the first column that will contain rownumbers;the value for this column is set with an EL Expression that refers to the rowStatus variable – see the af:table specification in the jspx table.

Then it creates a column for every field found in the file records. The column’s headerText is set using a value binding expression to an element in the getColumnHeaders map on this class. The column contents is also set using an EL Expression in a ValueBinding; it refers to a field in the row variable of type Map. This corresponds with the af:table set up in the JSPX page:

  &lt;af:table value=&quot;#{CsvProcessor.rows}&quot; var=&quot;row&quot;<br />            varStatus=&quot;rowStatus&quot; binding=&quot;#{CsvProcessor.table}&quot;<br />            partialTriggers=&quot;useFirstAsHeader&quot;&gt; <br />

The row variable is available during table rendering – it contains the individual elements retrieved from the #{CsvProcessor.rows} list, the data source for the table. This rows collection is an ArrayList that is set up with HashMap elements. The

            cell.setValueBinding(&quot;value&quot;, <br />                                 app.createValueBinding(&quot;#{row['cell&quot; + <br />                                                        (i + 1) + &quot;']}&quot;));<br />&nbsp;

refers to the cell1, cell2, … celln keys in the HashMap.

Note that all columns thus created are made sortable by setting the sortable property and specifying the SortProperty – to cell1, cell2… celln.

The last interesting bit to discuss is the checkbox Use first row values as Headers:

                &lt;af:selectBooleanCheckbox id=&quot;useFirstAsHeader&quot;<br />                                          label=&quot;Use first row values as Headers&quot;<br />                                          autoSubmit=&quot;true&quot;<br />                                          value=&quot;#{CsvProcessor.useFirstRowAsHeaders}&quot;/&gt;<br />&nbsp;

it is bound to the useFirstRowAsHeaders bean proper

ty in the CsvProcessor bean. It has its autoSubmit attribute set to true, meaning that the page values are submitted in an AJAX (PPR) request as soon as the checkbox is toggled. The table includes the id of this checkbox in its partialTriggers attribute, indicating that it should be refreshed whenever the checkbox is toggled.

The effect of toggling the checkbox or toggling the useFirstRowAsHeaders boolean in the CSVtoADFTableProcessor class is that the next call to getColumnHeaders() returns a different result: with useFirstRowAsHeaders set to false, the columnHeaders map contains the letters of the alphabet. When set to true, it returns the values from the first row read from the CSV file. In that latter case, the getRows() method returns the rows collection, starting at the second record:

    public List getRows() {<br />        return rows.subList(useFirstRowAsHeaders ? 1 : 0, rows.size());<br />    }<br />&nbsp;

Resources

Download JDeveloper 10.1.3.2 application: ProcessCVSFilesToADFTable.zip .

 

Share.

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.

4 Comments

  1. Would someone have a runable version of this project/feature, preferably with JDeveloper 11g.
    I did try with 10.1.3.2 but I’m not sure I found the appropriate utility jar files, and it fails with both versions.

    thanks in advance

  2. Erro ocurred when clikcing check box:

    Aug 16, 2007 2:58:26 PM oracle.adfinternal.view.faces.renderkit.core.xhtml.PanelPartialRootRenderer encodeAll
    SEVERE: Error during partial-page rendering
    javax.faces.el.EvaluationException: javax.faces.el.EvaluationException: Error getting property ‘rows’ from bean of type org.mtahq.adffaces.csv.view.managed.CSVtoADFTableProcessor: java.lang.IllegalArgumentException: fromIndex(1) > toIndex(0)