Wednesday, 12 October 2011

Sample Code for NavigationModelProvider in Websphere Portal Server


com.ibm.portal.navigation package defines the navigation model (NavigationModel) which represents a view on content model used for navigation. As described in section "The sub package com.ibm.portal.content", the topology of the navigation model currently corresponds with that of the content model - each node in the content model has an equivalent navigation node at the same hierarchical level.

The elements of the navigation model are NavigationNodes. Each such node can reference a ContentNode. The navigation nodes have a title that is provided through the Localized interface.

In this example, i am displaying all portal pages with url.

Sample Code:
package com.ibm.mynavigationmodelprovider;
import java.io.*;
import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.portlet.*;
import com.ibm.portal.MetaData;
import com.ibm.portal.ModelException;
import com.ibm.portal.ObjectID;
import com.ibm.portal.ObjectNotFoundException;
import com.ibm.portal.content.ContentNode;
import com.ibm.portal.identification.Identification;
import com.ibm.portal.model.LocalizedStringResolver;
import com.ibm.portal.navigation.NavigationModel;
import com.ibm.portal.navigation.NavigationNode;
import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.model.NavigationModelProvider;
import com.ibm.portal.serialize.SerializationException;
import com.ibm.portal.state.EngineURL;
import com.ibm.portal.state.PortletStateManager;
import com.ibm.portal.state.URLFactory;
import com.ibm.portal.state.accessors.selection.SelectionAccessorController;
import com.ibm.portal.state.accessors.selection.SelectionAccessorFactory;
import com.ibm.portal.state.service.PortletStateManagerService;

/**
 * A sample portlet based on GenericPortlet
 */
public class MyNavigationModelProviderPortlet extends GenericPortlet {

      public static final String JSP_FOLDER    = "/_MyNavigationModelProvider/jsp/";    // JSP folder name

      public static final String VIEW_JSP      = "MyNavigationModelProviderPortletView";         // JSP file name to be rendered on the view mode
      PortletServiceHome psh;
      private Identification idSvc;
      public static LocalizedStringResolver localizedStringResolver=null;
      protected PortletStateManagerService service;
       private static final String JNDI_NAME =
                  "portletservice/com.ibm.portal.state.service.PortletStateManagerService";
      /**
       * @see javax.portlet.Portlet#init()
       */
      public void init() throws PortletException{
            super.init();
            try {
                  Context ctx = new InitialContext();
                  psh = (PortletServiceHome) ctx.lookup(NavigationModelProvider.JNDI_NAME);
                  idSvc = (Identification)ctx.lookup(Identification.JNDI_NAME);
                  localizedStringResolver= (LocalizedStringResolver)ctx.lookup("portal:service/model/LocalizedStringResolver");
                   final PortletServiceHome serviceHome = (PortletServiceHome)ctx.lookup(JNDI_NAME);
                  service = (PortletStateManagerService)
                    serviceHome.getPortletService(PortletStateManagerService.class);
                  } catch(NameNotFoundException ex) {
                        ex.printStackTrace();
                  } catch (NamingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
      }

      /**
       * Serve up the <code>view</code> mode.
       *
       * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
       */
      public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
            // Set the MIME type for the render response
            response.setContentType(request.getResponseContentType());
            NavigationModelProvider provider = (NavigationModelProvider) psh.getPortletService(NavigationModelProvider.class);
            try {
                   NavigationModel model = provider.getNavigationModel(request, response);
                   NavigationNode root = (NavigationNode) model.getRoot();
                   ArrayList<Item> pages=new ArrayList<Item>();
                   pages.clear();
                   addChildren(root, model, pages, request, 0,response);
                   request.setAttribute("result", pages);
                  }
                   catch (ModelException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }

                   
            // Invoke the JSP to render
            PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
            rd.include(request,response);
      }


            // TODO Auto-generated method stub
            /**
             * @param root
             * @param navigationModel
             * @param pageGroups
             * @throws Exception
             */
            private void addChildren(NavigationNode node,
                        NavigationModel navigationModel, ArrayList pages, PortletRequest request,
                        int level,PortletResponse response) throws Exception {
                  Iterator i = navigationModel.getChildren(node);
                  if (i != null) {
                        while (i.hasNext()) {
                              boolean bDoNotDisplay = false;
                              NavigationNode n = (NavigationNode) i.next();
                              ContentNode content = n.getContentNode();
                              if (content instanceof MetaData) {
                                    MetaData md = (MetaData) content;
                                    Object hiddenAttr = md.getValue("hidden");
                                    if (hiddenAttr != null
                                                && "Yes".equalsIgnoreCase(hiddenAttr.toString())) {
                                          bDoNotDisplay = true;
                                    }
                              }
                              if (!bDoNotDisplay) {
                                   
                                    StringBuffer title = new StringBuffer(localizedStringResolver.getTitle(n, request.getLocales()));
                                    String uniqueName = null;
                                    if (n.getContentNode() != null
                                                && n.getContentNode().getObjectID() != null
                                                && n.getContentNode().getObjectID().getUniqueName() != null) {
                                          uniqueName = n.getContentNode().getObjectID()
                                                      .getUniqueName();
                                    }
                                    if (uniqueName != null) {
                                          String url=createPageURL(uniqueName, request,  response);
                                          pages.add(new Item(url, title.toString()));
                                    }
                              }

                              if (navigationModel.getChildren(n) != null) {
                                    addChildren(n, navigationModel, pages, request, level + 1,response);
                              }
                        }
                  }
            }


           
            /**
             * SelectionAccessorFactory:
             * Provides accessors to read and write portal page selection information.
             * Use the SelectionAccessorController to create a URL to another portal page.
             */
            public String createPageURL(final String uniquepagename,PortletRequest request, PortletResponse response) throws Exception {
                      // get the needed factories
                  URLFactory urlFactory=null;
                  SelectionAccessorController selCtrl=null;
                  try{
                   PortletStateManager manager = service.getPortletStateManager(request, response);
             urlFactory = manager.getURLFactory();
             EngineURL url=urlFactory.newURL(null);
                   SelectionAccessorFactory selFct = (SelectionAccessorFactory)manager.getAccessorFactory(SelectionAccessorFactory.class);
                 selCtrl = selFct.getSelectionAccessorController(url.getState());
                 selCtrl.setSelection(uniquepagename);
                   return url.writeDispose(new StringWriter()).toString();
                    }
                  catch(Exception e)
                  {
                        e.printStackTrace();
                        throw e;
                  }
                  finally
                  {
                              if(null !=selCtrl)selCtrl.dispose();
                              if(null !=urlFactory)urlFactory.dispose();
                    }
                  }

      /**
       * Returns JSP file path.
       *
       * @param request Render request
       * @param jspFile JSP file name
       * @return JSP file path
       */
      private static String getJspFilePath(RenderRequest request, String jspFile) {
            String markup = request.getProperty("wps.markup");
            if( markup == null )
                  markup = getMarkup(request.getResponseContentType());
            return JSP_FOLDER + markup + "/" + jspFile + "." + getJspExtension(markup);
      }

      /**
       * Convert MIME type to markup name.
       *
       * @param contentType MIME type
       * @return Markup name
       */
      private static String getMarkup(String contentType) {
            if( "text/vnd.wap.wml".equals(contentType) )
                  return "wml";
        else
            return "html";
      }

      /**
       * Returns the file extension for the JSP file
       *
       * @param markupName Markup name
       * @return JSP extension
       */
      private static String getJspExtension(String markupName) {
            return "jsp";
      }

}

ScreenShot:


Click here to download sample code

4 comments:

  1. Hi,why NavigationModelProvider.JNDI_NAME can not be resolved? thanks

    ReplyDelete
  2. which version server u are using.

    ReplyDelete
  3. Hi, I am getting the same error 'NavigationModelProvider.JNDI_NAME can not be resolved'. I am using Websphere Portal Server 6.1

    ReplyDelete
  4. It will work on portal 7 and 8 ... try it

    ReplyDelete