Recently by Michael Bevels


This is a follow-up to my last post about Exporting an ExtJs GridPanel to Word XML.  In that post I showed how to get all the configuration and state properties from an ExtJs GridPanel.  This post will demonstrate how to generate a basic table within a Word XML document using Ruby to produce XML

Section 1: Building a sample

The first step is to open Word, Open Office, or anything that will generate Open XML.  If you're not an Open XML expert, you can create a sample document of what you want the final product to look like.  Once you've got it formatted, save it in XML format.  I suggest labeling everything so it's easy to find in the XML later.  For example, if you're creating a table it might look like this:

Header 1       | Header 2       | Header 3
Row 1, Col 1 | Row 1, Col 2 | Row 1, Col 3
Row 2, Col 1 | Row 2, Col 2 | Row 2, Col 3

There are three columns with names Header 1, Header 2, and Header 3.  The data resides below these headers in Row 1 and Row 2.

Section 2: Building templates

The next step is to start building templates.  If you're just building an XML document with a simple table, you can use three simple templates: document, table, and row.

The "document" template can contain everything outside the of the content of <w:body> tags which will be generated by the Ruby code in Section 3.  This document template defines the fonts, styles, and document properties used by the sample generated in section 1.

document-template.xml - Note that the "{table}" string will be replaced with the generated table template.

<?mso-application progid="Word.Document"?>
<w:wordDocument xml:space="preserve" w:embeddedObjPresent="no">
<o:DocumentProperties>...</o:DocumentProperties>
<o:CustomDocumentProperties>...</o:CustomDocumentProperties>
<w:fonts>...</w:fonts>
<w:lists>...</w:lists>
<w:styles>...</w:styles>
<w:docPr>...</w:docPr>
<w:body>{table}</w:body>
</w:wordDocument>

table-template.xml - Note that the "{rows}" string will be replaced with the generated rows template.  If you're familiar with html tables, you should be able to recognize some patterns here.

<w:tbl> defines a table.  <w:tr> defines a row.  <w:tc> defines a cell.  Everything in between specifies the formatting.
        <w:tbl>
           <w:tblPr>
               <w:tblStyle w:val="Table1"/>
               <w:tblW w:w="9973.2467" w:type="dxa"/>
               <w:tblInd w:w="0" w:type="auto"/>
               <w:jc w:val="left"/>
           </w:tblPr>
           <w:tblGrid>
               <w:gridCol w:w="3324.3676"/>
               <w:gridCol w:w="3324.3676"/>
               <w:gridCol w:w="3324.3676"/>
           </w:tblGrid>
           <w:tr>
               <w:trPr/>
               <w:tc>
                   <w:tcPr>
                       <w:tcW w:type="dxa" w:w="3324.3676"/>
                       <w:tcMar/>
                       <w:tcBorders>
                           <w:top w:val="single" w:sz="0" w:color="000000"/>
                           <w:bottom w:val="single" w:sz="0" w:color="000000"/>
                           <w:left w:val="single" w:sz="0" w:color="000000"/>
                           <w:right w:val="none" w:sz="0" w:color="auto"/>
                       </w:tcBorders>
                   </w:tcPr>
                   <w:p>
                       <w:pPr>
                           <w:pStyle w:val="Table_20_Contents"/>
                       </w:pPr>
                       <w:r>
                           <w:t>Header 1</w:t>
                       </w:r>
                   </w:p>
               </w:tc>
               <w:tc>
                   <w:tcPr>
                       <w:tcW w:type="dxa" w:w="3324.3676"/>
                       <w:tcMar/>
                       <w:tcBorders>
                           <w:top w:val="single" w:sz="0" w:color="000000"/>
                           <w:bottom w:val="single" w:sz="0" w:color="000000"/>
                           <w:left w:val="single" w:sz="0" w:color="000000"/>
                           <w:right w:val="none" w:sz="0" w:color="auto"/>
                       </w:tcBorders>
                   </w:tcPr>
                   <w:p>
                       <w:pPr>
                           <w:pStyle w:val="Table_20_Contents"/>
                       </w:pPr>
                       <w:r>
                           <w:t>Header 2</w:t>
                       </w:r>
                   </w:p>
               </w:tc>
               #another w:tc defined here for Header 3...
           </w:tr>
        {rows}
        </w:tblPr>
        <w:p>
            <w:pPr>
                <w:pStyle w:val="Standard"/>
            </w:pPr>
        </w:p>
        <w:sectPr>
            <w:type w:val="next-page"/>
            <w:pgSz w:w="12241.5302" w:h="15841.9803" w:orient="portrait"/>
            <w:pgMar w:top="1133.9978" w:bottom="1133.9978" w:left="1133.9978" w:gutter="0" w:right="1133.9978"/>
            <w:pgBorders w:offset-from="text"/>
        </w:sectPr>

row-template.xml - Note that the "{column_#_value}" strings will be replaced with the corresponding values for the row being generated.

            <w:tr>
                <w:trPr/>
                <w:tc>
                    <w:tcPr>
                        <w:tcW w:type="dxa" w:w="3324.3676"/>
                        <w:tcMar/>
                        <w:tcBorders>
                            <w:top w:val="none" w:sz="0" w:color="auto"/>
                            <w:bottom w:val="single" w:sz="0" w:color="000000"/>
                            <w:left w:val="single" w:sz="0" w:color="000000"/>
                            <w:right w:val="none" w:sz="0" w:color="auto"/>
                        </w:tcBorders>
                    </w:tcPr>
                    <w:p>
                        <w:pPr>
                            <w:pStyle w:val="Table_20_Contents"/>
                        </w:pPr>
                        <w:r>
                            <w:t>{column_1_value}</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
                <w:tc>
                    <w:tcPr>
                        <w:tcW w:type="dxa" w:w="3324.3676"/>
                        <w:tcMar/>
                        <w:tcBorders>
                            <w:top w:val="none" w:sz="0" w:color="auto"/>
                            <w:bottom w:val="single" w:sz="0" w:color="000000"/>
                            <w:left w:val="single" w:sz="0" w:color="000000"/>
                            <w:right w:val="none" w:sz="0" w:color="auto"/>
                        </w:tcBorders>
                    </w:tcPr>
                    <w:p>
                        <w:pPr>
                            <w:pStyle w:val="Table_20_Contents"/>
                        </w:pPr>
                        <w:r>
                            <w:t>{column_2_value}</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
                #another w:tc defined with {column_3_value}...
            </w:tr>
        </w:tbl>

Section 3:  Injecting data into the templates and creating an XML file

The code snippet below queries for some data. It loops over the "table_data" returned and builds rows based on the row-template.xml defined in section 2.  The rows are concatenated and injected into the table template, which in turn is injected into the document template.  Obviously some of of these steps are unnecessary (the table template could be a part of the document template, thus skipping a substitution), but I wanted to show that you can make templates as granular as you like.  In my own solution, I have templates for cells, header rows, and much more.  I used the configuration and state data of the ExtJs GridPanel (described in a previous blog post) and looped over column names and values to generate a table from scratch.  However, most of the work in this blog post is already done for you.

Depending on the size of your dataset, you may want to write periodically to the file.  Holding many iterations of row-template.xml in memory can be costly.

#create a new empty xml document
document = File.new(some_filename, 'a')

#query for data
table_data = SomeObject.find(:all, :conditions => 'some conditions...')

document_template = File.open('path/to/document-template.xml').read

table_template = File.open('path/to/table-template.xml').read
rows = []
table_data.each do |row_data|
    row_template = File.open('path/to/row-template.xml').read
    row_template.gsub!('{column_1_value}', row_data.col_1) #substitute in whatever returns the data you need to put in the Col 1 column.
    row_template.gsub!('{column_2_value}', row_data.col_2) #substitute in whatever returns the data you need to put in the Col 2 column.
    row_template.gsub!('{column_3_value}', row_data.col_3) #substitute in whatever returns the data you need to put in the Col 3 column.
   
    #add the row to the master array of rows
    rows << row_template
end

#substitute the dynamically generated rows into the table template
table_template.gsub!('{rows}', rows.join(''))

#substitute the dynamically generated table into the document template
document_template.gsub!('{table}', table)

#write everything to the new xml document.  As I said before you'll probably want to write to the xml document more frequently than
#this example to avoid Out-Of-Memory errors.
document.puts document_template
document.close


As you can see, this is a very basic example.  However, the same principals can be applied to much more complex and dynamic situations such as a exporting a fully user-configurable ExtJs GridPanel to Word XML.  This process can also be applied to generating Excel XML files.
This blog post will lay out some of steps for exporting an ExtJs GridPanel to Word XML.  This is useful if you want to save or print what's currently displayed in the grid.  I am writing a subsequent post with steps on how to actually generate a Word XML file, but for now I'll focus on defining a grid, getting the grid's state, sending the grid's state to a controller, and prompting the user to save the generated Word XML document.

Technologies used:
- Ruby on Rails
- mod_xsendfile for Apache2/Apache2.2
- ExtJs
- javascript

At a high level, the following happens:
1. Gather and send the GridPanel state/configuration to the controller.
2. The controller runs a query and generates Word XML based on the query results.
3. The Word XML file is presented to the user via an "Open/Save As" dialog using XSendFile.

Section 1: Getting the current state/configuration of the GridPanel

If you're familiar with ExtJs GridPanel's you know they can be configured by each user viewing the panel.  Columns can be added, removed, grouped, shortened, lengthened and repositioned.  To capture the GridPanel's current state and pass it to the exporter, I wrote the following javascript.  It calculates and returns an array containing the column order, which column data indexes belong to which titles, the grouped field (if any), the sorted field, the sorted direction, and the widths of each column.  You will see where this function is used when I define the GridPanel in the next section.


var prepareExport = function(gridStore, gridColumnModel) {
    var sort = null;
    var direction = null;
    if (gridStore.getSortState()) {
        sort = gridStore.getSortState().field();
        direction = gridStore.getSortState().direction;
    }
   
    var columnOrder = []; //ordered list of columns reflecting the GridPanel's state
    var columnsToTitles = {}; //map of ext field mappings to column titles
    var columnsToWidths = {}; //width of each column
    var totalWidth = 0;
    var groupByField = gridStore.groupField; //the store's current grouping field ('false' if not grouped)
   
    var storeReaderMapping = gridStore.fields.items;
   
    //check to see if the groupField has a corresponding mapping
    for (var i = 0; i < gridReaderMapping.length; i++) {
        if (gridReaderMapping[i].name == gridStore.groupField && gridReaderMapping[i].mapping != null) {
            groupByField = gridReaderMapping[i].mapping;
            break;
        }
    }
   
    //get the total width of the displayed columns (this will be used later when generating the Word XML)
    gridColumnModel.getColumnsBy(function(c) {
        if (!c.hidden) {
            totalWidth = totalWidth + c.width;
        }
    });
   
    //iterate over the grid's column model.  For displayed columns, get the ext field names (mappings) and column titles
    gridColumnModel.getColumnsBy(function(c) {
        if (!c.hidden) {
            for (var i = 0; i < gridReaderMapping.length; i++) {
                if (gridReaderMapping[i].name == c.dataIndex && gridReaderMapping[i].mapping == null) {
                    columnOrder.push(gridReaderMapping[i].name);
                    var key = gridReaderMapping[i].name;
                    columnsToTitles[key] = c.header;
                    columnsToWidths[key] = c.width/totalWidth;
                    break;
                }
                else if (gridReaderMapping[i].name == c.dataIndex && gridReaderMapping[i].mapping != null) {
                    //if the name and mapping are different (i.e. a mapping exists), we need to push the mapping and not the name
                    columnOrder.push(gridReaderMapping[i].mapping);
                    var key = gridReaderMapping[i].mapping;
                    columnsToTitles[key] = c.header;
                    columnsToWidths[key] = c.width/totalWidth;
                    break;
                }
            }
        }
    });
   
    return [columnOrder, columnsToTitles, groupByField, sort, direction, columnsToWidths];
};



Section 2: The GridPanel

Here's a basic ExtJs GridPanel.  Note the "exportButton" is defined in Section 3.

var gridReaderMapping = [
    {name: 'id'},
    {name: 'col_one'},
    {name: 'col_two', mapping: 'some_mapping'},
    {name: 'col_three'}
];

var gridColumnModel = new Ext.grid.ColumnModel({
    defaults: {sortable: true},
    columns: [
        {header: 'ID', dataIndex: 'id'},
        {header: 'Column One', dataIndex: 'col_one'},
        {header: 'Column Two', dataIndex: 'col_two'},
        {header: 'Column Three', dataIndex: 'col_three'}
    ]
});

var store = new Ext.data.GroupingStore({
    proxy: new Ext.dataHttpProxy({
        url: 'give/me/my/data'
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader({
        root: 'data',
        totalProperty: 'total',
        messageProperty: 'message'
    }, gridReaderMapping)
});

var grid = new Ext.grid.GridPanel({
    id: 'gridpanel',
    ds: gridStore,
    cm: gridColumnModel,
    sm: new Ext.grid.RowSelectionModel({
        singleSelect: true
    }),
    tbar: [exportButton],
    view: etc, etc, etc, etc...
});


Section 3: The Export Button

When the export button is clicked it gathers all the necessary data from the GridPanel (columns, widths, etc) and passes that data along with query parameters to the controller.  The controller runs a query and generates the Word XML file.  Section 4 describes what happens when the Ajax request returns the data successfully.

As I said at the beginning of this post, I will follow on with another post about the actual Word XML generation.  The Word XML generation isn't too scary.  If you're impatient, here are a few tips on Word XML generation.
    1. You can start by creating a small Word XML file with a single table using MS Word or Open Office. 
    2. Open the XML file with the XML viewer/editor of your choice.  Your table will be buried somewhere between <w:body> and </w:body>.  All the other sections of the XML can remain the same. 
    3. You can create a series of templates for Word XML tables and rows based on the patterns you see in your Word XML sample.
    4. In your Word XML generator, substitute values into these templates to build tables.
    5. Insert the generated templates into a "master" template.

var exportButton = new Ext.Button({
    renderTo: this.wrap,
    listeners: {
        click: function (node, event) {
            var exportConfig = prepareExport(grid.getStore(), grid.getColumnModel());
           
            Ext.Ajax.request({
                url: 'url/to/query/for/data'
                params: {
                    'columnsToTitles': Ext.util.JSON.encode(exportConfig[1]),
                    'columnsToWidths': Ext.util.JSON.encode(exportConfig[5]),
                    'columnOrder[]': exportConfig[0],
                    'groupByExport': exportConfig[2],
                    'groupBy': gridStore.groupField,
                    'groupDir': 'ASC',
                    'sort': exportConfig[3],
                    'dir': exportConfig[4],
                    'export': true
                    'query': build_some_query_params_to_pass_to_the_controller
                },
                success: function(response, opts) {
                    window.location.href = 'path/to/exporter_controller/export_word_XML'
                },
                failure: function(response, opts) {
                    //output error message
                },
                scope: this
            });
        }
    }
});


Section 4:  Downloading the Word XML

Using XSendFile to prompt the user with an "Open/Save As" dialog box.

class ExportController < ApplicationController
    def export_word_XML
        filename = "#{X_SENDFILEPATH}/word_doc.xml"
        if (File.exist?(filename))
            send_file filename, :x_sendfile => true
        else
            render :nothing => true
        end
    end
end

Stay tuned for the upcoming Word XML generation blog post!

I recently needed to create a "JSF Editable Datatable" where all fields (or a subset) could be edited at once. Here's what I came up with...

My requirements:

  • Use a standard JSF datatable.
  • When user clicks the Edit Button, all fields (or a subset) become editable inputText components.
  • When a user clicks the Save Button, the changes will be saved to the affected objects and persisted to the DB.

My implementation involves the following:

  • IceFaces, Hibernate, Spring.
  • 1 jspx page with an ice:datatable component.
  • 1 backing bean with edit and save actions for the datatable.

The jspx:

<jsp:root
        xmlns:jsp="http://java.sun.com/JSP/Page"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:c="http://java.sun.com/jstl/core"
        xmlns:ice="http://www.icesoft.com/icefaces/component"
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        version="2.0">
    <jsp:directive.page contentType="text/html"/>
    <jsp:output omit-xml-declaration="no"
                doctype-root-element="html"
                doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
                doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>

    <ice:dataTable id="editableDatatable" value="#{backingBean.elements}" var="element">
        <ice:column>
            <f:facet name="header">
                <ice:outputText value="Value 1"/>
            </f:facet>
            <h:inputText disabled="#{backingbean.elementsDisabled}"
                         value="#{element.value1}"/>
        </ice:column>
        <ice:column>
            <f:facet name="header">
                <ice:outputText value="Value 2"/>
            </f:facet>
            <h:inputText disabled="#{backingbean.elementsDisabled}"
                         value="#{element.value2}"/>
        </ice:column>
    </ice:dataTable>

    <br/>

    <!--Buttons will be hidden or visible based on whether the table is in edit mode or display mode-->
    <div id="editElement" style="display:block;">
        <!--Put the table in edit mode by enabling the inputtext components-->
        <ice:commandButton value="Edit Element" partialSubmit="true"
                           onclick="toggleLayerOn('updateElement');toggleLayerOff('editElement');">
            <f:setPropertyActionListener value="#{false}" target="#{backingBean.elementsDisabled}"/>
        </ice:commandButton>
    </div>
    <div id="updateElement" style="display:none;">
        <!--Save the changes and return to display mode-->
        <ice:commandButton action="#{backingBean.updateElementValues}" value="Update Element Values"
                           partialSubmit="true"
                           onclick="toggleLayerOn('editElement');toggleLayerOff('updateElement');"/>
        <!--Cancel the changes and return to display mode-->
        <ice:commandButton value="Cancel Changes" partialSubmit="true"
                           onclick="toggleLayerOn('editElement');toggleLayerOff('updateElement');">
            <f:setPropertyActionListener value="#{true}" target="#{backingBean.elementsDisabled}"/>
        </ice:commandButton>
    </div>

</jsp:root>

The backing bean. Please note the upateElementValues() method. This gets the editableDataTable from the FacesContext, casts it to an HtmlDataTable, loops over the rows of this datatable, and casts each row to an Element. These Elements contain the updated values entered by the user. You must then load the original Elements via Id and make the necessary changes before persisting the updates back to the database. Make sure to set your datatable rowIndex back to -1 (see code) or there will be JSF errors.

import com.icesoft.faces.component.ext.HtmlDataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import java.util.*;

public class BackingBean {

    public static final Logger log = LoggerFactory.getLogger(BackingBean.class);

    private ElementDao elementDao;
    private boolean elementsDisabled = true;
    private List<Element> elements = new ArrayList<Element>();

    public BackingBean() {
        >//get all the elements from the database
        elements = elementDao.getAllElements();
    }

    public void setElementDao(ElementDao elementDao) {
        this.elementDao = elementDao;
    }

    public void updateElementValues() {
        >//get the datatable as a UI component
        UIComponent comp = FacesContext.getCurrentInstance().getViewRoot().findComponent("editableDataTable");

        if (comp != null) {
            UIData uIData = (UIData) comp;
            HtmlDataTable myTable = (HtmlDataTable) uIData;

            for (int i = 0; i < myTable.getRowCount(); i++) {
                >//loop over the rows
                myTable.setRowIndex(i);
                >//get the values that the user edited for this row
                Element modifiedElement = (Element) myTable.getRowData();
                >//print the values to verify they are correct
                log.info("Value 1 " + modifiedElement.getValue1());
                log.info("Value 2 " + modifiedElement.getValue2());

                >//load the element from the database
                Element originalElement = elementDao.load(modifiedElement.getId());
                originalElement.setValue1(modifiedElement.getValue1());
                originalElement.setValue2(modifiedElement.getValue2());
                >//update the values in the database for the given element
                elementDao.update(originalElement);

            }
            >//make sure to set the row Index back to -1!!!
            myTable.setRowIndex(-1);
        }
        >//disable the inputtext components, they should only be enabled during "edit mode"
        setElementsDisabled(true);
    }

    public boolean isElementsDisabled() {
        return elementsDisabled;
    }

    public void setElementsDisabled(boolean elementsDisabled) {
        this.elementsDisabled = elementsDisabled;
    }

    public List<Element> getElements() {
        return elements;
    }

    public void setElements(List<Element> elements) {
        this.elements = elements;
    }
}

The object:

import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Column;

public class Element {

    @Id
    @GeneratedValue(generator = "hibernate-uuid")
    private String id;

    @Column(nullable = false)
    private String value1;

    @Column(nullable = false)
    private String value2;

    public Element(String value1, String value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getValue1() {
        return value1;
    }

    public void setValue1(String value1) {
        this.value1 = value1;
    }

    public String getValue2() {
        return value2;
    }

    public void setValue2(String value2) {
        this.value2 = value2;
    }
}

Here's a quick and easy way to dynamically add JSF components to a page. You'll need a jsp, a backing bean, and a jsf component library. On the jsp, you will need a button and "container component" (I used a PanelGrid) with a binding to a backing bean. The button will call a method on the backing bean. The method will add child UI components to the bound container component.

1. The jsp. Notice the container component (PanelGrid) has a binding to the backing bean. The button calls the "addComponents" method on the backing bean.

<html xmlns:jsp="http://java.sun.com/JSP/Page"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:c="http://java.sun.com/jstl/core"
      xmlns:ice="http://www.icesoft.com/icefaces/component"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns="http://www.w3.org/1999/xhtml">
<jsp:directive.page contentType="text/html"/>

<ui:composition>


    <ice:panelGrid binding="#{backingBean.containerComponent}"/>

    <br/>

    <ice:commandButton value="Add UI Components" action="#{backingBean.addComponents}" partialSubmit="true"/>

</ui:composition>
</html>

2. The backing bean. The addComponents method makes a call to a database to determine what/how many fields need to be added to the container component.

import com.icesoft.faces.component.ext.HtmlPanelGrid;
import com.icesoft.faces.component.ext.UIColumn;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlInputText;

public class BackingBean {

    private HtmlPanelGrid containerComponent;

    public void addComponent() {
        //clean previous component
        containerComponent.getChildren().clear();

        List<Node> nodes = nodeDao.getAllNodes();

        //dynamically add Child Components to Container Component
        for (Node node : nodes) {
            UIColumn col = new UIColumn();
            HtmlOutputText ot = new HtmlOutputText();
            ot.setValue(node.getLabel() + ": ");
            col.getChildren().add(ot);
            HtmlInputText it = new HtmlInputText();
            it.setValue("");
            it.setId(node.getLabel());
            col.getChildren().add(it);

            if (containerComponent == null) {
                containerComponent = new HtmlPanelGrid();
            }
            containerComponent.getChildren().add(col);
        }

    }

    public HtmlPanelGrid getContainerComponent() {
        return containerComponent;
    }

    public void setContainerComponent(HtmlPanelGrid containerComponent) {
        this.containerComponent = containerComponent;
    }
}

That's it!

Another JSF project I've been working on required another dynamic JSF tree. However, this time the component library being used was IceFaces. If you recall, the last time I used RichFaces. I have to say that using IceFaces made this task MUCH easier.

The basic setup:

  • A "tree" structure that is made up of "node" objects. Each node has a parent node as well as a list of child nodes. Root nodes have a null parent. The tree object takes a list of root nodes. (see code below)
  • A JSF Tree. IceFaces was used this time. (see code below)
  • A JSF managed backing bean with ActionListeners and DAO access. ActionListeners are used for the CRUD operations on nodes. DAO access is used for directly updating the objects in the database. (see code below)
  • A great place to start is with one of IceFaces tree examples. I used this one: IceFaces Sample Tree Application

All of this sounds very familiar, right?

Here's where it starts to get different.

The Tree UI:

<ice:panelGroup style="border: 1px solid gray;">
                <ice:tree id="tree"
                          value="#{tree.model}"
                          var="item"
                          hideRootNode="false"
                          hideNavigation="false"
                        >
                    <ice:treeNode>
                        <f:facet name="content">
                            <ice:panelGroup style="display: inline">
                                <ice:commandLink
                                        actionListener="#{item.userObject.nodeClicked}"
                                        value="#{item.userObject.label}"/>
                            </ice:panelGroup>
                        </f:facet>
                    </ice:treeNode>
                </ice:tree>
            </ice:panelGroup>

Note that "tree.model" is passed in. Also note that there is a commandLink with actionListener. This sets the selected node id on the backing bean. Both of these things can be seen in the IceFaces sample tree application referenced above.

What you'll need to do to make this truly dynamic is add some controls to your tree display page and some backing bean methods. I'll use adding a node as an example.

Add the code below to the page that displays the tree. newNodeName is a field on the backing bean. addChildToSelectedNode is the method on the backing bean that takes "newNodeName", creates a node, and persists it to the database.

<div id="addNode">
    <table width="100%">
        <tr>
            <td><ice:outputText value="Name:"/></td>
            <td><ice:inputText value="#{nodeManagement.newNodeName}"/></td>
        </tr>
        <tr>
            <td>
                <ice:commandButton 
                                   value="Add Child to Selected Node"
                                   action="#{nodeManagement.addChildToSelectedNode}"
                                   partialSubmit="true"/>
            </td>
        </tr>
    </table>
</div>

<ice:outputText
        value="Selected Node: #{tree.selectedNodeObject.label}"
        escape="false" style="font-weight:bold;"/>

The method that add a node to the tree is shown below. Note the last line (tree.buildTreeModel()). This rebuilds the tree model that used to display the tree. If this method is not implemented on the Tree bean, you will have to refresh the page manually to see the node that was just created.

    public void addNodeToSelectedNode() {
        //you'll probably want to handle errors here
        //selectedNodeId can't be blank or null
        //newNodeName shouldn't be blank or null

        Node newNode = new Node();
        
        //load the selectedNode using the selectedNodeId
        Node selectedNode = nodeDao.load(selectedNodeId);
        
        //get the selected node's Set of children
        Set<Node> childrenOfParent = selectedNode.getChildren();

        //create node to be added
        newNode.setChildren(null);
        newNode.setLabel(newNodeName);
        newNode.setParent(selectedNode);

        //add new node to selectedNode
        childrenOfParent.add(newNode);

        //saving selected node saves selectedNode as well as newNode
        nodeDao.save(selectedNode);

        //rebuild tree
        tree.buildTreeModel();
    }

The node: (more of the same from last time)

import javax.persistence.*;
import java.util.List;
import org.hibernate.annotations.GenericGenerator;

@Entity
@GenericGenerator(
        name = "hibernate-uuid", strategy = "uuid"
)
public class Node {
    @Id
    @GeneratedValue(generator = "hibernate-uuid")
    private String id;

    @Column(nullable = false)
    private String label;

    @OneToMany(mappedBy = "parent", cascade = {CascadeType.ALL})
    private List children;

    @ManyToOne
    @JoinColumn(name = "fk_parent_id")
    private Node parent;

   // Getters and Setters...
}

I think is a much more straight forward way of creating a dynamic JSF tree. Using the IceFaces Sample Application is a good starting point. Adding the few snippets of code I've provided above should get you the rest of the way.