Monday, 9 February 2015

Recursive Left Menu - How to generate a left menu recursively

How to build a left menu recursively? This post is about how we can generate a left menu recursively from the database entries. The left menu can contain sub menus and further menu items. This post shows a simple way of constructing a left menu in java. The environment used are Java and HSQLDB.

Create a table with following entries:
CREATE TABLE MENU (ID INTEGER, NAME VARCHAR(100), PARENT INTEGER);
INSERT INTO MENU VALUES(2,'COMPUTER',NULL);
INSERT INTO MENU VALUES(3,'PRINTER',NULL);
INSERT INTO MENU VALUES(4,'NOTEBOOK',2);
INSERT INTO MENU VALUES(5,'DESKTOP',2);
INSERT INTO MENU VALUES(6,'DELL',4);
INSERT INTO MENU VALUES(7,'LENOVA',4);
INSERT INTO MENU VALUES(8,'CANON',3);
INSERT INTO MENU VALUES(9,'HP',3);
INSERT INTO MENU VALUES(10,'SERVER',2);
INSERT INTO MENU VALUES(11,'DELL',10);
INSERT INTO MENU VALUES(12,'POWEREDGE',11);

Following class reads the above data from database and outputs left menu data in JSON format:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gson.Gson;

public class RecurseMenu {
 private static final String DRIVER = "org.hsqldb.jdbcDriver";
 private static final String URL = 
 "jdbc:hsqldb:file:D:/hsqldb/data/hsqldb/cameldb;shutdown=true";
  
 
 public void process() {

  try {
  
   Connection conn = 
   DriverManager.getConnection(URL, "camel", "camel");

   Statement stmt = conn.createStatement();
   
   List<Item> data = new ArrayList<Item>();

   String qry = getSQL();

   ResultSet rs = stmt.executeQuery(qry);

   while (rs.next()) {

    Integer id = rs.getInt("ID");
    Integer parent = rs.getInt("PARENT");
    String title = rs.getString("TITLE");

    Item item = new Item();
    item.setId(id);
    item.setParent(parent);
    item.setTitle(title);

    data.add(item);
    
   }

   List tempList = new  ArrayList (); 

   recurseChildren( data, tempList, null);
   data.removeAll(tempList);

   Gson gson = new Gson();
   String json = gson.toJson(data);
   
   System.out.println(json);
   
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 public void recurseChildren( List<Item> items, List tempList, Item newItem) {
 
 for (Item item : items) {
    if (newItem != null){
    if(newItem.getParent() == item.getId()) {
     item.getChildren().add(newItem);
     item.setFolder(true);
     tempList.add(newItem);
     
     break;
    }else continue; 
   }
    
   if(newItem == null )
      recurseChildren( items,  tempList, item);
 
  }
 }
 
 private String getSQL() {
  StringBuffer sb = new StringBuffer();

  sb.append(" SELECT  ID, Parent, Name AS Title ");
  sb.append(" FROM Menu ");
  sb.append(" ORDER BY ID ASC ");

  return sb.toString();

 }
 
 
 public static void main(String[] args) {
  RecurseMenu obj = new RecurseMenu();
  obj.process();

 }

}



The Item bean:

import java.util.*;

 public class Item {
  private int id;
  private boolean folder;
  private int parent;
  private String title;
  private Set<Item> children = new HashSet<Item>();
  
  
  public Set<Item> getChildren() {
   return children;
  }

  public boolean getFolder(){
   return folder;
  }
  
  public void setFolder(boolean folder){
   this.folder = folder;
  }
  
  public String getTitle(){
   return title;
  }
  
  public void setTitle(String title){
   this.title = title;
  }
  
  public int getId() {
   return id;
  }

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

  public int getParent() {
   return parent;
  }

  public void setParent(int parent) {
   this.parent = parent;
  }

 }


The JSON output will be as follows:

[{"id":2,"folder":true,"parent":0,"title":"COMPUTER","children":[{"id":5,"folder":false,"parent":2,"title":"DESKTOP","children":[]},{"id":4,"folder":true,"parent":2,"title":"NOTEBOOK","children":[{"id":6,"folder":false,"parent":4,"title":"DELL","children":[]},{"id":7,"folder":false,"parent":4,"title":"LENOVA","children":[]}]},{"id":10,"folder":true,"parent":2,"title":"SERVER","children":[{"id":11,"folder":true,"parent":10,"title":"HP","children":[{"id":12,"folder":false,"parent":11,"title":"POWEREDGE","children":[]}]}]}]},{"id":3,"folder":true,"parent":0,"title":"PRINTER","children":[{"id":8,"folder":false,"parent":3,"title":"CANON","children":[]},{"id":9,"folder":false,"parent":3,"title":"HP","children":[]}]}]

No comments:

Post a Comment