class HibernateMenuDAO extends HibernatePersistentObjectDAO<Menu> implements MenuDAO {

	@Override
	@SuppressWarnings("rawtypes")
	public List<Menu> findByUserId(long userId) {
		List<Menu> coll = new ArrayList<Menu>();

		try {
			User user = userDAO.findById(userId);
			if (user == null)
				return coll;

			// The administrators can see all menus
			if (user.isMemberOf("admin"))
				return findAll();

			Set<Group> precoll = user.getGroups();
			Iterator iter = precoll.iterator();
			if (!precoll.isEmpty()) {
				// First of all collect all menus that define it's own policies
				StringBuffer query = new StringBuffer("select distinct(_menu) from Menu _menu  ");
				query.append(" left join _menu.menuGroups as _group ");
				query.append(" where _group.groupId in (");

				boolean first = true;
				while (iter.hasNext()) {
					if (!first)
						query.append(",");
					Group ug = (Group) iter.next();
					query.append(Long.toString(ug.getId()));
					first = false;
				}
				query.append(")");
				coll = (List<Menu>) findByQuery(query.toString(), null, null);

				// Now collect all menus that references the policies of the
				// previously found menus
				List<Menu> tmp = new ArrayList<Menu>();
				query = new StringBuffer("select _menu from Menu _menu  where _menu.securityRef in (");
				first = true;
				for (Menu menu : coll) {
					if (!first)
						query.append(",");
					query.append(Long.toString(menu.getId()));
					first = false;
				}
				query.append(")");
				tmp = (List<Menu>) findByQuery(query.toString(), null, null);

				for (Menu menu : tmp) {
					if (!coll.contains(menu))
						coll.add(menu);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		Collections.sort(coll);
		return coll;
	}

	protected  HibernateMenuDAO();

}