Sunday, 4 September 2011

Portal Model SPI

Models provide information that WebSphere Portal needs to perform tasks such as content aggregation or building navigation to browse the aggregated content.
  •    The information that is aggregated is represented through models that can be accessed programmatically using the Model SPI (read-only).
  •  The information of a model is usually persistent (stored in a database), but can also be transient (computed and stored only in memory).
The following models can be obtained by using the Model SPI:
  • Content model, which describes the topology in which the content is structured
  •   Navigation model, which describes the topology of the navigation visible to a specific user and is  composed of navigation nodes
  •   Navigation Selection model, which describes the selected node in the navigation
  •   Content Metadata model, which provides access to metadata of nodes of the Content model
  •   Language list, which provides a list of supported languages
  •  Layout model, which describes the layout of a page that is composed of layout nodes
  • Markup list, which provides a list of supported markup languages
Sample Code:
package com.ibm.portletmodel;
import java.io.*;
import java.util.Iterator;
import java.util.Locale;
import javax.portlet.*;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import com.ibm.portal.admin.Theme;
import com.ibm.portal.content.ContentNode;
import com.ibm.portal.content.ContentPage;
import com.ibm.portal.navigation.NavigationNode;
import com.ibm.portal.admin.Language;
import com.ibm.portal.admin.LanguageList;
import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.model.LanguageListProvider;

/**
 * A sample portlet based on GenericPortlet
 */
public class PortletModelPortlet extends GenericPortlet {
    public static final String JSP_FOLDER    = "/_PortletModel/jsp/";    // JSP folder name
    public static final String VIEW_JSP      = "PortletModelPortletView";         // JSP file name to be rendered on the view mode
    public static final String SESSION_BEAN  = "PortletModelPortletSessionBean";  // Bean name for the portlet session
    public static final String FORM_SUBMIT   = "PortletModelPortletFormSubmit";   // Action name for submit form
    public static final String FORM_TEXT     = "PortletModelPortletFormText";     // Parameter name for the text input
    private static com.ibm.portal.model.NavigationSelectionModelHome navigationSelectionModelHome;
    private static com.ibm.portal.model.ThemeListHome themeListHome;
    private static com.ibm.portal.model.ContentModelHome contentModelHome;
    private static com.ibm.portal.model.ContentMetaDataModelHome cmdmHome;
    private PortletServiceHome lsh;
   
    /**
     * @see javax.portlet.Portlet#init()
     */
    public void init() throws PortletException{
        super.init();
        try
        {
          /* only perform this JNDI lookup once as this is an expensive call performance wise */
        javax.naming.Context ctx = new javax.naming.InitialContext();
        navigationSelectionModelHome = (com.ibm.portal.model.NavigationSelectionModelHome) ctx.lookup("portal:service/model/NavigationSelectionModel");
        themeListHome = (com.ibm.portal.model.ThemeListHome) ctx.lookup("portal:service/model/ThemeList");
        contentModelHome = (com.ibm.portal.model.ContentModelHome) ctx.lookup("portal:service/model/ContentModel");
        cmdmHome = (com.ibm.portal.model.ContentMetaDataModelHome) ctx.lookup("portal:service/model/ContentMetaDataModel");
        lsh = (PortletServiceHome) ctx.lookup("portletservice/com.ibm.portal.portlet.service.model.LanguageListProvider");
        }
        catch(Exception e)
        {
           
        }
    }

    /**
     * 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());
        getModelDetails((javax.servlet.ServletRequest)request, (javax.servlet.ServletResponse)response);
        getLanguages(request);
        // Check if portlet session exists
        PortletModelPortletSessionBean sessionBean = getSessionBean(request);
        if( sessionBean==null ) {
            response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
            return;
        }

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

    private void getModelDetails(ServletRequest request, ServletResponse response) {
        // TODO Auto-generated method stub
        try
        {
        NavigationNode navigationNode= getSelectedNode(request,response);
        getLayoutModel(request,response,navigationNode);
        Theme currentTheme=getCurrentTheme(request,response);
        System.out.println("currentTheme="+currentTheme);
        Object t=getMetaData(request,response);
        System.out.println("MetaData="+t);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Process an action request.
     *
     * @see javax.portlet.Portlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
     */
    public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
        if( request.getParameter(FORM_SUBMIT) != null ) {
            // Set form text in the session bean
            PortletModelPortletSessionBean sessionBean = getSessionBean(request);
            if( sessionBean != null )
                sessionBean.setFormText(request.getParameter(FORM_TEXT));
        }
    }

    /**
     * Get SessionBean.
     *
     * @param request PortletRequest
     * @return PortletModelPortletSessionBean
     */
    private static PortletModelPortletSessionBean getSessionBean(PortletRequest request) {
        PortletSession session = request.getPortletSession();
        if( session == null )
            return null;
        PortletModelPortletSessionBean sessionBean = (PortletModelPortletSessionBean)session.getAttribute(SESSION_BEAN);
        if( sessionBean == null ) {
            sessionBean = new PortletModelPortletSessionBean();
            session.setAttribute(SESSION_BEAN,sessionBean);
        }
        return sessionBean;
    }

    /**
     * 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";
    }

protected void getLayoutModel( javax.servlet.ServletRequest request, javax.servlet.ServletResponse response,NavigationNode navigationNode) throws com.ibm.portal.ModelException {
         System.out.println("Entering into getSelectedNode method");
         com.ibm.portal.model.ContentModelProvider cmProvider = contentModelHome.getContentModelProvider();
         com.ibm.portal.content.ContentModel contentModel = cmProvider.getContentModel( request, response );
         com.ibm.portal.Locator cmLocator = contentModel.getLocator();
         com.ibm.portal.content.ContentNode cNode = navigationNode.getContentNode();
         ContentPage contentPage =(ContentPage) contentModel.getLocator().findByID(cNode.getObjectID());
         com.ibm.portal.content.LayoutModel layoutModel = null;
         layoutModel = contentModel.getLayoutModel(contentPage);  
         System.out.println("layoutModel="+layoutModel);
         System.out.println("contentPage="+contentPage);
         System.out.println(layoutModel.getCreated().toString());
         for (java.util.Iterator it = layoutModel.getAllAllowedPortlets().iterator(); it.hasNext(); ) {
          System.out.println("Element in getLayoutModel: " + it.next());
     }
         System.out.println("Exiting into getSelectedNode method");
 }

protected com.ibm.portal.navigation.NavigationNode getSelectedNode( final javax.servlet.ServletRequest request, javax.servlet.ServletResponse response ) throws com.ibm.portal.ModelException {
    System.out.println("Entering into getSelectedNode method");
    com.ibm.portal.model.NavigationSelectionModelProvider nsmProvider = navigationSelectionModelHome.getNavigationSelectionModelProvider();
    com.ibm.portal.navigation.NavigationSelectionModel nsm = nsmProvider.getNavigationSelectionModel(request, response);
    return (com.ibm.portal.navigation.NavigationNode) nsm.getSelectedNode();
}

protected com.ibm.portal.admin.Theme getCurrentTheme(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response) throws com.ibm.portal.ModelException {
    final com.ibm.portal.model.NavigationSelectionModelProvider nsmProvider = navigationSelectionModelHome.getNavigationSelectionModelProvider();
    final com.ibm.portal.navigation.NavigationSelectionModel nsm = nsmProvider.getNavigationSelectionModel(request, response);
    com.ibm.portal.model.ContentModelProvider cmProvider = contentModelHome.getContentModelProvider();
    com.ibm.portal.content.ContentModel contentModel = cmProvider.getContentModel( request, response );
    final NavigationNode currentNavNode = (NavigationNode) nsm.getSelectedNode();
    final ContentNode currentContentNode = currentNavNode.getContentNode();
    com.ibm.portal.admin.Theme currentTheme = null;
    // Walk up the content hierarchy to get the theme that is in place currently.
    ContentNode parent = currentContentNode;
    while(currentTheme == null && parent != null ){
        if(parent instanceof com.ibm.portal.content.ThemeProvider){
            final com.ibm.portal.content.ThemeProvider themeProvider = (com.ibm.portal.content.ThemeProvider) parent;
            currentTheme = themeProvider.getTheme();
        }
        parent = (ContentNode) contentModel.getParent(parent);
    }
    if(currentTheme == null){
        // No theme was found, use the portal default:
        final com.ibm.portal.admin.ThemeList themeList = themeListHome.getThemeListProvider().getThemeList(request);
           currentTheme = themeList.getDefault();
    }
    return currentTheme;
}

protected Object getMetaData(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response) throws com.ibm.portal.ModelException
{
        com.ibm.portal.model.NavigationSelectionModelProvider nsmProvider = navigationSelectionModelHome.getNavigationSelectionModelProvider();
        com.ibm.portal.navigation.NavigationSelectionModel nsm = nsmProvider.getNavigationSelectionModel(request, response);
        com.ibm.portal.model.ContentMetaDataModelProvider cmdmProvider = cmdmHome.getContentMetaDataModelProvider();
        com.ibm.portal.content.ContentMetaDataModel cmdm = cmdmProvider.getContentMetaDataModel(request, response);
        System.out.println("ContentMetaDataModel="+cmdm);
        Object cn = nsm.getSelectedNode();
        com.ibm.portal.MetaData md = cmdm.getMetaData(cn);
        Object metaDataValue = md.getValue("com.ibm.portal.applicationGuid");
        return metaDataValue;
}

private void getLanguages(PortletRequest request) {
     Locale locale = request.getLocale();       
     try {       
         if (lsh!= null) {
             LanguageListProvider provider = (LanguageListProvider) lsh.getPortletService(LanguageListProvider.class);
             LanguageList list = provider.getLanguageList(request);
             Iterator it = list.iterator();
             Language language = null;
             while (it.hasNext()) {
                 language = (Language)it.next();
                 System.out.println(language.getLocale()+"="+language.getTitle(locale));           
             }
         }
     } catch(Exception ex) {
         System.err.println("There was an error retrieving the languages " + ex);
     }       
}
} 


ouput i got:

[9/4/11 2:35:07:389 PDT] 0000003d SystemOut     O Entering into getSelectedNode method
[9/4/11 2:35:07:389 PDT] 0000003d SystemOut     O Entering into getSelectedNode method
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O layoutModel=com.ibm.wps.model.wrappers.LayoutModelWrapperFactoryImpl$LayoutModelWrapperImpl@ca00ca
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O contentPage=null ( STATICPAGE , [ObjectIDImpl 'Z6_IARJNKG10O82F0I902J9FK0001', CONTENT_NODE, VP: 0, [Domain: rel], DB: 0000-52ED79290C0023F1804C40CCF4280020] )
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O Thu Aug 25 11:47:07 PDT 2011
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O Exiting into getSelectedNode method
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O currentTheme=Theme, id=[ObjectIDImpl 'ZJ_CGAH47L00OES90IAH10FQR3KJ6', THEME, VP: 0, [Domain: rel], DB: 0000-0CAA484E05003B9E80543180A7F7A0D3],ResourceRoot=PageBuilder2
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O ContentMetaDataModel=com.ibm.wps.model.wrappers.ContentMetaDataModelWrapper@7e267e26
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O MetaData=null
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O ar=null
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O ca=null
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O cs=null
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O da=null
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O de=null
[9/4/11 2:35:07:404 PDT] 0000003d SystemOut     O el=null
 

click here to download the files 

Remote PUMA SPI REST Service

The Remote PUMA SPI REST Service is implemented as a servlet that runs as a separate enterprise application on the WebSphere Portal Express server.

Operation
Description
Parameter(Method Name)
/um/attributes/users
 list of references to the attribute definitions that are available for users
expandRefs(GET)
/um/attributes/users/attribute name

representation of the attribute definition

/um/attributes/groups
the list of references to the attribute definitions that are available for groups
expandRefs(GET)
/um/attributes/groups/attribute name
a representation of the attribute definition

/um/currentuser/profile
profile of the current user. If this operation is performed without authentication, the profile of the anonymous user is returned.
Update(PUT OR POST)
/um/users/profiles
the list of references to all user that correspond to the search criteria and other parameters. If there are no limiting parameters, all available users are returned. The list that is returned is access control filtered for the current user.
expandRefs(GET)
includeAttributes(GET)
memberOf(GET)
showNested(GET)
searchAttributes(GET)
identifier(GET)
resultsPerPage(GET)
sortByAttributes(GET)
descending(GET)
/um/groups/profiles

the list of references to all groups that correspond to the search criteria and other parameters. If there are no limiting parameters, all available groups are returned. The list that is returned is access control filtered for the current user.
expandRefs(GET)
includeAttributes(GET)
memberOf(GET)
showNested(GET)
searchAttributes(GET)
identifier(GET)
resultsPerPage(GET)
sortByAttributes(GET)
descending(GET)
/um/users/profiles/unique id of user
Returns a representation of a user profile.
update(PUT OR POST)
/um/groups/profiles/unique id of group
Returns a representation of a group profile.
update(PUT OR POST)
/um/groupmembership/unique id of user
Returns the list of references to all group profiles of the groups of which the user is a member.
expandRefs(GET)
includeAttributes(GET)
showNested(GET)
update(PUT OR POST)
/um/groupmembership/unique id of group

Returns the list of references to all group profiles of the groups of which the group is a member.
expandRefs(GET)
includeAttributes(GET)
showNested(GET)
update(PUT OR POST)

The portal Remote PUMA SPI REST Service allows requests to the following operations only for authenticated users by using the /um/secure path element:
  • /um/attributes/users
  •  /um/attributes/users/attribute name
  •   /um/attributes/groups
  •  /um/attributes/groups/attribute name
Sample Code:
       
public class SampleTest {
    public static void main(String[] args) {
        try {
           
            /**   
            /um/secure/users/profiles
            /um/secure/attributes/groups
             /um/secure/attributes/users/
              **/
          final String userName = "wasadmin";
          final String password = "wasadmin";
          HttpClient client = new HttpClient();
          GetMethod  get = new  GetMethod ("http://localhost:10039/wps/mycontenthandler/!ut/p/um/secure/currentuser/profile");
          Credentials defaultcreds = new UsernamePasswordCredentials(userName,password);
          client.getState().setCredentials(null,null,defaultcreds);
          get.setDoAuthentication(true);
          // Open the URL: throws exception if not found
          client.executeMethod(get);
          InputStream inputStream = get.getResponseBodyAsStream();
          System.out.println(convertStreamToString(inputStream));
      
        } catch (MalformedURLException e) {
          e.printStackTrace(System.out);
        } catch (IOException e) {
          e.printStackTrace(System.out);
        }
      }
    public static String convertStreamToString(InputStream inputStream) throws IOException {
        if (inputStream != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                inputStream.close();
            }
            return sb.toString();
        } else {
            return "";
        }
    }
    }

In this example,i am able to get profile of "wasadmin".

Result XML





Click here to download the files

Monday, 29 August 2011

Login Service SPI

The public login portlet service introduced with WebSphere Portal V6.0.1 (interface com.ibm.portal.portlet.service.login.LoginService) can be used to trigger a form-based login to WebSphere Portal from any portlet .This service is useful in a couple of different scenarios in which the following conditions apply:
·      It is necessary to enhance the login portlet by additional elements, for example, a custom form, additional input elements, or enhanced portlet functionality.
  • The user input or parts of it need to be modified by some logic before being passed to the actual login.
  • You want to propagate information from the user interface to the actual login, for example, in the javax.security.auth.Subject object passed on to the Java™ Authentication and Authorization Service (JAAS) login or the login context that is passed to the ExplicitLoginFilter elements introduced with WebSphere Portal V6.1
  • You want to influence the login portlet’s behavior in reaction to particular errors that might occur during the login, for example, a redirect operation to a dedicated page to change the password after the login failed, indicating that the password expired. 
Operation of Login Service

An instance of the com.ibm.portal.portlet.service.login.LoginService is retrieved for FavouriteLogin Portlet request and response pair using the com.ibm.portal.portlet.service.login.LoginHome interface, which can be looked up using Java Naming and Directory Interface (JNDI) once (for example, during portlet initialization).The service provides one method to trigger a login that takes the user ID, password, a mandatory java.util.Map object that holds context information, and an optional prefilled javax.security.auth.Subject object. 

The login method defines a couple of exceptions to distinguish several error conditions that can cause the login to fail and might be handled appropriately in the portlet. Additionally, the interface defines a constant DO_RESUME_SESSION_KEY to be used as a key to store a java.lang.Boolean object to indicate whether the portal should perform a session resume. If an error occurs during login, the portlet renders the view with the login form again, additionally displaying the message of the error on the top.If there is no error in login, user is authenticated and redirected to protected page.(from /portal to /myportal)



For redirecting to a custom page after logging(using login service),please refer to my article.

Download the code

Sunday, 28 August 2011

Client-side and server-side page rendering modes in Page Bulider Theme

Client-side mode
    In client-side mode the following applies:
    • Page changes occur without a browser full page refresh. Upon a user request a SWITCH_PAGE client-side event is fired. This triggers the update of the page navigation, and the contents of the new page are loaded and replace the content of the prior page.
    • Interaction with portlets and widgets updates only the affected portlet or widget, and possibly others as a result of wiring. Portlets are rendered as iWidgets by means of an iWidget Wrapper.
    • The implementation and programming model for client-side mode is provided by the Mashups Enabler common component, and public builder events.
Server-side mode

In server-side mode the following applies:
  • Page changes cause a browser full page refresh.
  • Interactions with portlets result in a browser full page refresh.
  • However, iWidgets are rendered and interact within the page just as in client-side mode. 
Theme adjustment  to Modes:
To render the portal theme, the same theme elements are used in both rendering modes. In general, you can write navigation iWidgets to fire a SWITCH_PAGE event. The internal JavaScript NavigationController of the theme determines the current rendering mode of the page and processes the event appropriately.