4 Replies Latest reply on Jul 23, 2010 6:09 AM by Ilya Shaikovsky

    How to create RIchfaces Menu dynamically from database?

    Siva P Master

      Hi All,

       

      I have to create Menus from database(dynamically).For horizontal menu i am able to create using rich:toolbar.But Vertical menus how to create?If any one come out of the problem help me.From database i am able to read total menu size in menuInterface java file.my files are listed below.

       

      My jsp:

       

      <rich:dropDownMenu binding="#{loginBean.richMenu}">
      </rich:dropDownMenu>

       

      Login Bean:

       

      public class LoginBean {

       

      private static Log log = LogFactory.getLog(LoginBean.class);
      private ResourceBundle ppsResources = ResourceBundle.getBundle("ApplicationResources");

       

      private List<NavigationMenuItem> menu;
      //private HtmlToolBar richMenu;
      private HtmlDropDownMenu richMenu;
      private MenuInterface menuInterface;

       


      public LoginBean()
      {
      System.out.print("Calling Cons.............");
      menuInterface = new MenuInterface();
      }

       

      /* Getter Setter methods */

       

      public List<NavigationMenuItem> getMenu() {
      return menu;
      }

       

      public void setMenu(List<NavigationMenuItem> menu) {
      this.menu = menu;
      }

       

      public HtmlDropDownMenu getRichMenu() {
      return richMenu;
      }

       

      public void setRichMenu(HtmlDropDownMenu richMenu) {
      this.richMenu = richMenu;
      }

       

      }

       

      MenuInterface.Java:

       

      public class MenuInterface {

       

      private static Log log = LogFactory.getLog(MenuInterface.class);
      private List<NavigationMenuItem> menu;
      //private HtmlToolBar richToolbar;
      private HtmlDropDownMenu richToolbar;

       

      public MenuInterface() {

       

      }

       

      private List<NavigationMenuItem> generateMenu(int userSerial) {
      //List cache = ServiceDao.menuListExecute().fetchMenuByRole(userSerial);
      List cache = new ArrayList<String>();
      return engineMenu(cache);

       

      }

       

      private List<NavigationMenuItem> generateMenu() {
      List cache = ServiceDao.menuListExecute().fetchMenuSortData();
      return engineMenu(cache);
      }

       

      private HtmlDropDownMenu generateRichMenu() {
      List cache = ServiceDao.menuListExecute().findByExample();
      //List cache = ServiceDao.menuListExecute().fetchMenuSortData();
      return engineRichMenu(cache);
      }

       

      private HtmlDropDownMenu generateRichMenu(int userSerial) {
      //List cache = ServiceDao.menuListExecute().findByExample();
      //List cache = ServiceDao.menuListExecute().fetchMenuByRole(userSerial);
      List cache = ServiceDao.menuListExecute().findMenuByRoleExample(userSerial);
      //List cache = ServiceDao.menuListExecute().fetchMenuSortData();
      return engineRichMenu(cache);

       

      }

       

      private HtmlDropDownMenu engineRichMenu(List cache) {

       

      log.debug("engine Rich Menu starting...");
      //List<NavigationMenuItem> rootMenu = null;
      HtmlDropDownMenu toolbar = new HtmlDropDownMenu();
      int tabSpaces=0;

       


      NavigationMenuItem parentMenu;
      List<HtmlMenuItem> childMenu;

       

      log.info("Menu List Size = " + cache.size());
      //rootMenu = new ArrayList<NavigationMenuItem>();

       

      int i = 0;
      while(i<cache.size()){
      //while (cache.size() > 0) {
      //Menu menu = getDataMenu(cache, i);
      Menu menu = (Menu)cache.get(i);

       

      if ((menu.getParent() == 0) && !menu.getStatus().equals("ADDED")){
      log.debug("STATUS ==== "+menu.getStatus());
      HtmlDropDownMenu rootMenu = new HtmlDropDownMenu();
      rootMenu.setValue(menu.getLabel());
      rootMenu.setLabelClass("celcomMenuLabel");
      rootMenu.setStyleClass("celcomMenuLabel");

       

      log.debug("Root Menu === " + menu.getSerial() + "|"
      + menu.getDescription() + "|" + menu.getParent());

       

      //parentMenu = menuInfo(menu);
      //rootMenu.add(parentMenu);
      menu.setStatus("ADDED");
      cache.set(i,menu);
      //cache.remove(i);
      //i--;
      log.debug("Menu List Size after remove = " + cache.size());
      Integer ii = new Integer(i);
      childMenu = recursiveChildRichMenu(tabSpaces+10,ii,cache, menu.getSerial());
      rootMenu.getChildren().addAll(childMenu);
      //parentMenu.setNavigationMenuItems((List<HtmlMenuItem>) childMenu);
      toolbar.getChildren().add(rootMenu);

       

      } else {
      log.debug("Not Root Menu..."+menu.getLabel());
      log.debug("STATUS ==== "+menu.getStatus());

       

      }

       

      i++;
      //      if (i >= cache.size())
      //      i = 0;
      }
      log.debug("engine Menu end...");
      return toolbar;
      }

       

      private List<HtmlMenuItem> recursiveChildRichMenu(int tabSpaces, Integer upperI, List recursiveData,
      int parentID) {

       

      int beforeI;
      List parentMenuList = null;

       

      parentMenuList = new ArrayList();

       

      log.debug(whiteSpace(tabSpaces)+"["+ parentID +"]"+ "<--- Parent ID ************************************************ [ START ]");
      HtmlMenuItem parentMenu = null;
      HtmlMenuGroup parentGroupMenu = null;
      List<HtmlMenuItem> childMenu;
      int i = 0;

       

      while (i < recursiveData.size()) {
      //Menu menu = getDataMenu(recursiveData, i);
      Menu menu = (Menu)recursiveData.get(i);
      if ((menu.getParent() == parentID) && !menu.getStatus().equals("ADDED")) {

       

      log.debug("STATUS ==== "+menu.getStatus());
      log.debug(whiteSpace(tabSpaces)+"Child Menu Found [" + i + "] === " + menu.getSerial() + "|"
      + menu.getDescription() + "|" + menu.getParent());

       

      parentMenu = richMenuInfo(menu);
      HtmlActionParameter menuItemParam = new HtmlActionParameter();
      menuItemParam.setId("includePage"+Integer.toString(menu.getSerial()));
      menuItemParam.setName("includePage");
      menuItemParam.setValue(menu.getAction());
      parentMenu.getChildren().add(menuItemParam);
      parentMenu.setReRender("contentPage");

       

      parentGroupMenu = richMenuGroupInfo(menu);

       

      //recursiveData.remove(i);

       

      menu.setStatus("ADDED");
      recursiveData.set(i, menu);
      //log.debug(whiteSpace(tabSpaces)+"Menu List Size after remove = "+ recursiveData.size());
      log.debug(whiteSpace(tabSpaces)+"upperI ======= "+upperI +" current i ===="+i);

       


      //i--;
      beforeI = i;
      log.debug(whiteSpace(tabSpaces)+"before i ======= "+i);
      childMenu = recursiveChildRichMenu(tabSpaces+10,i,recursiveData, menu.getSerial());

       

      log.debug(whiteSpace(tabSpaces)+"after i ======= "+i);
      if(childMenu.size()>0){
      //log.debug(whiteSpace(tabSpaces)+"Child Found = "+childMenu.size());
      parentMenuList.add(parentGroupMenu);
      parentGroupMenu.getChildren().addAll(childMenu);
      parentMenu = null;
      }else{
      //log.debug(whiteSpace(tabSpaces)+"No Child Found... ");
      Class[] params = {};

       

      FacesContext ctx = FacesContext.getCurrentInstance();
      Application app = ctx.getApplication();
      MethodExpression actionExpression = app.getExpressionFactory().createMethodExpression(ctx.getELContext(),"#{menuActionBean.actionInclude}",String.class, params);
      parentMenu.setActionExpression(actionExpression);

       

      parentMenuList.add(parentMenu);
      parentGroupMenu = null;
      }

       

       

       

      } else {
      log.debug("STATUS ==== "+menu.getStatus());
      log.debug(whiteSpace(tabSpaces)+"Not It Child [" + i + "] === " + menu.getSerial() + "|"
      + menu.getDescription() + "|" + menu.getParent());
      }
      i++;
      }
      log.debug(whiteSpace(tabSpaces)+"["+ parentID +"]"+ "<--- Parent ID ************************************************ [ END ]");
      return parentMenuList;
      }

       

      private HtmlMenuItem richMenuInfo(Menu menu) {

       

      HtmlMenuItem htmlMenuItem = new HtmlMenuItem();
      //htmlMenuItem.setAction(menu.getAction());
      htmlMenuItem.setValue(menu.getLabel());
      htmlMenuItem.setSubmitMode("ajax");
      htmlMenuItem.setRendered(true);
      htmlMenuItem.setAjaxSingle(true);
      htmlMenuItem.setLabelClass("celcomMenuLabel");
      htmlMenuItem.setStyleClass("celcomMenuLabel");
      //htmlMenuItem.setOnclick(_onclick)
      //htmlMenuItem.setId(Integer.toString(menu.getSerial()));

       

      //menuItem.setAction(menu.getAction());
      //menuItem.setActionListener(menu.getActionListerner());
      //menuItem.setLabel(menu.getLabel());
      //menuItem.setDescription(menu.getDescription());
      // menuItem.setExternalLink();
      //menuItem.setActive(true);
      //menuItem.setOpen(true);
      //menuItem.setTarget(menu.getTarget());

       

      return htmlMenuItem;
      }

       

      private HtmlMenuGroup richMenuGroupInfo(Menu menu) {

       

      HtmlMenuGroup htmlMenuGroup = new HtmlMenuGroup();
      //htmlMenuItem.setAction(menu.getAction());
      htmlMenuGroup.setValue(menu.getLabel());
      htmlMenuGroup.setLabelClass("celcomMenuLabel");
      htmlMenuGroup.setStyleClass("celcomMenuLabel");
      //htmlMenuGroup.setId(Integer.toString(menu.getSerial()));
      //menuItem.setAction(menu.getAction());
      //menuItem.setActionListener(menu.getActionListerner());
      //menuItem.setLabel(menu.getLabel());
      //menuItem.setDescription(menu.getDescription());
      // menuItem.setExternalLink();
      //menuItem.setActive(true);
      //menuItem.setOpen(true);
      //menuItem.setTarget(menu.getTarget());

       

      return htmlMenuGroup;
      }

       


      private String whiteSpace(int count){
      String spacing="";
      for(int i=0;i<count;i++){
      if(i==count-10)
      spacing = spacing + "|";
      else
      spacing = spacing + " ";
      }
      return spacing;
      }
      }

       

      My MenuDao:

       

      public List findMenuByRoleExample(int userSerial) {
      log.debug("finding Menu instance by example");
      List results=null;
      List menu = new ArrayList();
      try {

       

      /*results = getSession().createCriteria(UserProfile.class)
      .add(Restrictions.eq("serial", userSerial))
      .list();

       

      UserProfile userProfile = (UserProfile)results.get(0);
      log.debug("userProfile.getUserRole().getId() = " + userProfile.getUserRole().getId());*/
      results = getSession().createCriteria(Menu.class)    
      .addOrder(Order.asc("parent"))
      .addOrder(Order.asc("sequence"))
      //.createCriteria("menuRoleAccesses")
      //.add(Restrictions.eq("userRole.id", ))
      .list();

       

      log.debug("find by example successful, result size: " + results.size());

       


      return results;
      } catch (RuntimeException re) {
      log.error("find by example failed", re);
      throw re;
      }finally{
      getCloseSession();
      }
      //return results;
      }

       

       

       

      In Jsp page it is displaying empty.Nothing it is diaplaying.Any one help me about this problem.

       

      This code is working for me but i have to hit the db 11 times if i have 11 Root menus.Below is hard coded values.

       

      HtmlDropDownMenu toolbar = new HtmlDropDownMenu();
      HtmlDropDownMenu rootMenu = new HtmlDropDownMenu();
      List<HtmlMenuItem> childMenu;
      int tabSpaces=0;
      toolbar.setValue("Home"); 
      toolbar.setLabelClass("celcomMenuLabel");
      toolbar.setStyleClass("celcomMenuLabel");
      toolbar.setValue("New Registration"); 
      toolbar.setLabelClass("celcomMenuLabel");
      toolbar.setStyleClass("celcomMenuLabel");
      HtmlMenuGroup htmlMenuGroup = new HtmlMenuGroup();
      //htmlMenuItem.setAction(menu.getAction());
      htmlMenuGroup.setValue("Home1");
      htmlMenuGroup.setLabelClass("celcomMenuLabel");
      htmlMenuGroup.setStyleClass("celcomMenuLabel");
      //htmlMenuGroup.getChildren().addAll(c);
      HtmlMenuItem htmlMenu1 = new HtmlMenuItem();
      htmlMenu1.setLabelClass("celcomMenuLabel");
      htmlMenu1.setStyleClass("celcomMenuLabel");
      htmlMenu1.setValue("SubItem1");
      HtmlMenuItem htmlMenu2 = new HtmlMenuItem();
      htmlMenu2.setLabelClass("celcomMenuLabel");
      htmlMenu2.setStyleClass("celcomMenuLabel");
      htmlMenu2.setValue("SubItem2");
      HtmlMenuItem htmlMenu3 = new HtmlMenuItem();
      htmlMenu3.setLabelClass("celcomMenuLabel");
      htmlMenu3.setStyleClass("celcomMenuLabel");
      htmlMenu3.setValue("SubItem3");
      HtmlMenuItem htmlMenu4 = new HtmlMenuItem();
      htmlMenu4.setLabelClass("celcomMenuLabel");
      htmlMenu4.setStyleClass("celcomMenuLabel");
      htmlMenu4.setValue("SubItem4");
      List<HtmlMenuItem> cachenew = new ArrayList<HtmlMenuItem>();
      cachenew.add(htmlMenu1);
      cachenew.add(htmlMenu2);
      cachenew.add(htmlMenu3);
      cachenew.add(htmlMenu4);
      htmlMenuGroup.getChildren().addAll(cachenew);
      toolbar.getChildren().add(htmlMenuGroup);
      HtmlMenuGroup htmlMenuGroup1 = new HtmlMenuGroup();
      //htmlMenuItem.setAction(menu.getAction());
      htmlMenuGroup1.setValue("Home2");
      htmlMenuGroup1.setLabelClass("celcomMenuLabel");
      htmlMenuGroup1.setStyleClass("celcomMenuLabel");
      //htmlMenuGroup.getChildren().addAll(c);
      HtmlMenuItem htmlMenu11 = new HtmlMenuItem();
      htmlMenu11.setLabelClass("celcomMenuLabel");
      htmlMenu11.setStyleClass("celcomMenuLabel");
      htmlMenu11.setValue("SubItem111");
      HtmlMenuItem htmlMenu22 = new HtmlMenuItem();
      htmlMenu22.setLabelClass("celcomMenuLabel");
      htmlMenu22.setStyleClass("celcomMenuLabel");
      htmlMenu22.setValue("SubItem222");
      List<HtmlMenuItem> cachenew1 = new ArrayList<HtmlMenuItem>();
      cachenew1.add(htmlMenu11);
      cachenew1.add(htmlMenu22);
      htmlMenuGroup1.getChildren().addAll(cachenew1);
      toolbar.getChildren().add(htmlMenuGroup1);
      public String systemGatewayLogin() {
      System.out.println("Loading systemGatewayLogin.....");
      log.debug("Entering into systemGatewayLogin....");
      setRichMenu(menuInterface.getRichMenu(2));
      log.debug("ChildCount:"+getRichMenu().getChildCount());
      //setInteractionType(menuInterface.getInteractionType());
      AppSession.CreateNewSession();
      AppSession.AppTimeOut();
      AppSession.AppSessionSetAttribute("username","siva");
      //AppSession.AppSessionSetAttribute("fullname",login.getUserProfile().getFullname());
      AppSession.AppSessionSetAttribute("userserial","0");
      return "success";
      }
        • 1. Re: How to create RIchfaces Menu dynamically from database?
          Ilya Shaikovsky Master

          In the first snippets - I do not see where the richMenu property initialized. Because the constructor of loginBean contains only new menuInterface and that constructor is empty.

           

          This code is working for me but i have to hit the db 11 times if i have 11 Root menus.Below is hard coded values.

           

          If you will add initialization logic to getter - such numerous calls - expected behavior. JSF called properties accessors many times during lifecycle. So them should be initialized out of the getters and then just returned on calling.

          • 2. Re: How to create RIchfaces Menu dynamically from database?
            Siva P Master

            Thank you very much for ur reply.

             

            I forgot to add code.When i click Login button there i am doing setter for menu.Which is in bold.here 2 is some UserRole id.(user restrictions.)

             

             

            public String systemGatewayLogin() {
            System.out.println("Loading systemGatewayLogin.....");
            log.debug("Entering into systemGatewayLogin....");
            setRichMenu(menuInterface.getRichMenu(2));
            log.debug("ChildCount:"+getRichMenu().getChildCount());
            //setInteractionType(menuInterface.getInteractionType());
            AppSession.CreateNewSession();
            AppSession.AppTimeOut();
            AppSession.AppSessionSetAttribute("username","siva");
            //AppSession.AppSessionSetAttribute("fullname",login.getUserProfile().getFullname());
            AppSession.AppSessionSetAttribute("userserial","0");
            return "success";
            }
            • 3. Re: How to create RIchfaces Menu dynamically from database?
              Ilya Shaikovsky Master

              So you see in debug that after setting - the Menu object containsproper component object with items child? Is the log.debug returns correct child number?

               

              Check then also what getRichMenu reutrns then at render responce phase.

              • 4. Re: How to create RIchfaces Menu dynamically from database?
                Ilya Shaikovsky Master

                doh.. sorry.. read about "empty" and not checked the picture where seen that it's actually constructed.. Does the problenm that labels for items not set? So check your construction code where it get them and setting to items.