Thursday, February 21, 2013

ADF 11G : How to create Role Based Dynamic Menu using ADF?

ADF 11G : How to create Role Based Dynamic Menu using ADF?
ADF 11G : How to implement Security in ADF?

DB Table :

CREATE TABLE  "MENU"
   (    "ID" NUMBER(10,0) NOT NULL ENABLE,
        "NAME" VARCHAR2(30) NOT NULL ENABLE,
        "DISPLAY_SEQUENCE" NUMBER(2,0),
        "SHORTCUT" VARCHAR2(30),
        "ICON" VARCHAR2(60),
         CONSTRAINT "MEN_PK" PRIMARY KEY ("ID") ENABLE
   )


CREATE TABLE  "MENU_ITEMS" 
   (    "ID" NUMBER(10,0) NOT NULL ENABLE, 
        "NAME" VARCHAR2(30) NOT NULL ENABLE, 
        "SHORTCUT" VARCHAR2(30), 
        "DISPLAY_SEQUENCE" NUMBER(2,0), 
        "ACTION" VARCHAR2(60) NOT NULL ENABLE, 
        "MEN_ID" NUMBER(10,0) NOT NULL ENABLE, 
        "ICON" VARCHAR2(60), 
         CONSTRAINT "MIT_PK" PRIMARY KEY ("ID") ENABLE, 
         CONSTRAINT "MIT_MEN_FK" FOREIGN KEY ("MEN_ID")
          REFERENCES  "MENU" ("ID") ON DELETE CASCADE ENABLE
   )

CREATE TABLE  "ROLES" 
   (    "ID" NUMBER(10,0) NOT NULL ENABLE, 
        "NAME" VARCHAR2(30) NOT NULL ENABLE, 
         CONSTRAINT "ROL_PK" PRIMARY KEY ("ID") ENABLE
   )
 
 
 
 

CREATE TABLE  "ROLE_MENU_ITEMS" 
   (    "ROL_ID" NUMBER(10,0) NOT NULL ENABLE, 
        "MIT_ID" NUMBER(10,0) NOT NULL ENABLE, 
         CONSTRAINT "RMI_PK" PRIMARY KEY ("ROL_ID", "MIT_ID") ENABLE, 
         CONSTRAINT "RMI_MIT_FK" FOREIGN KEY ("MIT_ID")
          REFERENCES  "MENU_ITEMS" ("ID") ENABLE, 
         CONSTRAINT "RMI_ROL_FK" FOREIGN KEY ("ROL_ID")
          REFERENCES  "ROLES" ("ID") ON DELETE CASCADE ENABLE
   )
 
 
 
 
----------------------------------------------------------------------
ApplicationModule:
 
 
 fig: Application Module
 
  
 

public class MenuAMImpl extends ApplicationModuleImpl {
  /**
   * This is the default constructor (do not remove).
   */
  public MenuAMImpl() {
  }

  /**
   * Container's getter for MenuItemsView1.
   * @return MenuItemsView1
   */
  public ViewObjectImpl getMenuItemsView1() {
    return (ViewObjectImpl)findViewObject("MenuItemsView1");
  }

  /**
   * Container's getter for MenuItemsView2.
   * @return MenuItemsView2
   */
  public ViewObjectImpl getMenuItemsView2() {
    return (ViewObjectImpl)findViewObject("MenuItemsView2");
  }
 
  public static String getUserName(){

  return ADFContext.getCurrent().getSecurityContext().getUserName().toUpperCase();
  }
 
  public static boolean isUserInRole(String role){

  return ADFContext.getCurrent().getSecurityContext().isUserInRole(role);
  }
 
 
----------------------------------------------------------
MenuItems ViewObject
 
 
 
 
 fig: ViewObject
 
 
 


 

SELECT MenuItems.ID,
       MenuItems.NAME,
       MenuItems.SHORTCUT,
       MenuItems.DISPLAY_SEQUENCE,
       MenuItems.ACTION,
       MenuItems.MEN_ID,
       MenuItems.ICON,
       Menu.DISPLAY_SEQUENCE AS DISPLAY_SEQUENCE1,
       Menu.ICON AS ICON1,
       Menu.ID AS ID1,
       Menu.NAME AS NAME1,
       Menu.SHORTCUT AS SHORTCUT1,
       Roles.NAME AS NAME2,
       Roles.ID AS ID2,
       RoleMenuItems.MIT_ID,
       RoleMenuItems.ROL_ID,
       RoleMenuItems.STATUS,
       RoleMenuItems.EFF_DT,
       RoleMenuItems.EXP_DT
FROM MENU_ITEMS MenuItems, MENU Menu, ROLE_MENU_ITEMS RoleMenuItems, ROLES Roles
WHERE ((MenuItems.MEN_ID = Menu.ID) AND (MenuItems.ID = RoleMenuItems.MIT_ID)) AND (RoleMenuItems.ROL_ID = Roles.ID) AND (RoleMenuItems.STATUS = 'Active')
AND NVL(trunc(RoleMenuItems.EFF_DT),sysdate+1) <= trunc(SYSDATE)
AND NVL(trunc(RoleMenuItems.EXP_DT),sysdate+1) >= trunc(SYSDATE)
ORDER BY Menu.DISPLAY_SEQUENCE,MenuItems.DISPLAY_SEQUENCE
----------------------------------------------------------

Managed Bean





public class Menu {
   
  private RichMenuBar initMenu;
  public String loggedInUserName;
  public String loggedInbranchId;

  public void createMenus(PhaseEvent phaseEvent) {

      String MenuAMDef = null;
      String MenuAMConfig =null;
      ApplicationModule MenuAM = null;
     
    try {
      updateSession();
      // check the menu is already added
      boolean addMenu = true;
      for (Iterator iterator = initMenu.getChildren().iterator();
           iterator.hasNext(); ) {
        UIComponent component = (UIComponent)iterator.next();
        if (component.getId().startsWith("menuId")) {
          addMenu = false;
        }
      }
      if (addMenu) {

        // get roles
        String[] roles =
          ADFContext.getCurrent().getSecurityContext().getUserRoles();

        // get application module
//        MenuAMImpl menuAM = getAm();
        MenuAMDef = "com.operations.model.security.am.MenuAM";
        MenuAMConfig = "MenuAMLocal";
        MenuAM = Configuration.createRootApplicationModule(MenuAMDef,MenuAMConfig);
        ViewObject menuView = null;
                                                        
        menuView = MenuAM.findViewObject("MenuItemsView1");
//        MenuItemsViewImpl menuView =
//          (MenuItemsViewImpl)menuAM.getMenuItemsView1();
        menuView.executeQuery();
        while (menuView.hasNext()) {
          MenuItemsViewRowImpl menuItem =
            (MenuItemsViewRowImpl)menuView.next();

          // check if the user has this role
          boolean roleFound = false;
          for (int i = 0; i < roles.length; i++) {
            if (roles[i].equalsIgnoreCase(menuItem.getRoleName())) {
              roleFound = true;
            }
          }

          if (roleFound) {
            Boolean menuFound = false;
            RichMenu menu = new RichMenu();
            String menuId = "menuId" + menuItem.getMenuId().toString();

            // check if the main menu is already added
            for (Iterator iterator = initMenu.getChildren().iterator();
                 iterator.hasNext(); ) {
              UIComponent component = (UIComponent)iterator.next();
              if (component.getId().equalsIgnoreCase(menuId)) {
                menuFound = true;
                menu = (RichMenu)component;
              }
            }
            if (!menuFound) {
              // new main menu
              RichMenu newMenu = new RichMenu();
              newMenu.setId(menuId);
              newMenu.setText(menuItem.getMenuName());
              newMenu.setIcon(menuItem.getMenuIcon());
              initMenu.getChildren().add(newMenu);
              menu = newMenu;
            }

            Boolean menuItemFound = false;
            String menuItemId = menuItem.getName();

            // check if the menu item is already added

            for (Iterator iterator = menu.getChildren().iterator();
                 iterator.hasNext(); ) {
              UIComponent component = (UIComponent)iterator.next();
              if (component.getId().equalsIgnoreCase(menuItemId)) {
                menuItemFound = true;
              }
            }
            if (!menuItemFound) {
              RichCommandMenuItem richMenuItem = new RichCommandMenuItem();
              richMenuItem.setId(menuItemId);
              richMenuItem.setText(menuItem.getName());
              richMenuItem.setActionExpression(getMethodExpression(menuItem.getAction()));
              richMenuItem.setIcon(menuItem.getIcon());
              menu.getChildren().add(richMenuItem);
            }
          }
        }
        menuView.remove();
      }
    } catch (Exception e) {
      // TODO: Add catch code
      e.printStackTrace();
    } finally {
      if(MenuAM!=null){
          Configuration.releaseRootApplicationModule(MenuAM, true);
      }
    }
  }

  public void setInitMenu(RichMenuBar initMenu) {
      this.initMenu = initMenu;
  }

  public RichMenuBar getInitMenu() {
      return initMenu;
  }

  private MethodExpression getMethodExpression(String name) {
      Class[] argtypes = new Class[1];
      argtypes[0] = ActionEvent.class;
      FacesContext facesCtx = FacesContext.getCurrentInstance();
      Application app = facesCtx.getApplication();
      ExpressionFactory elFactory = app.getExpressionFactory();
      ELContext elContext = facesCtx.getELContext();
      return elFactory.createMethodExpression(elContext, name, null,
                                              argtypes);
  }

    public String doLogOut() throws IOException{
      return "logout";
  }
  private void updateSession() {
 
  FacesContext context=FacesContext.getCurrentInstance();
  Application appl = null;
  String masterAmDef=null;
  String masterConfig=null;
  ApplicationModule MasterAM=null;
  String userName = null;
  VariableResolver vr = null;
 
  HttpSession session = null;
  String brId = null;
  String MenuAMDef = null;
  String MenuAMConfig = null;
  ApplicationModule MenuAM = null;

  try {
    MenuAMDef = "com.operations.model.security.am.MenuAM";
    MenuAMConfig = "MenuAMLocal";
    MenuAM = Configuration.createRootApplicationModule(MenuAMDef,MenuAMConfig);
    userName = MenuAMImpl.getUserName();

          
         HttpServletRequest request =
              (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
          session = request.getSession();
          session.setAttribute("userName", userName);
          session.setAttribute("brId", SafexUtils.getBrId(userName));

  } catch (Exception e) {
  // TODO: Add catch code
  e.printStackTrace();
  } finally {
  if(MenuAM!=null){
  Configuration.releaseRootApplicationModule(MenuAM, true);
  }
  }
  }

  public String navigateToHome() {
    // Add event code here...
    return "toHome";
  }

  public void setLoggedInUserName(String loggedInUserName) {
    this.loggedInUserName = loggedInUserName;
  }

  public String getLoggedInUserName() {
   
    System.out.println("getLoggedInUserName()");
    HttpSession session =null;
    HttpServletRequest request =
         (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    session = request.getSession(false);
   
   
    loggedInUserName= session.getAttribute("userName").toString();
   
    return loggedInUserName;
  }

  public void setLoggedInbranchId(String loggedInbranchId) {
    this.loggedInbranchId = loggedInbranchId;
  }

  public String getLoggedInbranchId() {
   
    System.out.println("getLoggedInbranchId()");
    HttpSession session =null;
    HttpServletRequest request =
         (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    session = request.getSession(false);
   
   
     loggedInbranchId= session.getAttribute("brId").toString();
   
 
    return loggedInbranchId;
  }

  public String changeBranch() {
    // Add event code here...
    return "";
  }
}

---------------------------------------------------------------
TEMPLATE:






JSPX page:





-------------------------------------------------------------------------
Enabling Security













Select HTTP Basic Authentication and NEXT

put welcome page(optional) on next windows

Finish.


-----------------------------------------------------------------------

web xml config

1. web xml .. security .. login Authentication .. http:Basic Authentication
2.  web xml .. security .. Security roles.. Add your role ex, user, Administration


3. web xml .. security .. constratints ... webResource colection ... allPages
4. web xml .. security .. constratints ... authentication ...check valid user , uncheck user, administrator
5. web xml .. security .. constratints ... webResource colection .. add adfAuthentication


-------------------------------------------------------------------------

jazn data

Updated Realm as jazn data with below info

add user
Add role
Allocate resources to the user , role