4 Replies Latest reply on Dec 20, 2009 8:58 AM by sdf1

    Dynamic <rich:tree> filled with data from database

      Hi,

      is it possible to fill the <rich:tree> with data from DataBase (MySQL) through "select" query in treeBean class?

      I started like this, but don't work:

      tree.xhtml

      ...
      <h:form>
       <rich:tree switchType="client" ajaxSubmitSelection="true"
       value="#{TreeViewBean.itemKatAll}" var="itemCat">
       <rich:treeNode>
       <h:outputText value="Categories" />
       </rich:treeNode>
       <rich:treeNode>
       <h:outputText value="#{itemCat.nameCategory}" />
       </rich:treeNode>
       </rich:tree>
      </h:form>
      ...
      


      treeBean.java
      ...
      public class TreeViewBean {
       Connection con;
       Statement ps;
       ResultSet rs;
       private List itemCatAll = new ArrayList();
       public List getItemCatAll() {
       int i = 0;
       try {
       Class.forName("com.mysql.jdbc.Driver");
       con = DriverManager.getConnection("jdbc:mysql://localhost:3306/portaldb","root","sa");
       ps = con.createStatement();
       rs = ps.executeQuery("select * from categories");
       while(rs.next()){
       System.out.println(rs.getString(1));
       itemCatAll.add(i,new itemCat(rs.getInt("ID_CATEGORY"),
       rs.getString("NAME_CATEGORY")));
       i++;
       }
       }catch (Exception e){
       System.out.println("Error Data : " + e.getMessage());}
       return itemCatAll;
       }
      
       public class itemCat {
       private int id;
       private String nameCategory;
       public itemKat(int id, String nameCategory) {
       this.id = id;
       this.nameCategory = nameCategory;
       }
       public int getId() {
       return id;
       }
       public void setId(int id) {
       this.id = id;
       }
       public String getNameCategory() {
       return nameCategory;
       }
       public void setNameCategory(String nameCategory) {
       this.nameCategory = nameCategory;
       }
       }
      }
      



      All the examples with the <rich:tree> component are with *.properties file. Is there a way to fill <rich:tree> with select query?

      Thanx in advance

        • 1. Re: Dynamic <rich:tree> filled with data from database
          nbelaevski

          Hi,

           

          Check rich:treeNodesAdaptor and rich:recursiveTreeNodesAdaptor.

          • 2. Re: Dynamic <rich:tree> filled with data from database

            First you have to get all the data from database and create a property file with node path and node name based on stucture you want to show like

            1        node1

            1.1     child1

            1.2     child2

             

            and then  call the addNode method by passing that propery and your tree should be binded with rootNode

             

             

             

            rootNode = new TreeNodeImpl();

            addNodes(

            null, rootNode, properties);

             

             

             

             

             

             

            private void addNodes(String path, TreeNode node, Properties properties) {

             

             

            boolean end = false;

             

             

            int counter = 1;

             

             

            while (!end) {

             

                 String key = path !=

            null ? path + '.' + counter : String

                 .valueOf(counter);

                 String value = properties.getProperty(key);

             

                 if (value != null) {

             

                      TreeNodeImpl nodeImpl =

            new TreeNodeImpl();

             

                      nodeImpl.setData(value);

                      node.addChild(

            new Integer(counter), nodeImpl);

             

                 }

             

             

             

             

            addNodes(key, nodeImpl, properties);

             

             

             

            counter++;

             

            }

             

             

             

             

             

            else {

             

            end =

            true;

             

            }

             

            }

             

             

             

            Check for the richfaces demo site ..there is really a very good example given to do this by property file

            • 3. Re: Dynamic <rich:tree> filled with data from database
              bolsover

              heavily edited code.... - my give some useful leads

               

               

              private HtmlTree buildProductTree() {
                      HtmlTree        tree   = new HtmlTree();
                    

                      ProductDao      dao    = new ProductDao(); // data access methods
                     
                      CustomerProduct rootCP = new CustomerProduct();

                      TreeNode parentNode = new TreeNodeImpl();

                      parentNode.setData(rootCP);
                          
                      List<Product>   productList = dao.retrieveProductsByParent("P", "Product"); // the initial list of products
                     
                      walkTree(parentNode, productList, dao);

                      tree.setValue(parentNode);
                      tree.setVar("item");

                      return tree;
                  }

                  private void walkTree(TreeNode parentNode, List<Product> productList, ProductDao dao) {
                      TreeNodeImpl    childNode;
                      CustomerProduct cp;

                      for (Product prod : productList) {
                          cp = new CustomerProduct();
                          cp.setProduct(prod);
                          cp.setLabel(prod.getDescription());
                          childNode = new TreeNodeImpl();
                          childNode.setData(cp);
                          parentNode.addChild("" + count++, childNode);

                          List<Product> childProducts = dao.retrieveProductsByParent("P", prod.getId()); // child items

                          walkTree(childNode, childProducts, dao); // recursive call
                      }
                  }

              • 4. Re: Dynamic <rich:tree> filled with data from database [SOLVED]

                Hi,

                 

                I almost forget to tell my solution to this problem.

                This is XHTML file with <rich:tree> component which dynamic create nodes:

                <ui:composition xmlns="http://www.w3.org/1999/xhtml"
                      xmlns:ui="http://java.sun.com/jsf/facelets"
                      xmlns:h="http://java.sun.com/jsf/html"
                      xmlns:f="http://java.sun.com/jsf/core"
                      xmlns:a4j="http://richfaces.org/a4j"
                      xmlns:rich="http://richfaces.org/rich">
                     <h:form>
                          <rich:panel style="width:200px">
                               <f:facet name="header">
                                    <h:outputText value="Simple Tree"/>
                               </f:facet>
                               <rich:tree value="#{SimpleTreeBean.root}" ajaxSubmitSelection="true"  switchType="client"
                               nodeSelectListener="#{SimpleTreeBean.selectionListener}" reRender="out"/>
                               <h:outputText value="#{SimpleTreeBean.key}" id="out" />
                          </rich:panel>
                     </h:form>
                </ui:composition>
                

                 

                This is the Bean class with the method that performs connect and download data from the database, then the fills nodes of TreeView:

                import org.richfaces.component.UITree;
                import org.richfaces.event.NodeSelectedEvent;
                import org.richfaces.model.TreeNode;
                import org.richfaces.model.TreeNodeImpl;
                
                import java.sql.Connection;
                import java.sql.DriverManager;
                import java.sql.ResultSet;
                import java.sql.Statement;
                
                import java.util.ArrayList;
                import java.util.Iterator;
                import java.util.List;
                
                public class SimpleTreeBean {
                     
                     Connection con;
                     Statement ps;
                     ResultSet rs;
                     public String key;
                     
                     private List itemCatAll = new ArrayList();
                     
                     @SuppressWarnings("unchecked")
                     private TreeNode root = null;
                
                     @SuppressWarnings({ "unchecked" })
                     private void addNodes(TreeNode root, List cat) {
                          int rId = 0;
                          String rValue = "Category";
                          TreeNodeImpl rootImpl = new TreeNodeImpl();
                          rootImpl.setData(rValue);
                          root.addChild(new Integer(rId), rootImpl);
                          Iterator iter = cat.iterator();
                          while(iter.hasNext()){
                               ItemCat item = (ItemCat)iter.next();
                               int id = item.getId();
                               String value =  item.getName();
                               TreeNodeImpl nodeImpl = new TreeNodeImpl();
                               nodeImpl.setData(value);
                               rootImpl.addChild(new Integer(id), nodeImpl);
                          }
                     }
                     
                     public void selectionListener(NodeSelectedEvent event) {
                          UITree tree = (UITree) event.getComponent();
                          String str1 = String.valueOf(tree.getRowKey());
                          String substr1 = str1.substring(2);
                          key = substr1;
                     }
                     
                     @SuppressWarnings("unchecked")
                     public List getItemCatAll() {
                          int i = 0;
                          try{  
                               Class.forName("com.mysql.jdbc.Driver");
                               con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","sa");
                               ps = con.createStatement();
                               rs = ps.executeQuery("select * from tree");
                               while(rs.next()){
                                    itemCatAll.add(i,new ItemCat(rs.getInt("ID"),rs.getString("NAME")));
                                    i++;
                               }
                          }catch (Exception e){
                               System.out.println("Error Data : " + e.getMessage());
                          }
                          return itemCatAll;
                     }
                     
                     @SuppressWarnings("unchecked")
                     public void initTree() {
                          List cat = getItemCatAll();
                          try {
                               root = new TreeNodeImpl();
                               addNodes(root, cat);
                          }catch (Exception e){
                               System.out.println("Error Data : " + e.getMessage());
                          }
                     }
                
                     @SuppressWarnings("unchecked")
                     public TreeNode getRoot() {
                          if (root == null) {
                               initTree();
                          }
                          return root;
                     }
                     
                     @SuppressWarnings("unchecked")
                     public void setRoot(TreeNode root) {
                          this.root = root;
                     }
                     
                     public String getKey() {
                          return key;
                     }
                
                     public void setKey(String key) {
                          this.key = key;
                     }
                
                     public class ItemCat {
                          private int id;
                          private String name;
                     
                          public ItemCat(int id, String name) {
                               this.id = id;
                               this.name = name;
                          }
                     
                          public int getId() {
                               return id;
                          }
                     
                          public void setId(int id) {
                               this.id = id;
                          }
                     
                          public String getName() {
                               return name;
                          }
                     
                          public void setName(String name) {
                               this.name = name;
                          }
                     }
                }
                

                 

                SQL queries to create and fill a database:

                 

                #
                # Database structure for database 'user'
                #
                CREATE DATABASE "user";
                USE "user";
                #
                # Table structure for table 'tree'
                #
                CREATE TABLE "tree" (
                  "id" int(11) default NULL,
                  "name" char(20) default NULL
                );
                #
                # Dumping data for table 'tree'
                #
                LOCK TABLES "tree" WRITE;
                INSERT INTO "tree" ("id", "name") VALUES (1,'Category1');
                INSERT INTO "tree" ("id", "name") VALUES (2,'Category2');
                INSERT INTO "tree" ("id", "name") VALUES (3,'Category3');
                INSERT INTO "tree" ("id", "name") VALUES (4,'Category4');
                
                UNLOCK TABLES;
                

                 

                Simple_tree.png