Sunday, 23 October 2011

Sample Code for PortletSiteAnalyzerLoggingService in Websphere Portal Server

WebSphere Portal Express implements a logging function for your usage data. The portal writes usage records to a dedicated log file if site analysis logging is enabled. Multiple types of site analyzer loggers allow portal administrators to collect statistical data in various areas. The portal server manages the collection of data on its own, but from a business point of view you can also log custom details of business events.

The portal configuration service, SiteAnalyzerLogService, determines the type of site analysis data that the portal logs at run time. Depending on the service configuration, the portal logs the following events:
  • Page management, such as creating, reading, updating, deleting pages.
  • Requests of pages by users.
  • Requests of portlets by users.
  • Session activities, such as login, logout, time out, login failed.
  • User management actions, such as creating, reading, updating, and deleting users and groups.

SiteAnalyzerLogService is not a replacement for other logs such as audit, performance, or system event logs. The audiences for those kinds of logs are different:
  • Audit logging is usually used in security-sensitive environments where changes made to the portal's run time configuration are recorded. Auditing is primarily part of the administrative function in WebSphere Portal. Portal analytics, on the other hand, focuses on that part of the portal that end users see as well as how they use the portal.
  • Performance logs are used to find out how well a particular part of the whole portal performs in the real production environment. It enables the operator to determine to what extent the portal consumes valuable resources (such as CPU or memory) while it adheres to the defined Service Level Agreements (SLAs).

  • System event logs help the system administrator to understand what issues occur while running the portal. Typically, records in the system event log contain Java™ exception traces that enable an administrator to take appropriate action

    Operation of SiteAnalyzerLoggingService

    Figure  shows an overview of the conceptual event-processing flow for server-side analytics, described as follows:

    1.      User requests are sent from the browser to the WebSphere Portal Server.

    2.      WebSphere Portal decomposes the browser request into the details of the user request andanalyzes the semantics of the request.

    3.      Based on the analysis of the request, WebSphere Portal writes event records to the siteanalytics log file (SA.log) on the WebSphere Portal Server's file system of the portal nodes.

    4.      These events reflect requested resources (for example, portal pages and portlets) as well asuser interactions (customization, log in, log out…) with corresponding event types.

    5.      These event types are written to the log file in a standard compliant syntax that follows theNational Center for Supercomputing Application (NCSA) Combined log format.



    Configuration of SiteAnalyzerLoggingService


    Once the server is restarted try accessing few pages and then look at the sa.log file you should see events being added to it.

    Since sa.log is NASA Format,we need some reporting  tools to view .I used Awstats.

    Click here to know  how to install Awstats and  intergate  Awstats with websphere portal.

    In this example,i have logged some messages for view and processaction method.

    Sample Code:

    package com.ourwebsphereportal.portletsiteanalyzerloggingservice;
    import java.io.*;
    import java.util.*;

    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.portlet.*;

    import com.ibm.portal.portlet.service.PortletServiceHome;
    import com.ibm.portal.portlet.service.siteanalyzer.PortletSiteAnalyzerLogger;
    import com.ibm.portal.portlet.service.siteanalyzer.PortletSiteAnalyzerLoggingServiceHome;

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

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

        public static final String VIEW_JSP      = "PortletSiteAnalyzerLoggingServicePortletView";         // JSP file name to be rendered on the view mode
        public static final String SESSION_BEAN  = "PortletSiteAnalyzerLoggingServicePortletSessionBean";  // Bean name for the portlet session
        public static final String FORM_SUBMIT   = "PortletSiteAnalyzerLoggingServicePortletFormSubmit";   // Action name for submit form
        public static final String FORM_TEXT     = "PortletSiteAnalyzerLoggingServicePortletFormText";     // Parameter name for the text input
        PortletServiceHome psh;
        PortletSiteAnalyzerLoggingServiceHome saLogServiceHome=null;
        PortletSiteAnalyzerLogger logger;

        /**
         * @see javax.portlet.Portlet#init()
         */
        public void init() throws PortletException{
            super.init();
            Context ctx =null;
            try {
                ctx = new InitialContext();
                psh = (PortletServiceHome) ctx.lookup(PortletSiteAnalyzerLoggingServiceHome.JNDI_NAME);
                 // obtain the service object
                saLogServiceHome = (PortletSiteAnalyzerLoggingServiceHome) psh
                                .getPortletService(PortletSiteAnalyzerLoggingServiceHome.class);
               
            } 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());

            // Check if portlet session exists
            PortletSiteAnalyzerLoggingServicePortletSessionBean sessionBean = getSessionBean(request);
            if( sessionBean==null ) {
                response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
                return;
            }
            logger=saLogServiceHome.getLogger(request, response);
            logger.log("Entering into Render");
            // Invoke the JSP to render
            PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
            rd.include(request,response);
        }

        /**
         * 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
                PortletSiteAnalyzerLoggingServicePortletSessionBean sessionBean = getSessionBean(request);
                if( sessionBean != null )
                    sessionBean.setFormText(request.getParameter(FORM_TEXT));
            }
            logger=saLogServiceHome.getLogger(request, response);
            logger.log("Entering into processAction");
        }

        /**
         * Get SessionBean.
         *
         * @param request PortletRequest
         * @return PortletSiteAnalyzerLoggingServicePortletSessionBean
         */
        private static PortletSiteAnalyzerLoggingServicePortletSessionBean getSessionBean(PortletRequest request) {
            PortletSession session = request.getPortletSession();
            if( session == null )
                return null;
            PortletSiteAnalyzerLoggingServicePortletSessionBean sessionBean = (PortletSiteAnalyzerLoggingServicePortletSessionBean)session.getAttribute(SESSION_BEAN);
            if( sessionBean == null ) {
                sessionBean = new PortletSiteAnalyzerLoggingServicePortletSessionBean();
                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";
        }

    }

    ScreenShots

    Portlet result:


    Awstat results for view and processaction method

     
    Click here to download the source code

Wednesday, 19 October 2011

Sample Code for PortletPocService in Websphere Portal Server


Using this service,we can obtain POC URL. To know what is POC URL ,please refer this link

Method Summary of PortletPocServiceHome
createContext(PortletRequest request, PortletResponse response)
Constructs the COR context for request and response
getPortletPocService(ActionRequest request, ActionResponse response)
Get a portlet POC service for the current request and response.
getPortletPocService(EventRequest request, EventResponse response)
Get a portlet POC service for the current request and response.
getPortletPocService(PortletRequest request, PortletResponse response)
Get a portlet POC service for the current request and response.
getPortletPocService(RenderRequest request, RenderResponse response)
Get a portlet POC service for the current request and response.
getPortletPocService(ResourceRequest request, ResourceResponse response)
Get a portlet POC service for the current request and response.

Each service needs  PocURLFactory object to create POC URLS.

PocURLFactory is Factory to create POC URLs. Depending on the factory method, the URL will directly point to the portal servlet, if it represents a view that keeps the navigational state of the current interaction with portal.

Method Summary of PocURLFactory
getServerContext()
Returns information about the URL configuration in the scope of the current request.
getServerContext(java.lang.Boolean bLateBinding)
Returns information about the URL configuration in the scope of the current request.
newURL(java.lang.Boolean bLateBinding)
Generates a URL that points to the POC servlet and that does not contain navigational state.
newURL(Constants.Clone type, java.lang.Boolean bLateBinding)
Generates a URL that points to the portal servlet and it based on the navigational state of the current request.
newURL(DataSource ds)
Constructs a URL that points to the POC servlet and that does not contain navigational state.
newURL(StateHolder state, Constants.Clone type, java.lang.Boolean bLateBinding)
Generates a URL that points to the portal servlet and it based on navigational state explicitly.
newURL(StateHolder state, URLContext allowedContext, Constants.Clone type, java.lang.Boolean bLateBinding)
Generates a URL that points to the portal servlet and it based on navigational state explicitly.
newURL(URLContext allowedContext, java.lang.Boolean bLateBinding)
Generates a URL that points to the POC servlet and that does not contain navigational state.
newURL(URLContext allowedContext, Constants.Clone type, java.lang.Boolean bLateBinding)
Generates a URL that points to the portal servlet and it based on the navigational state of the current request.

POCURL

The PocURL is a URL that addresses a piece of content (POC). Depending on the way the actual URL instance has been achieved, such a URL might represent the view of a resource or its binary representation. The binding to the actual resource might happen early (i.e. at URL generation time) or late (only when the URL is invoked). 

Via the writeCopy and writeDispose methods the URL can be written to a stream. writeDispose should be used wherever possible as this methods has a smaller performance impact than writeCopy. The PocURL should be disposed if it is no longer used by calling the dispose() method. The writeDispose however writes the URL to a stream and disposes it in one single step, so if writeDispose is called, the object must not be disposed additionally. 

Note: For  LATE_BINDING, POC URL is constructed as /wps/poc. For EARLY_BINDING ,,POC URL is constructed as /wps/contenthandler.


Method Summary of POCURL
java.lang.String
getDigest()
Returns a string that represents a hash over the request headers that might influence the responses (independent of the request URL).
java.lang.String
getMode()
Returns the mode that is currently associated with the resouce
java.util.Map<java.lang.String,java.lang.String[]>
getParameters()
Returns a modifiable version of the parameters used to address the object, never null, but potentially the empty map.
void
setAddressable(Addressable aAddr)
Associates the URI and parameters of the addressable object
void
setDigest(java.lang.String aDigest)
Associates a digest with the POC URL.
void
setMode(java.lang.String aMode)
Associates a mode with the URI.
void
setProtected(java.lang.Boolean bFlag)
Indicates if the URL points to the private area or to the public area .
void
setSecure(java.lang.Boolean bFlag)
Indicates the security setting for this URL.
void
setURI(java.net.URI aURI)
Associates a POC URI with the URL object.
java.io.Writer
writeCopy(java.io.Writer out, boolean bEscapeXML)
Streams the state represented by this URL object to a writer.
java.io.Writer
writeDispose(java.io.Writer out, boolean bEscapeXML)
Streams the state represented by this URL object to a writer.

URI can be in the following formats:
      uri = "cm:" page-oid |
            "nm:" navigationnode-oid |
            "lm:" [layoutnode-oid "@"] page-oid |
            "pm:" portlet-oid ["@" page-oid

Example:
/wps/mycontenthandler?uri=cm:oid:wps.content.root

In this example, I have created a pocurl pointing to IBMPortletUtils page.

Sample Code:
package com.ibm.mypocservice;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.portlet.*;
import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.resolver.PocURL;
import com.ibm.portal.resolver.accessors.url.PocURLFactory;
import com.ibm.portal.resolver.service.PortletPocServiceHome;
import com.ibm.portal.resolver.service.PortletRenderPocService;
import com.ibm.portal.state.exceptions.StateException;
import com.ibm.portal.state.exceptions.StateManagerException;



/**
 * A sample portlet based on GenericPortlet
 */
public class MyPocServicePortlet extends GenericPortlet {
      PortletServiceHome psh;
      /**
       * @see javax.portlet.Portlet#init()
       */
      public void init() throws PortletException{
            super.init();
            try {
                  Context ctx = new InitialContext();
                  psh = (PortletServiceHome) ctx.lookup(PortletPocServiceHome.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)
       */
     
      /**
       *          uri=model-uri
            The identification of the addressed resource, as described further below. The uri parameter can appear only once.
            model-uri = "cm:" page-oid |
            "nm:" navigationnode-oid |
            "lm:" [layoutnode-oid "@"] page-oid |
            "pm:" portlet-oid ["@" page-oid
            /wps/mycontenthandler?uri=lm:oid:_7_0830M4HTFF0SHFCQ_2BV@oid:_6_0830M4HTFF0SHFCQ_4D
             /wps/mycontenthandler?uri=cm:oid:wps.content.root
    
       */
      public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
            // Set the MIME type for the render response
            response.setContentType(request.getResponseContentType());
            PortletPocServiceHome service = (PortletPocServiceHome) psh.getPortletService(PortletPocServiceHome.class);
        // get the POC service for the current request
        try {
            PortletRenderPocService pocSvc = service.getPortletPocService(request, response);
            String uniquenamepage="test.IBMPortletUtils";
            String uniquenameportlet="test.IBMPortletUtils.Portlet";
            URI pocURI= new URI("pm:oid:"+uniquenameportlet+"@oid:"+uniquenamepage);
            // When this resource URL is actually invoked, the portlet receives a callback to the
            //ResourceServingPortlet#serveResource(javax.portlet.ResourceRequest, javax.portlet.ResourceResponse) method
                  ResourceURL url=pocSvc.createResourceURL(pocURI);// Calls the serveresource method of this portlet
                  PocURL pocurl=pocSvc.getURLFactory().newURL(PocURLFactory.LATE_BINDING);
                  pocurl.setURI(pocURI);
                  response.getWriter().print("<a href='"+url.toString()+"' target='_blank'>ResourceURL</a><br/>");
                  response.getWriter().print("<a href='"+pocurl.toString()+"'>PocURL For IBMPortletUtils</a>");

            } catch (StateManagerException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (URISyntaxException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (StateException e) {
                  // TODO Auto-generated catch block
                  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 {
           
      }
     
      /**
       * Process an Resource request.
       *
       * @see javax.portlet.Portlet#serveResource(javax.portlet.ResourceRequest, javax.portlet.ResourceResponse)
       */
      public void serveResource(ResourceRequest request, ResourceResponse response)throws PortletException, java.io.IOException {
            System.out.println("calling serveResource method of MyPocServicePortlet");
      }


}

ScreenShot



 Click here to download the source code