Tuesday, 18 October 2011

Sample Code for PortletModelProvider in Websphere Portal Server


The PortletModel represents portlets and their configuration data in the portal. It contains the following Object:

WebApplication
represents a deployed WAR file in the portal.
Portlet
the programmer in the deployment descriptor of a portlet web application. Each portlet web application contains one or more portlets.
PortletDefinition
represents administrator configuration for a portlet. Multiple portlet definitions can be associated with the same portlet, so that the same portlet code can be invoked with different administrative settings. The administrative UI of the portal allows to create new portlet definitions as copies of existing ones.
PortletEntity
represents end-user configuration for a portlet. It is normally created by placing a portlet definition on a page; the same portlet definition can be added to multiple pages, resulting in multiple portlet entities. There can be two levels of end-user configuration (shared and personalized configuration) that are stored in the form of separate portlet entities.
PortletWindow
represents a particular view on a portlet. It normally corresponds to a LayoutControl in the layout model. The same PortletWindow can be associated with different PorltetEntities for different users, if they have personalized the portlet independently.
PortletPreferences
An interface describing portlet preferences. Portlet preferences are not the same as metadata in general, but they may alternatively be accessed using the same interface, therefore this interface extends MetaData.
In contrast to MetaData, preferences can associate multiple values with a single key; for multi-valued preferences the inherited getValue (java.lang.String) method returns only the first value. Portlet preference values are always strings.
 
Portlet.xml

 <?xml version="1.0" encoding="UTF-8"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" id="com.ibm.myportletmodelprovider.MyPortletModelProviderPortlet.f38dc17a23">
    <portlet>
        <portlet-name>MyPortletModelProvider</portlet-name>
        <display-name xml:lang="en">MyPortletModelProvider</display-name>
        <display-name>MyPortletModelProvider</display-name>
        <portlet-class>com.ibm.myportletmodelprovider.MyPortletModelProviderPortlet</portlet-class>
        <init-param>
            <name>wps.markup</name>
            <value>html</value>
        </init-param>
        <expiration-cache>0</expiration-cache>
        <supports>
            <mime-type>text/html</mime-type>
            <portlet-mode>view</portlet-mode>
            <portlet-mode>edit</portlet-mode>
        </supports>
        <supported-locale>en</supported-locale>
        <resource-bundle>com.ibm.myportletmodelprovider.nl.MyPortletModelProviderPortletResource</resource-bundle>
        <portlet-info>
            <title>MyPortletModelProvider</title>
            <short-title>MyPortletModelProvider</short-title>
            <keywords>MyPortletModelProvider</keywords>
        </portlet-info>
    <portlet-preferences>
    <preference>
    <name>test</name>
    <value>value1</value>
    <value>value2</value>
    </preference>   
    </portlet-preferences>
    </portlet>
    <default-namespace>http://MyPortletModelProvider/</default-namespace>
</portlet-app>

Sample Code:

package com.ibm.myportletmodelprovider;
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.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.model.PortletModelProvider;
import com.ibm.portal.portletmodel.PortletDefinition;
import com.ibm.portal.portletmodel.PortletEntity;
import com.ibm.portal.portletmodel.PortletModel;
import com.ibm.portal.portletmodel.PortletWindow;
import com.ibm.portal.portletmodel.WebApplication;

/**
 * This provider provides currentportletwindow and portlet model
 */

public class MyPortletModelProviderPortlet extends GenericPortlet {

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

      public static final String VIEW_JSP      = "MyPortletModelProviderPortletView";         // JSP file name to be rendered on the view mode
      PortletServiceHome psh;
      /**
       * @see javax.portlet.Portlet#init()
       */
      public void init() throws PortletException{
            super.init();
            try {
                  Context ctx = new InitialContext();
                  psh = (PortletServiceHome) ctx.lookup(PortletModelProvider.JNDI_NAME);
                  } 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());
            try {
                  PortletModelProvider provider = (PortletModelProvider) psh.getPortletService(PortletModelProvider.class);
                  PortletModel model = provider.getPortletModel(request, response);
                  String markup = getMarkup(request.getResponseContentType());
                  PortletModelBean portletmodelbean=new PortletModelBean();
                 
                  /** PortletWindow methods **/
                  PortletWindow portletwindow=provider.getCurrentPortletWindow(request);
                  HashMap<String,String>  windowobj=new HashMap<String,String>();
                  windowobj.put("GetName",portletwindow.getObjectID().getObjectType().getName());
                  portletmodelbean.setPortletwindow(windowobj);
                 
                 
                  /** PortletDefinition methods **/
                  PortletDefinition portletdefinition=model.getPortletDefinition(portletwindow);
                  HashMap portletdefinitionobj=new HashMap();
                  ArrayList arr=new ArrayList ();
                  HashMap supportsPortletMode=new HashMap ();
                 
                  for(Iterator it=portletdefinition.getPortletModes().iterator();it.hasNext();)
                  {
                        PortletMode mode=(PortletMode)it.next();
                        String modename=mode.toString();
                        arr.add(modename);
                        supportsPortletMode.put(modename,portletdefinition.supportsPortletMode(mode));
                  }
                  portletdefinitionobj.put("GetPortletModes",arr);
                  portletdefinitionobj.put("SupportsPortletMode",supportsPortletMode);
                 
                  arr=new ArrayList ();
                  supportsPortletMode=new HashMap ();
                  for(Iterator it=portletdefinition.getPortletModes(markup).iterator();it.hasNext();)
                  {
                        PortletMode mode=(PortletMode)it.next();
                        String modename=mode.toString();
                        arr.add(modename);
                        supportsPortletMode.put(modename,portletdefinition.supportsPortletMode(mode,markup));
                  }
                  portletdefinitionobj.put("GetPortletModes For Html",arr);
                  portletdefinitionobj.put("SupportsPortletMode For Html",supportsPortletMode);
                  portletmodelbean.setPortletdefinition(portletdefinitionobj);
                 
                  /** Portlet methods **/
                  com.ibm.portal.portletmodel.Portlet portlet=model.getPortlet(portletdefinition);//Interface that represents the deployed code unit for a portlet, as specified in the deployment descriptor. Properties of the portlet are defined by the portlet programmer and deployer, typically in the deployment descriptor, and cannot be altered after deployment.
                  HashMap portletobj=new HashMap();
                  portletobj.put("PortletName",portlet.getPortletName());
                  portletobj.put("GetTitle",portlet.getTitle(Locale.ENGLISH));
                 
                  MetaData data=portlet.getMetaData();
                  HashMap metadata=new HashMap();
                  for(Iterator it=data.iterator();it.hasNext();)
                  {
                        Map.Entry<String,?> entry=(Map.Entry<String,?>)it.next();
                        metadata.put(entry.getKey(), entry.getValue());
                  }
                  portletobj.put("GetMetaData",metadata);
                 
                  com.ibm.portal.portletmodel.PortletPreferences portletpreflayer=portlet.getPortletPreferencesLayer();
                  HashMap prefrenceslayer=new HashMap();
                  for(Iterator it=portletpreflayer.iterator();it.hasNext();)
                  {
                        Map.Entry<String,?> entry=(Map.Entry<String,?>)it.next();
                        String name=entry.getKey();
                        String [] values=portletpreflayer.getStringValues(name);
                        ArrayList val=new ArrayList();
                        for(int i=0;i<values.length;i++)
                        {
                              val.add(values[i]);
                        }
                        prefrenceslayer.put(name, val);
                  }
                  portletobj.put("GetPortletPreferencesLayer", prefrenceslayer);
                 
                  arr=new ArrayList ();
                  supportsPortletMode=new HashMap ();
                  for(Iterator it=portlet.getPortletModes().iterator();it.hasNext();)
                  {
                        PortletMode mode=(PortletMode)it.next();
                        String modename=mode.toString();
                        arr.add(modename);
                        supportsPortletMode.put(modename,portlet.supportsPortletMode(mode));
                  }
                  portletobj.put("GetPortletModes",arr);
                  portletobj.put("SupportsPortletMode",supportsPortletMode);
                 
                  arr=new ArrayList ();
                  supportsPortletMode=new HashMap ();
                  for(Iterator it=portlet.getPortletModes(markup).iterator();it.hasNext();)
                  {
                        PortletMode mode=(PortletMode)it.next();
                        String modename=mode.toString();
                        arr.add(modename);
                        supportsPortletMode.put(modename,portlet.supportsPortletMode(mode,markup));
                  }
                  portletobj.put("GetPortletModes For Html",arr);
                  portletobj.put("SupportsPortletMode For Html",supportsPortletMode);
                 
                  portletobj.put("SupportsWindowState",String.valueOf(portlet.supportsWindowState(WindowState.NORMAL)));
                  portletobj.put("SupportsWindowState For Html",String.valueOf(portlet.supportsWindowState(WindowState.NORMAL,markup)));
                  portletmodelbean.setPortlet(portletobj);
                 
                 
                  /** PortletEntity methods **/
                  PortletEntity portletentity=model.getPortletEntity(portletwindow);
                  HashMap<String,String> entityobj=new HashMap<String,String>();
                  entityobj.put("GetName",portletentity.getObjectID().getObjectType().getName());
                  portletmodelbean.setPortletentity(entityobj);
                 
                  /** PortletPreferences methods **/
                  com.ibm.portal.portletmodel.PortletPreferences portletpref=model.getPreferencesHierarchy(portletentity);
                  HashMap portletpreferencesobj=new HashMap();
                  HashMap prefrenceshierarchy=new HashMap();
                  for(Iterator it=portletpref.iterator();it.hasNext();)
                  {
                        Map.Entry<String,?> entry=(Map.Entry<String,?>)it.next();
                        String name=entry.getKey();
                        System.out.println(name);
                        String [] values=portletpref.getStringValues(name);
                        arr=new ArrayList();
                        for(int i=0;i<values.length;i++)
                        {
                              arr.add(values[i]);
                        }
                        prefrenceshierarchy.put(entry.getKey(), arr);
                  }
                  portletpreferencesobj.put("GetPreferencesHierarchy", prefrenceshierarchy);
                  portletmodelbean.setPortletpref(portletpreferencesobj);
                 
                  /** WebApplication methods **/
                  WebApplication webapplication=model.getWebApplication(portlet);
                  HashMap<String,String>  webapplicationobj=new HashMap<String,String>();
                  webapplicationobj.put("ContextRoot",webapplication.getContextRoot());
                  portletmodelbean.setWebapplication(webapplicationobj);
                  request.setAttribute("result", portletmodelbean);
                 
            } catch (ModelException 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);
      }

      /**
       * Serve up the <code>edit</code> mode.
       *
       * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
       */
      public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
           
            response.getWriter().println("Edit Mode");
      }
      /**
       * 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 {
           
      }

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

}

<%@page import="com.ibm.wps.pe.om.definition.PortletDefinitionBean"%>
<%@page session="false" contentType="text/html" pageEncoding="ISO-8859-1" import="java.util.*,javax.portlet.*,com.ibm.myportletmodelprovider.*" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>       
<%@taglib prefix="c_rt" uri="http://java.sun.com/jstl/core_rt"%>  
<portlet:defineObjects/>
<c_rt:if test="${!empty requestScope.result}">
<c_rt:set var="windowobj" value="${requestScope.result.portletwindow}"/>
<c_rt:set var="portletdefinitionobj" value="${ requestScope.result.portletdefinition}"/>
<c_rt:set var="portletobj" value="${ requestScope.result.portlet}"/>
<c_rt:set var="portletentityobj" value="${requestScope.result.portletentity}"/>
<c_rt:set var="portletprefobj" value="${requestScope.result.portletpref}"/>
<c_rt:set var="webapplicationobj" value="${requestScope.result.webapplication}"/>

<table width="100%">

<tr>
<td valign="top">
<div><div align="left">PortletWindow</div>
<table border="1">
<tr>
<td><b>Method Name</b></td>
<td><b>Value</b></td>
</tr>
<c_rt:forEach var="windowbean" items="${windowobj}">
<tr>
<td>${windowbean.key}</td>
<td>${windowbean.value}</td>
</tr>
</c_rt:forEach>
</table>
<br/>
</div>
</td>

<td valign="top">
<div><div align="left">PortletDefinition</div>
<table  border="1">
<tr>
<td><b>Method Name</b></td>
<td><b>Value</b></td>
</tr>
<c_rt:forEach var="portletdefinitionbean" items="${portletdefinitionobj}">
<tr>
<td>${portletdefinitionbean.key}</td>

<td><table>
<c_rt:forEach var="arrval" items="${portletdefinitionbean.value}">
<tr>
<td>${arrval}</td>
</tr>
</c_rt:forEach>
</table></td>
</tr>
</c_rt:forEach>
</table>
<br/>
</div>
</td>

<td valign="top">
<div><div align="left">Portlet</div>
<table  border="1">
<tr>
<td><b>Method Name</b></td>
<td><b>Value</b></td>
</tr>
<c_rt:forEach var="portletbean" items="${portletobj}">
<tr>
<td>${portletbean.key}</td>
<td><table>
<c_rt:forEach var="arrval" items="${portletbean.value}">
<tr>
<td>${arrval}</td>
</tr>
</c_rt:forEach>
</table></td>
</tr>
</c_rt:forEach>
</table>
<br/>
</div>
</td>

</tr>

<tr>
<td valign="top">
<div><div align="left">PortletEntity</div>
<table border="1">
<tr>
<td><b>Method Name</b></td>
<td><b>Value</b></td>
</tr>
<c_rt:forEach var="portletentitybean" items="${portletentityobj}">
<tr>
<td>${portletentitybean.key}</td>
<td>${portletentitybean.value}</td>
</tr>
</c_rt:forEach>
</table>
<br/>
</div>
</td>

<td valign="top">
<div><div align="left">PortletPreferences</div>
<table border="1">
<tr>
<td><b>Method Name</b></td>
<td><b>Value</b></td>
</tr>
<c_rt:forEach var="portletprefbean" items="${portletprefobj}">
<tr>
<td>${portletprefbean.key}</td>
<td>${portletprefbean.value}</td>
</tr>
</c_rt:forEach>
</table>
<br/>
</div>
</td>

<td valign="top">
<div><div align="left">WebApplication</div>
<table border="1">
<tr>
<td><b>Method Name</b></td>
<td><b>Value</b></td>
</tr>
<c_rt:forEach var="webapplicationbean" items="${webapplicationobj}">
<tr>
<td>${webapplicationbean.key}</td>
<td>${webapplicationbean.value}</td>
</tr>
</c_rt:forEach>
</table>
<br/>
</div>
</td>

</tr>

</table>
</c_rt:if>


 ScreenShot


Click here to download the source code

No comments:

Post a Comment