MenuBar from DataBase a contribution to improve

First thank you for the excellent support vaddin received Vaadin-pro and the starter kit order the t-shirt I really liked

Let me share with you how to create a MenuBar with command to create a new component from the database, and I hope you can help improve.

i just make some change on MenuBar Component

Fisrt i have this data model

grupos == group who owns the Users
grupos_menu == menu available to the group
menu_model == Setup menu

here is the java entity


@Entity
@Table(name = "grupos", schema = "public")
public class Grupos implements java.io.Serializable {

	private Integer idgrupo; //id
	private String nombre; //name of the group
        @OneToMany(fetch = FetchType.LAZY, mappedBy = "grupos")
	private Set<GruposMenu> gruposMenus = new HashSet<GruposMenu>(0);

getter and setters.....

@Entity
@Table(name = "grupos_menu", schema = "public")
public class GruposMenu implements java.io.Serializable {

        @EmbeddedId
	@AttributeOverrides({
			@AttributeOverride(name = "idgrupo", column = @Column(name = "idgrupo", nullable = false)),
			@AttributeOverride(name = "idmenu", column = @Column(name = "idmenu", nullable = false)) })
	private GruposMenuId id; 
        @ManyToOne(fetch = FetchType.LAZY)
	private Grupos grupos; 
	@ManyToOne(fetch = FetchType.EAGER)
        private MenuModel menuModel;
	private boolean activo; // decides if the menu is active for the group     


@Entity
@Table(name = "menu_model", schema = "public")
public class MenuModel implements java.io.Serializable {

        @Id
	private Integer idmenu;
	private String label;  // caption of menu to display
	private String classstring; //full class name of the Component to display ej  "com.sample.Component"
	private Integer parent; // the idmenu who is the parent
	private Integer indice;
	private Set<GruposMenu> gruposMenus = new HashSet<GruposMenu>(0);

now i add my model properties to the MenuItem and make a new constructor


  
		/**Data Base Params**/
		private Integer idmenu;
		private Integer idgrupo;
		private String label;
		private String classString;
		private Boolean activo;
		private Integer menuParent;

		/**
		 * Creado por Eneldo Serrata
		 * 
		 * @param caption
		 * @param icon
		 * @param command
		 * @param params
		 */
		public MenuItem(String caption, Resource icon, DbMenuBar.Command command, Object[] params) {
			if (caption == null) {
				throw new IllegalArgumentException("caption cannot be null");
			}
			itsId = ++numberOfItems;
			itsText = caption;
			itsIcon = icon;
			itsCommand = command;

			setIdmenu((Integer) params[0]
);
			setIdgrupo((Integer) params[1]
);
			setLabel((String) params[2]
);
			setClassString((String) params[3]
);
			setActivo((Boolean) params[4]
);
			setMenuParent((Integer) params[5]
);
		}

and new addItem Method to MenuItem to add a ready MenuItem from DB



public void addItem(MenuItem newItem) {
			if (isSeparator()) {
				throw new UnsupportedOperationException(
						"Cannot add items to a separator");
			}

			if (itsChildren == null) {
				itsChildren = new ArrayList<MenuItem>();
			}

			// The only place where the parent is set
			newItem.setParent(this);
			itsChildren.add(newItem);

			requestRepaint();
		}

now a create a new Command to create a Component from String and to a TabSheet


package com.marcos.ui.comp.menu;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import com.marcos.main.MarcosMain;
import com.marcos.ui.comp.menu.DbMenuBar.Command;
import com.marcos.ui.comp.menu.DbMenuBar.MenuItem;
import com.vaadin.terminal.Resource;
import com.vaadin.ui.Component;
import com.vaadin.ui.TabSheet;

/**
 * 
 * @author eneldoserrata 17/03/2011
 *
 */
public class MenuCommand implements Command {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private MarcosMain marcosMain; //Main Application
	private TabSheet mainTabSheet; //Container to new component 

	private final Map<String, Component> modulos = new HashMap<String, Component>();

	public MenuCommand(MarcosMain marcosMain) {
		this.marcosMain = marcosMain;
		mainTabSheet = marcosMain.getMainTabSheet();

	}


	/**
	 * 
	 * @param claseName coming from Data Base 
	 * @param moduleName caption for new tab
	 * @param icon
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	private void createModule(String claseName, String moduleName, Resource icon) 
	throws ClassNotFoundException, SecurityException, NoSuchMethodException, 
	IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
		if (modulos.get(moduleName)==null){

			Class clase = Class.forName(claseName.trim());
			Constructor<?> constructor = clase.getConstructor(MarcosMain.class);
			Component modulo = (Component) constructor.newInstance(marcosMain);

			modulos.put(moduleName, modulo);
			mainTabSheet.addTab(modulo, moduleName, icon, 0);
			mainTabSheet.getTab(modulo).setClosable(true);
			mainTabSheet.setSelectedTab(modulo);

		} else {
			mainTabSheet.addTab(modulos.get(moduleName), moduleName, icon, 0);
			mainTabSheet.getTab(modulos.get(moduleName)).setClosable(true);
			mainTabSheet.setSelectedTab(modulos.get(moduleName));
		}
	}


	@Override
	public void menuSelected(MenuItem selectedItem) {
		try{
			createModule(selectedItem.getClassString(), selectedItem.getLabel(), null);			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


now on MenuBar add two method. new addItem and other addChildrens


/**
	 * Creado por Eneldo Serrata
	 * 
	 * @param menuItem
	 * @return
	 */	
	public DbMenuBar.MenuItem addItem(MenuItem newItem) {

		menuItems.add(newItem);
		requestRepaint();

		return newItem;

	}

	/**
	 * Creadp por Eneldo Serrata
	 * @param fullMenu
	 * @param child
	 */
	public void addChildrens(Map<Integer, MenuItem> fullMenu, Map<Integer, MenuItem> childMenu){
		Iterator child = childMenu.entrySet().iterator();

		while (child.hasNext()) {
			Entry<Integer, MenuItem> childMap = (Entry<Integer, MenuItem>) child.next();
			Integer parentId = childMap.getValue().getMenuParent();

			MenuItem parent = fullMenu.get(parentId);
			parent.addItem(childMap.getValue());
		}	

	}

ok now we have the magic part create a new Constructor on MenuBar to pass the List and Command to generate the Menu


public DbMenuBar(List<GruposMenu> gruposMenus, Command command) {

		Map<Integer, MenuItem> fullmenu = new HashMap<Integer, MenuItem>(); // place all menu_model with id on key
		Map<Integer, MenuItem> childMenu = new HashMap<Integer, MenuItem>(); // place the child menu with id on key

		menuItems = new ArrayList<MenuItem>();
		setCollapse(true);
		setMoreMenuItem(null);

		// iterate on the list
		for (Iterator iterator = gruposMenus.iterator(); iterator.hasNext();) {
			GruposMenu gruposMenu = (GruposMenu) iterator.next();		

			//new MenuItem With DataBase Properties
			MenuItem menuItem = new MenuItem(gruposMenu.getMenuModel().getLabel(), null, 
					command,
					new Object[] {gruposMenu.getId().getIdmenu(),
				gruposMenu.getId().getIdgrupo(),
				gruposMenu.getMenuModel().getLabel(),
				gruposMenu.getMenuModel().getClassstring(),
				gruposMenu.getActivo(),
				gruposMenu.getMenuModel().getParent()});

			//adding all menu item to the fullmenu
			fullmenu.put(menuItem.getIdmenu(), menuItem);

			//filtering top menu and adding without command
			if (gruposMenu.getMenuModel().getParent()==0){	
				menuItem.setCommand(null);
				addItem(menuItem);

			} else {// fill childs menu
				childMenu.put(menuItem.getIdmenu(), menuItem);				
			}			

		}
		//
		addChildrens(fullmenu, childMenu);
	}

after all this you only need to
//call data from dababase
final List gruposMenus = getMarcosServices().getGenericDaoService().findAll(GruposMenu.class);
//add your new menu and new command
menuLayout.addComponent(new DbMenuBar(gruposMenus, new MenuCommand(this)));

I hope you like

if some body need my DbMenuBar let me know to send and

and sorry for my English is not very good I’m from Domincan Republic

Hola he visto tu post me gustaria que si esta en tus manos enviarme la base de datos, estoy empezando en vaadin y tengo muchas dudas, el codigo y las clases no te pido que me las envies porque seria demasiado, yo soy de Panama,

mi correo es rolando.quintero@provinfor.com

saludos

hey i need ur dbmenubar…plz will u send me…thanks its urgent