Saturday 8 October 2011

Sample Code for ContentAccessService in Websphere Portal Server


Through ContentAccessService, we can access external and internal resources. This service provides similar function like java.net.URL, HttpClient.There are four methods available in this service.
  •    getInputStream(java.lang.String urlString, PortletRequest req, PortletResponse resp)
            Returns an input stream that reads from the passed url
  •   getMarkup(java.lang.String urlString, PortletRequest req, RenderResponse resp)
            Returns the markup of the input stream read from the passed url.
  • getURL(java.lang.String urlString, PortletRequest request, PortletResponse response)
Re              Returns an URL object after following redirects using a proxy if necessary
  •     include(java.lang.String urlString, RenderRequest request, RenderResponse response, PortletContextcontext)                                                                                                                  writes the content of the given url to the output stream of the portlet following redirects and using a proxy if necessary.
Sample Code:

package com.ibm.mycontentaccessservice;
import java.io.*;
import java.net.URL;
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.PortletServiceUnavailableException;
import com.ibm.portal.portlet.service.contentaccess.ContentAccessService;
/**
 * Service to access external and internal resources.
 * This on-demand proxy allows the creation of a URL or Stream which can then be passed to other classes
 * without knowing about the proxy support to enable seemless adaption to proxied environments.
 * The proxying will be provided to the URL object by means of a StreamHandler.
 */
public class MyContentAccessServicePortlet extends GenericPortlet {

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

    public static final String VIEW_JSP      = "MyContentAccessServicePortletView";         // JSP file name to be rendered on the view mode
    PortletServiceHome psh;
    ContentAccessService contentAccessservice=null;
    /**
     * @see javax.portlet.Portlet#init()
     */
    public void init() throws PortletException{
        super.init();
         Context ctx;
            try {
                ctx = new InitialContext();
                psh = (PortletServiceHome) ctx.lookup("portletservice/com.ibm.portal.portlet.service.contentaccess.ContentAccessService");
                contentAccessservice =   (ContentAccessService) psh.getPortletService(ContentAccessService.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());
       
        String urlS="http://www.google.co.in";
        InputStream in=getHTTPInputStream(urlS,  request,  response);//Returns Markup in InputStream format.
        String res=convertStreamToString(in);
        request.setAttribute("method1", res);
       
        String markup=getMarkup(urlS,  request,  response);//Returns Markup in String format.
        request.setAttribute("method2", markup);

        // Invoke the JSP to render
        PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
        rd.include(request,response);
        include(urlS,  request,  response);//include google.com markup into our code.
       
    }

    /**
     * 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";
    }
   
    protected void  include(String urlS, RenderRequest  request, RenderResponse  response)
    throws IOException, PortletServiceUnavailableException {
            if (psh != null && contentAccessservice!=null)
            {
            // content access service handles local and remote URLs transparently
             contentAccessservice.include( urlS, request, response,getPortletConfig().getPortletContext());
            }
            }


    protected InputStream getHTTPInputStream(String urlS, PortletRequest request, PortletResponse response)
    throws IOException, PortletServiceUnavailableException {
            if (psh != null && contentAccessservice!=null)
            {
            // content access service handles local and remote URLs transparently
            return contentAccessservice.getInputStream( urlS, request, response );
           
            } else
            {
            // no content access service available
            return (new URL(urlS).openStream());
            }
            }
   
    protected String getMarkup(String urlS, PortletRequest request, PortletResponse response)
    throws IOException, PortletServiceUnavailableException {

            if (psh != null && contentAccessservice!=null)
            {
            // content access service handles local and remote URLs transparently
            return contentAccessservice.getMarkup(urlS, request, (RenderResponse) response );
            }
            return null;
            }
   
    private String convertStreamToString(InputStream is)throws IOException {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
        }
      
        return sb.toString();
    }
}

ScreenShot:


Click to download samplecode

W

No comments:

Post a Comment