Showing posts with label JSR 286 Portlets. Show all posts
Showing posts with label JSR 286 Portlets. Show all posts

Inter Portlet Communication JSR286 chnages

page.xml
<cross-page-wire action="update" domain="rel" immediate-switch="true" objectid="10_I8AA1AO0GGD4D0I983LEVI3002" ordinal="0" source-pageref="6_I8AA1AO0G81VF0IU4TPL3530G0" source-portletinstanceref="5_I8AA1AO0G81VF0IU4TPL3530G5" source-property="publish.{http:bluf.com/events}ExceptionEvent" target-action="process.{http:bluf.com/events}ExceptionEvent" target-pageref="6_2A5IGJG0GOUJ10IIFCH4V42084" target-param="process.{http:bluf.com/events}ExceptionEvent" target-portletinstanceref="5_2A5IGJG0GGDJ40IASDNVIN2007" user="anonymous portal user"/>
        <cross-page-wire action="update" domain="rel" immediate-switch="true" objectid="10_I8AA1AO0GGD4D0I983LEVI3001" ordinal="0" source-pageref="6_2A5IGJG0GOUJ10IIFCH4V42084" source-portletinstanceref="5_2A5IGJG0GGDJ40IASDNVIN2007" source-property="publish.{http:bluf.com/events}backToException" target-action="process.{http:bluf.com/events}backToException" target-pageref="6_I8AA1AO0G81VF0IU4TPL3530G0" target-param="process.{http:bluf.com/events}backToException" target-portletinstanceref="5_I8AA1AO0G81VF0IU4TPL3530G5" user="anonymous portal user"/>
PortletNo1 portlet.xml
<supported-processing-event>
            <qname xmlns:x="http:bluf.com/events">x:backToException</qname>
        </supported-processing-event>
        <supported-publishing-event>
            <qname xmlns:x="http:bluf.com/events">x:ExceptionEvent</qname>
        </supported-publishing-event> 


 PortletNo2 portlet.xml
<supported-processing-event>
            <qname xmlns:x="http:bluf.com/events">x:ExceptionEvent</qname>
        </supported-processing-event>
        <supported-publishing-event>
            <qname xmlns:x="http:bluf.com/events">x:backToException</qname>
        </supported-publishing-event>


Add Event info to the portlet.xml
<default-namespace>http://target/</default-namespace>
    <event-definition>
        <qname xmlns:x="http:jpmc.com/events">x:ExceptionEvent</qname>
        <value-type>com.jpmc.gap.event.WrapperEvent</value-type>
    </event-definition>
    <event-definition>
        <qname xmlns:x="http:jpmc.com/events">x:backToException</qname>
    </event-definition>



Click here to View more...

JSR286 Portlet Filter Sample

Overview

The Java Portlet Specification 2.0 added the concept of Portlet Filters, to allow for code to be called on portlet initialization, destruction and action, event and render phases, so that developers could intercept portlet requests and insert additional functionality to existing portlets (eg, for common mechanisms across portlets like auditing or a hit counter) similar to what has been available to J2EE developers via Servlet Filters for quite a while now.

For more information about JSR286 Java Portlet Specification 2.0 Portlet Filters and other mechanisms new to the 2.0 portlet spec, see the following article:

http://www.ibm.com/developerworks/websphere/library/techarticles/0803_hepper/0803_hepper.html

A sample portlet filter


import java.io.IOException;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.filter.FilterChain;
import javax.portlet.filter.FilterConfig;
import javax.portlet.filter.RenderFilter;
public class MyPortletFilter implements RenderFilter
{
public void doFilter(RenderRequest req, RenderResponse res, FilterChain chain)
throws IOException, PortletException
{
System.out.println("DEBUG: My Portlet Filter Pre-processing a render request");
// Hand off control to the next filter in the chain, 
// or the portlet itself if no more filters
chain.doFilter(req, res);
System.out.println("DEBUG: My Portlet Filter Post-processing a render request"); 
}
public void destroy()
{
System.out.println("DEBUG: Destroying My Portlet :-(");  
}
public void init(FilterConfig arg0) throws PortletException
{
System.out.println("DEBUG:  Initializing My Portlet");  
}
}
 

Configuring a portlet filter


The Java Portlet Specification 2.0 defines optional elements to define portlet filters, and then to map them to portlets (via portlet name) also defined in the descriptor.

WPF generates the WEB-INF/portlet.xml descriptor each time you publish a portlet WAR from a project, from a template under WEB-INF/bin/deploy ment. To avoid upgrade issues, WPF recommends not editing the portlet.xml template directly, but rather to use the new deployment descriptor fragment processing mechanism available as of the August 09 WPF Next beta update and followon WPF releases.
The fragment processing mechanism allows you to add elements to standard web and portlet deployment descriptors, by defining a subset of a descriptor in one of the WEB-INF/bin/deployment/extensions folders. For instance, see the readme in your project's WebContent/WEB-INF/bin/deployment/extensions/portlet.jsr286/Readme.txt

The following filter fragment file (MyPortletFilter.xml) should be placed under your project's WebContent/WEB-INF/bin/deployment/extensions/portlet.jsr286 folder.

<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd">
    <filter>
        <filter-name>MyPortletFilter</filter-name>
        <filter-class>com.ibm.samples.MyPortletFilter</filter-class>
        <lifecycle>RENDER_PHASE</lifecycle>
   </filter>
    <filter-mapping>
        <filter-name>MyPortletFilter</filter-name>
        <portlet-name>WPFHelloPortletWorld</portlet-name>
    </filter-mapping>
</portlet-app>


 
Click here to View more...

JSR 286 - Portlet Filters

INTRO:
● Modeled after Servlet Filters
● Modify request data by wrapping request
● Modify response data by wrapping response
● Intercept invocation of a portlet before and after it is called
● Filters may be chained

Portlet Filter Interface:
● Must implement javax.portlet.Filter interface
● Must provide a public no-arg constructor
● init() method will be called on all Filters before being called on any Portlets
● destroy() will be called if Filter is removed from service
● doFilter() method called if processAction(),processEvent(), render(), or serveResource() would be called on Filtered Portlet

Declaring Portlet Filters
● Declared in portlet.xml in <filter> element
● <filter-mapping> element must specify the applicable portlets
● Restrict to specific lifecycle methods using the <lifecycle> element in <filter-mapping>
● Order in portlet.xml matters for multiple filters of the same portlet
● Portlet containers are expected/allowed to cache the "filter chain"

Wrapping Requests/Reponses
–  ActionRequestWrapper      ActionResponseWrapper
–  EventRequestWrapper        EventResponseWrapper
–  RenderRequestWrapper     RenderResponseWrapper
–  ResourceRequestWrapper  ResourceResponseWrapper

Click here to View more...

Inter portlet communication between portlets across pages

In order to provide coordination between portlets the Java Portlet Specification, JSR 286 introduces Eventing and Public Render Parameters

Eventing:

By default portlets can send and receive events with other portlets that are on the same page. This can be changed to enable portlets to send and receive events from other portlets that are on different pages. This can be done by adding the following property in portal-ext.properties in Web Space server and Liferay Portal 5.2.x.

portlet.event.distribution=ALL_PORTLETS



Public Render Parameters:

By default portlets can share render states with other portlets that are on the same page. This can be changed to enable portlets to share render states with other portlets that are on different pages. This can be done by adding the following property in portal-ext.properties in Web Space server and Liferay Portal 5.2.x.

portlet.public.render.parameter.distribution=ALL_PORTLETS


Click here to View more...

Preventing infinite loops in Eventing of JSR 286

The following property is used to specify the maximum number of events that can be generated from portlets to prevent infinite loops. If a portlet sends an event to other portlets, it is considered as one event generation. If the other portlets send events, that is considered as two event generations and so on. The default value is 3.





portlet.event.max.generation=3


Click here to View more...

Caching with JSR 286

The public review draft of JSR 286 was recently released and the related files can be downloaded from this link. One of the major changes introduced in the new Portlet specification is how the caching of markup and resources can be done by the Portlet Container. I just want to highlight the differences between the caching part of JSR 168 and JSR 286 here.

JSR 168:

* Only markup caching is supported. Resources are not accessed through a separate life cycle method.
* Only "Expiration" cache is supported.
* The cache is per user client and not shared across users.
* The cached content is expired after a pre-defined (in portlet.xml) period, or as set in the portlet (programatically).
* The expired cache is deleted and a fresh markup is fetched by calling the render method




JSR 286:

* Resources can be cached. A new life cycle method serveResource() has been introduced which allows access to the PortletContext object apart from providing more control for the portlet developers.
* "Validation" caching is supported along with "Expiration" caching. After the cache has expired the portlet has the option to check if the cache is still valid and indicate that the cache can be reused. To enable this, ETag has been introduced, which is similar to how the browsers, which conform to HTTP 1.1, perform caching. Once the cache has expired the Portlet Container calls the render/serveResource method with the ETag set in the RenderRequest/ResourceRequest, which the portlet can access and check if the cache is still valid. If the cache is still valid, then the portlet can set the USE_CACHED_CONTENT property in the response, and the new expiration time.
* Cache scope has been introduced, which when set to "public" indicates that the cache can be shared across users. The default value is "private" which behaves like the JSR 168 caching where the cache is per user.

The introduction of ETag ensures that the browser can be leveraged to cache resources and markup. With the new features of public sharing of caches, resource caching, validation caching and leveraging browser caching, the performance of aggregation of portlets by a portal can be seen to increase significantly.

Click here to View more...

Resource Serving in JSR 286

Recently the JSR 286 draft was available for public review which can be downloaded from this link. It includes some of the major features which were missed in the JSR 168 spec. You can visit Deepak's blog to get a list of all those major changes. One of the major feature introduced in this new Portlet specification is "Resource Serving" . In this blog I will explain this feature in detail.

In one line "The resource serving feature provides the ability for a portlet to serve a resource".
Why it is needed ?

Direct links to the resources in the same portlet web application are not guaranteed to pass through the portal server and will not have portlet context available. So direct link should be used for the use case where access to the portlet context and access through portal server is not needed.

But the resource url link points back to the portlet. A new interface "ResourceServingPortlet" is introduced in the JSR 286 spec. Via these resource url links serveResource method of ResourceServingPortlet interface is called and portlet can serve the resource which may be protected by the portal security and can leverage portlet context. Portlet container does not render any output in addition to the content returned by the serveResource call. Thus this new life cycle method serveResource() provides more
control to the portlet developer by giving access to write directly on the response object where portal server just acts as a proxy.

The serveResource call can also be used to implement AJAX use cases by invoking resourceURL through XMLHttpRequest in client side javascript. The client side code of the portlet is then responsible for inserting either the markup or otherwise update the page DOM in a non disruptive manner for the other components on the page.



How to Create a Resource URL ?

A resource url can be generated by invoking createResourceURL() method of the RenderResponse object in render phase of the portlet or doView() method of the Generic Portlet.

The resouce url can also be created inside serveResource() method of the ResourceServingPortlet. In that case portlet developers need to call createResourceURL() method on ResouceResponse object passed to the serveResource() method.

In the following code snippet we will create a resource url inside the doView() and then we will set that url as a IMG source in the rendered output.


public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {

response.setContentType("text/html");
PrintWriter writer = response.getWriter();

ResourceURL resURL = response.createResourceURL();
resURL.setResourceID("image");
writer.println("");

//Render other markups

}


So when the browser loads the portal page to show the view mode of the portlet, it automatically sends the request for the resURL which goes through portal and finally serveResouce() of GenericPortlet is called to serve the resource (in this case "image").

The serveResource() for this example should look like below

public void serveResource(ResourceRequest resRequest, ResourceResponse resResp) throws PortletException, IOException {

resResp.setContentType("image/png");
byte[] b = getImage("MyImage.PNG"); //Returns image bytes
resResp.getPortletOutputStream().write(b);

}

I have taken the above image example to explain the usefulness of this new feature properly. But you may also want to create a link for a resource url in your doView() and then on clicking on that link, serverResource() will be called which will only show the output returned from the serveResource().

You can also set a resource id of the resourceURL to enable same serveResource() serving multiple resources. You can also create new resource urls inside serveResource().

The cache level of a resource url can be set through setCacheability() of ResourceURL class though there are certain restrictions in setting cache level. Possible values are: FULL, PORTLET
or PAGE.
Click here to View more...

Difference between ActionURL v/s RenderURL in JSR286 Portal

The difference is,
I would say:

ActionURL - forwards your request to processAction()
RenderURL - forwards your request to doView()

The most important difference is how the portal must handle both requests.
As the portlet specification says:

If the client request is triggered by an action URL, the portal/portlet-container must first trigger the action request by invoking the processAction method of the targeted portlet.

The portal/portlet-container must wait until the action request finishes.Then, the portal/portlet-container must trigger the render request by invoking the render method for all the portlets in the portal page with the possible exception of portlets for which their content is being cached.

The render requests may be executed sequentially or in parallel without any guaranteed order. Click here to View more...

JSR-286 Java Portlet API 2.0

Hi Friends

The following link might be very useful for most of us.
I was constantly in search of an diagrammatic representation of Potal 2.0 API and my search ended with this :)

JSR-286 Java Portlet API 2.0


Click here to View more...

How IBM supports JSR 286 portlets within WebSphere Portal Server 6.1

Java portlets started to become popular after the first version of the Java Portlet Specification, the Java Specification Request (JSR) 168, was finished in 2003 at the Java Community Processes. Since then, nearly all the vendors in the Java portal space, both commercial and open-source vendors, have implemented this standard, and developers have written portlets using the Java Portlet API.The JSR 168, however, stopped at defining the overall UI component model and did not define any means for building integrated composite applications out of these components. This limitation, and many other things that didn't make it into V1.0 due to time constraints, is now addressed in V2.0.Work on JSR 286 started in January 2006, and the final version was submitted in February 2008.Please go through the following links to get yourself more familiar with JSR 286 features and specifications:

http://www.ibm.com/developerworks/websphere/library/techarticles/0803_hepper/0803_hepper.html
http://www.ibm.com/developerworks/websphere/library/techarticles/0809_hepper/0809_hepper.html

(The second link also provides you some of the recommendations to consider while developing JSR 286 Portlets).


Broadly speaking, JSR 286 (or v2.0) has the following key points:

  • Binary compatible with JSR-168 Java Portlet Specification V2.0 was designed to avoid breaking binary code compatibility with V1.0 and to maintain compatible behavior for all API methods. This design point means that all portlets written against the V1.0 specification should run unchanged on a V2.0 container. The only exceptions to this rule are the following slight behavior changes that normally should not break any portlets:
  1. RenderResponse.setContentType is no longer required before calling getWriter or getOutput-stream. Calling getWriter or getOutputstream without previously setting the content type no longer results in an IllegalStateException in V2.0.
  2. getProtocol for included servlets / JSPs no longer returns null, but instead returns HTTP/1.1 in V2.0.

    This backward compatibility statement also includes the deployment descriptor in which V2.0 added new entries, but did not change existing ones. This behavior means that you can turn most JSR 168 portlets into a JSR 286 portlet by changing the one line in the portlet deployment descriptor that references the schema to the new V2.0 portlet deployment descriptor schema.
  • Portlet Coordination (Event support) V2.0 provides additional coordination capabilities using Event paradigm as an extension to Property Broker (dynamic event declaration for sending events and static declaration for receiving events). Within action phase, portlets will have event handling step which should get over before rendering starts.
  • Public Render Parameters allow render parameters to be shared across portlets (using HTTP GET), may be across pages and not restricted to portlet application. Parameters are visible to the portal and allowed to be shared with other components. Public render parameters are defined in the portlet.xml.
  • Resource Serving: Resource serving via Portlet (implementing additional ResourceServingPortlet interface) is additional in JSR 286. It introduces new ResourceURLs that trigger a new lifecycle method serveResource and uses Resource serving APIs (JSP Tags and method calls etc).
  • AJAX driven use cases: Ajax patterns provide full access to portlet state via XmlHttpRequest and ResourceURLs.
  • Setting cookies and HTTP headers / HTML head attributes inside Portlets (JSR 286). Within Portlet code, headers / cookies needs to be set before the document body starts.
  • Portlet Filter: V2.0 introduces Portlet filters and request / response wrappers. Portlet filters are largely similar to Servlet filter, but can be restricted to specific portlet life cycle methods (e.g. render/action etc) in portlet.xml via filter-mapping element (similar to servlet filters). Portlet container calls the filter chain.
  • Extended Request Dispatcher capabilities (to support servlet-based frameworks on top of portlets). Request dispatch includes allowed in all lifecycle methods in v2.0. This will allow better integration with Servlet driven frameworks like Struts 2.0, Spring etc.
  • Added API based Caching control
  • New JSP Tag lib for resource URLs and more implicit variables (e.g. portletSession, portletPreferences etc) available.
  • Portlet Managed modes (allow portlets to specify their own application specific portlet modes)
  • Java 5 features (e.g. Annotations, Generics, back supportability with Java 1.4 based implementations)
  • WSRP 2.0 It is a standard protocol to access portlets as web service. Portlet developers need not know anything about it if they want to publish their portlets as a Web Service.
  1. JSR 286 - API Class Diagram - Request
  2. JSR 286 - API Class Diagram - Response
  3. JSR 286 - API Class Diagram - Portlet
  4. JSR 286 - Resource Serving
  • Producer/portlet acts as proxy to resources
    • Requests for resources (e.g. PDF documents) addressed within portlet API & WSRP protocol
    • WSRP 1.0 / JSR168 required out-of-band connection (e.g. HTTP to servlet)
  • Advantages
    • Consumers do not need full access to resources referenced by portlets
    • >> Resources do not have to be directly addressable by URLs
    • >> Producers / portlets can implement any back-end protocol to serve resources (e.g. from CMS)
    • Context information is passed directly over the API / protocol, i.e.
    • >> Same session
    • >> User context, Authentication, etc.
    • >> Resources become portal context aware
    • AJAX use cases are now better supported via the portlet
  • New lifecycle method "serveResource"
    • Addresses the portlet directly
    1. Portlet responsible to dispatch or write resource to output stream
    • In portal context
    1. Navigational state, current portlet mode, window state, session, preferences...)
  • New ResourceURLs trigger "serveResource" invocation
  • Resource addressing via resourceID
    • Set as optional ResourceURL parameter
    • Allows complete protocol abstraction
    • >> Resources can be served from virtually anywhere and brought to the browser
    • AJAX fragments can be served as resources
  • Portlet owned AJAX calls
    • Full access to the portlet state
      • Via XmlHttpRequest and ResourceURLs
      • Allowed to change portlet preferences and portlet-scoped session attributes
    • Functionality restricted:
      • No state changes for navigational state (portlet mode, window state, render parameters)
      • No support for events
  • Coordinated between portal and portlet
    • Not covered by JSR 286, but vendor specific solutions exist
    • Needs to include a client side library that the portlet can leverage
    • E.g. For allowing the portal to update the URLs on the page if the portlet sets new render parameters (e.g. XmlPortletRequest and XmlPortletResponse objects)
    • OpenAjax is working on a standardized solution for the future
      • Defining a generic client side gadget programming model
  • AJAX-enabled portlet reloads affected content using a resource request
    • JavaScript call points to the Portal Application
    • Portal Application dispatches resource serving call to portlet
5. Introduction Portlet Filters & features
The Java Portlet Specification has introduced concept of Portlet Filters based on Servlet Filters. The basic concept remains the same that Portlet Filter allows you to do some pre and/or post processing for every request. Note one important point that unlike servlets, portlet specification defines 4 different phases for handling user request and as result it defines 4 Filter interfaces that you can use.
  • ACTION_PHASE : If you want to perform filtering during action phase then you should implement class implementing javax.portlet.filter.ActionFilter interface
  • RENDER_PHASE : If you want to perform filtering during render phase then you should implement class implementing javax.portlet.filter.RenderFilter interface
  • EVENT_PHASE : If you want to perform filtering during event handling phase then you should implement class implementing javax.portlet.filter.EventFilter interface
  • RESOURCE_PHASE : If you want to perform filtering during resource serving phase then you should implement class implementing javax.portlet.filter.ResourceFilter interface

A portlet filter is a Java component that can be used to modify portlet request and response before/after any lifecycle method of the portlet is being executed. The concept of Portlet filter is same as that of servlet filter. The only difference is that a servlet has only one request handling method i.e. service() method and therefore there is only one type of the servlet filter. A portlet has four types of request handling methods and therefore there are 4 different types of portlet filters. The portlet API defines following interfaces for creating Portlet filter:
  • javax.portlet.filter.ResourceFilter (for serveResource method)
  • javax.portlet.filter.RenderFilter (for render method)
  • javax.portlet.filter.ActionFilter (for processAction method)
  • javax.portlet.filter.EventFilter (for processEvent method)

Each of the above filter interface contains a single doFilter (*Request, *Response, FilterChain chain) method which differs in the type of request and response object. For example, doFilter () method in ActionFilter takes ActionRequest and ActionResponse while doFilter () method of RenderFilter takes RenderRequest and RenderResponse objects. Each of the above filter interfaces extends a common base interface called javax.portlet.filter.PortletFilter. This common base interface contains init (javax.portlet.filter.FilterConfig filterConfig) and destroy () methods. The init (...) method makes sure that every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the PortletContext which it can use, for example, to load resources needed for filtering tasks. The init () and destroy () methods of a portlet filter are being called only once during their lifetime.

A single filter class can provide filter functionality for more than one lifecycle methods and also a single filter can provide filter functionality for more than one portlet. There can be multiple filters associated with one lifecycle method of a portlet. The javax.portlet.filter.FilterChain class (created by Portlet container) is used to invoke the sequence of filters applicable for a particular lifecycle method of a portlet. The doFilter () method of a portlet filter may create customized request and response objects by using *RequestWrapper and *ResponseWrapper classes and passing these wrappers to the doFilter () method of FilterChain.

In order to write a portlet filter, the developer is required to do the following 2 things:
  1. Write a filter class - A filter class should implement one or more of the above mentioned four interfaces and should provide a no argument public constructor. The filter class is also required to override init () and destroy () method of javax.portlet.filter.PortletFilter interface. Note: Rational Application Developer 7.5 Portal Toolkit does not have inbuilt support for developing Portlet Filters unlike Servlet Filters.
  2. Add entry of filter in portlet.xml - After writing a portlet filter class, it can be configured by adding following 2 xml fragments in portlet.xml.
The first xml fragment defines a filter by providing a logical name to it. It tell portlet container about the filter class and the lifecycle phases supported by it. You can specify initialization parameters also.

The Second xml fragment specifies the portlet(s) for which this filter will be applicable. You can specify a single portlet name or mapping to a group of portlets using the ‘*’ as a wildcard.

6. JSR 286 - Public Render Parameters
In JSR 168, the render parameters set in processAction method is only available in the render of the same portlet.With the Public Render Parameters feature, the render parameters set in the processAction method of one portlet will be available in render of other portlets also. Using public render parameters instead of events avoids the additional process event call.[GL] In order to allow coordination of render parameters with other portlets, within the same portlet application or across portlet applications, the portlet can declare public render parameters in its deployment descriptor using the public-render-parameter element in the portlet application section. Public render parameters can be viewed and changed by other portlets or components.In the portlet section each portlet can specify the public render parameters it would like to share via the supported-public-render-parameter element. The supported-public-render-parameter element must reference the identifier of a public render parameter defined in the portlet application section in a public-render-parameter element.In the code, the portlets should use the defined public render parameter identifier to access the public render parameter [GL]. Rational Application Developer 7.5 (RAD) Portal Toolkit has inbuilt support for public render parameter declarations and usage, hence you will not have to code or modify the deployment descriptor the way shown down below in example[GL].

Steps to create a portlet with the Render parameters:
  1. Declare the render parameters to be shared in the portlet.xml
  2. Specify the render parameter that the portlet would like to share in the portlet section
  3. Set the render parameter in the processAction () method
Coordination aka Inter-Portlet Communication
In most cases, portlets are self-contained and do not effect each other. Such portlets can be added/removed at will without affecting other portlets on a page. This decoupled nature makes portlet development and deployment easy. But the down side is that, for the end user, the UI looks less interesting. Silos are not the best way to present UI in a browser.

The JSR-286 and WSRP 2.0 specifications allow an exception to this. These specifications add ability for portlets to communicate with each other in a loosely-coupled manner. One of the key mechanisms for doing this is by using events. Events are named, and can optionally have a payload with them. Using this mechanism, based on some user interaction, one portlet could fire an event that other portlets can handle. Upon handling the event, those portlets can fire more events, and the chain can continue until some system limit occurs. In this model, portlets don’t send events directly to each other, and the portal acts as a coordinator for event distribution. During event processing, portlets can change their own state (e.g. change some back-end data). After the event chain completes, the portal renders each portlet with their latest state. In this way, portlets can still remain loosely coupled, and yet influence each other. In essence, events make it possible for a user interaction with one portlet to change the view of not just the portlet that the user is interacting with, but other portlets on a portal page as well. In some cases, the portal itself may want to handle some events, and its own markup may change.

Here is an example. Let’s say, a portal page is aggregating two portlets, viz. A and B. A submits an XMLHttpRequest to the server, which then invokes portlet A. As part of processing the request, A fires an event that B can handle. The portal dispatches the event to B. A then generates some JSON data to be returned via the responseText field of the XMLHttpRequest. While processing the event, portlet B changes its state, and its view in the browser becomes stale. The portal then needs to render B as well, and update its UI in the browser.
Portlet A’s script that started the XMLHttpRequest does not know much about portlet B, and hence the portal can not simply return portlet A’s JSON data and portlet B’s HTML view in the same response to portlet A. It needs do something special. Again, the XMLPortletRequest interface is designed to solve this problem such that (a) portlet A can receive its JSON data, and (b) the portal can update portlet B’s view independently. The approach is not limited to events. Depending on how the portal is implemented and the features it supports, it can update any part of the portal page when several fragments of a page need to be updated in response to a portlet are XMLHttpRequest.

XMLPortletRequest is a script interface, i.e. it is possible to implement this interface in JavaScript. This is unlike XMLHttpRequest which can only be implemented by browsers natively. Except for its name, XMLPortletRequest shares the same syntax and semantics with XMLHttpRequest. If a portlet wants to synchronously or asynchronously update its UI either through an action or a render URL, it would simply use XMLPortletRequest in stead of the XMLHttpRequest. Where as browsers implement the XMLHttpRequest interface, portals and similar aggregating applications implement the XMLPortletRequest interface, typically as a layer on top of the XMLHttpRequest.

Here is the XMLPortletRequest interface:
Wrapping XMLHttpRequest:
Note that the XMLPortletRequest can be implemented as a wrapper over XMLHttpRequest, and portals provide an implementation of the XMLPortletRequest. This gives the portal a chance to intercept both requests and response. It also gives portals a chance to ferry additional portal-specific data along with each request and response, and that is the key feature of the XMLPortletRequest. See figure below.
In the above, the XMLPortletRequest is implemented using XMLHttpRequest. When a portlet’s script submits an XMLPortletRequest, the implementation makes a request to the portal on behalf of the portlet. This request could contain any implementation specific data. The portal then wraps the portlet’s response (which in this case is some JSON data) in its own response payload and returns it to its implementation in the browser. The XMLPortletRequest implementation can then return portlet’s response to the portlet via its responseText or responseXML fields. In this process, it can also update other parts of the page, including UI generated by other portlets. That is the advantage of wrapping XMLHttpRequest with a semantically equivalent interface.


Click here to View more...

JSR286: defineObjects Tag

I have got lot of queries about the variables to be used in JSP page when included from within a Portlet. Also few problems were reported that the new variables introduced in JSR 286 are not working as expected. Let me explain both.

JSR 168 (Portlet 1.0)

In JSR 168 only three variables are defined:
  • RenderRequest renderRequest
  • RenderResponse renderResponse
  • PortletConfig portletConfig
In order to use them you must refer to the taglib uri and use defineObject Tag in the JSP page as follows

<%@ taglib uri=âhttp://java.sun.com/portletâ prefix=âportletâ��%>

<portlet:defineObjects/>






JSR 268 (Portlet 2.0)


In JSR 286 following variables are defined:
  • RenderRequest renderRequest and RenderResponse renderResponse (if the JSP is included from render method)
  • ResourceRequest resourceRequest and ResourceResponse resourceResponse (if the JSP is included from serveResource method)
  • ActionRequest actionRequest and ActionResponse actionResponse (if the JSP is included from processAction method)
  • EventRequest eventRequest and EventResponse eventResponse (if the JSP is included from processEvent method)
  • PortletConfig portletConfig
  • PortletSession portletSession (returns an existing session or null if no session exists)
  • Map portletSessionScope (provides access to the portletSession attributes)
  • PortletPreferences portletPreferences (provides access to the portlet preferences)
  • Map portletPreferencesValues (provides access to the portlet preferences as a Map)

In order to use the variables you must refer to a different taglib uri and use defineObject Tag in the JSP page as follows


<%@ taglib uri=”http://java.sun.com/portlet_2_0” prefix=”portlet”%>




Click here to View more...

JSR286 : Public Render Parameter

When the Java Portlet Specification( draft was released last year, i had written a blog on Public Render Parameter feature. Recently the proposed final draft was released, it has some changes in public render parameter feature. In this blog i will explain the feature with an example.

In JSR 168, the render parameters set in processAction is only available in the render of the same portlet.

With the Public Render Parameters feature, the render parameters set in the processAction of one portlet will be available in render of other portlets also. Using public render parameters instead of events avoids the additional process event call.

In order to allow coordination of render parameters with other portlets, within the same portlet application or across portlet applications, the portlet can declare public render parameters in its deployment descriptor using the public-render-parameter element in the portlet application section. Public render parameters can be viewed and changed by other portlets or components.

In the portlet section each portlet can specify the public render parameters it would like to share via the supported-public-render-parameter element. The supported-public-render-parameter element must reference the identifier of a public render parameter defined in the portlet application section in a public-render-parameter element.

In the code, the portlets should use the defined public render parameter identifier to access the public render parameter(new addition in the proposed final draft).

To create portlets that use the public render parameters, follow these steps

1. Declare the render parameters to be shared in the portlet.xml file by setting the public render parameters at the portlet application level.


<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
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="myPortletApp" version="2.0">
<portlet>
. . .
</portlet>

<public-render-parameter>
<identifier>zip-id</identifier>
<qname xmlns:x="http://sun.com/params">x:zip</qname>
</public-render-parameter>

</portlet-app>

2. Specify the render parameter that the portlet would like to share in the portlet section.

<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
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="myPortletApp" version="2.0">
<portlet>
<description>WeatherPortlet</description>
<portlet-name>WeatherPortlet</portlet-name>
<display-name>WeatherPortlet</display-name>
<portlet-class>com.sun.portal.portlet.WeatherPortlet</portlet-class>
......
<supported-public-render-parameter>zip-id</supported-public-
render-parameter>
</portlet>

<portlet>
<description>MapPortlet</description>
<portlet-name>MapPortlet</portlet-name>
<display-name>MapPortlet</display-name>
<portlet-class>com.sun.portal.portlet.MapPortlet</portlet-class>
. . .
<supported-public-render-parameter>zip-id</supported-public-
render-parameter>
</portlet>
. . .
</portlet-app>



3. Set the render parameter in the processAction() method:

public class WeatherPortlet extends GenericPortlet {
. . .
public void processAction(ActionRequest req, ActionResponse res)
throws IOException, PortletException {
. . .
res.setRenderParameter("zip-id", zip);
}
. . .
}

Sample Application

You can download the binary WeatherMap.war file to deploy and run the sample application in . You can also get the source for the sample. If you are behind a firewall you need need to set the proxy in the webcontainer configuration.

The figure shows the Weather and Map portlets. The Weather portlet sets the zip-id which is declared as a Public Render Parameter. This parameter is supported by both Weather and Map portlets. Any change in the value of zip by Weather portlet is reflected during the render phase of both weather and map portlets.
Click here to View more...

Inter portlet communication: Shared render parameter and Eventing

IBM Portlet allows to methods for inter portlet communication:

  • Shared render parameters: allows portlets to set params that can be read by other portlets. This rather simple mechanism will probably be enough for all but the most complex communication needs
  • Events: needed for complex scenarios. The main advantage of this second method is that it allows a fully decoupled communication. A portlet issues an event and doesn't have to care if there is anyone listening for it.

I have created some portlets that implement both methods of communication and going to try to share the main points to communicate portlets using these methods.

IDE

  • The first thing to point is that the development IDE I am using is NetBeans 6.7 with Portal Pack 3.0.2.

Shared render parameters

From Portlet

  • FromPortlet_view.jsp: In this portlet page we can the parameter that is sent as public parameter and in this sample has name action-id
To Portlet
  • ToPortlet_view.jsp: In this portlet page we get the parameter and print the value
Common
  • portlet.xml: The most important in the portlet.xml are the following lines: *
  • <supported-public-render-parameter>action-id</supported-public-render-parameter>
  • <public-render-parameter><identifier>action-id</identifier><qname xmlns:x="http://www.liferay.com/public-render-parameters">x:action-id</qname></public-render-parameter>

    Events

    This method of intercommunication is much more complex than shared render parameters but looks much more power full that shared render parameters method because the event can be processed by other portlet and I think this functionality is very interesting.

    From Portlet (Publisher) The main line of portlet page is:

  • <form method="post" action="<portlet:actionURL><portlet:param name="javax.portlet.action" value="savecontact" /></portlet:actionURL>">

    In the java code of the portlet we have the following main lines:

  • @ProcessAction(name="savecontact")
  • And the method saveContact where we get the parameters and set/trigger the event

    In the portlet.xml the main lines are:

  • <supported-publishing-event><qname xmlns:x="http:mycompany.com/events">x:contactInfo</qname></supported-publishing-event>
  • <event-definition><qame xmlns:x="http:mycompany.com/events">x:contactInfo</qname><value-type>java.util.Hashmap</value-type></event-definition>

    To Portlet (Listener) The main line of portlet page is:

    getAttribute
    Print the values

    In the java code of the portlet we have the following main lines:

    @ProcessEvent(qname="{http:mycompany.com/events}contactInfo")
    Method processEvent1 where we get the event values and apply business logic

    In the portlet.xml the main lines are:
  • <supported-publishing-event><qname xmlns:x="http:mycompany.com/events">x:contactInfo</qname></supported-publishing-event>
  • <event-definition><qame xmlns:x="http:mycompany.com/events">x:contactInfo</qname><value-type>java.util.Hashmap</value-type></event-definition>



Click here to View more...

Inter Portlet Communication in JSR 286 Portlets

Coordination between portlets is a very common requirement. An example of information sharing between portlets can be a weather portlet displaying the weather information of a city and a map portlet displaying the location of the city. Since, both the portlets would be using the same zip code for a user, there should be mechanism provided by the portlal containers to allow portlets to share the zip code.

Prior to JSR 286, the support for inter portlet communication was rather minimal and information sharing between different portlets was accompalished primarily using application scoped session objects or vendor specific APIs. Both of above methods were rather problematic as in the former maintaining the uniqueness of the session attribute over a complex aaplication was a concern and in the later portability of the portlet was hampered. In order to provide coordination between portlets the Java Portlet Specification v2.0 (JSR 286) introduces the following mechanisms:

  1. public render parameters in order to share render state between portlets.
  2. portlet events that a portlet can receive and send.

Let's have a look how to use the above features.

Public Render Parameters

In JSR 168, the render parameters propagated by one portlet were only available in the render method of the same portlet. This is explained in the following figure.
jsr-168-render

In JSR 286, the render parameters propagated by one portlet can be made available to the render methods of other portlets. This is explained in the following figure.



jsr-286-render

In order to allow coordination of render parameters with other portlets, within the same portlet application or across portlet applications, in JSR 286 portlets, the portlet can declare public render parameters in its deployment descriptor using the public-render-parameter element in the portlet application section. In the portlet section each portlet can specify the public render parameters it would like to share via the supported-public-render-parameter element. The supported public-ender-parameter element must reference the identifier of a public render parameter defined in the portlet application section in a public-render-parameter element. The portlet should use the defined public render parameter identifier in its code in order to access the public render parameter.

Let's see how it works..
Consider the following example..

1. Set the public render parameters at the portlet application level.


<public-render-parameter>
<identifier>id1</identifier>
<qname xmlns:x="http://sun.com/params">x:param1</qname>
</public-render-parameter>
<public-render-parameter>
<identifier>id2</identifier>
<qname xmlns:x="http://sun.com/params">x:param2</qname>
</public-render-parameter>

2. Specify the render parameter the portlet would like to share in the portlet section.

<portlet>
<portlet-name>PortletA</portlet-name>
<supported-public-render-parameter>id1</supported-public-render-parameter>
<supported-public-render-parameter>id2</supported-public-render-parameter>
<portlet>
<portlet>
<portlet-name>PortletB</portlet-name>
<supported-public-render-parameter>id1</supported-public-render-parameter>
</portlet>
<portlet>
<portlet-name>PortletC</portlet-name>
<supported-public-render-parameter>id2</supported-public-render-parameter>
<portlet>

The public render paramters declared above are processed as explained in the figure below.
parameter-sending
Now, since the public render parameters are encoded in the URL, the values that can be shared between portlets are restricted to String and String arrays. Since, public render parameters are available only in the render method, the information shared by the portlets should be used for rendering the view rather than for processing the shared information.

Portlet Events
Portlet events could be generated as a result of a user interaction with other portlets. The portlet event model is a loosely coupled, brokered model that allows creating portlets as stand-alone portlets that can be wired together with other portlets at runtime. Portlet programmers should therefore not make any specific assumptions about the environment of portlets they are running together with. The means of wiring different portlets together is portal implementation specific. An example where a portlet may want to offer receiving events is for state changes triggered by simple user interactions, e.g. adding an item to a shopping cart. By offering this as an event to other portlets these can trigger adding items to the shopping cart based on the user interactions happing inside these portlets.

EventPortlet Interface
In order to receive events the portlet must implement the EventPortlet interface in he javax.portlet package. The portlet container will call the processEvent method for each event targeted to the portlet with an EventRequest and EventResponse object.

Events are targeted by the portal / portlet container to a specific portlet window in the current client request. Events are a lifecycle operation that occurs before the rendering phase. The portlet may issue events via the setEvent method during the action processing which will be processed by the portlet container after the action processing has finished. As a result of issuing an event the portlet may optionally receive events from other portlets or container events. A portlet that is not target of a user action may optionally receive container events, e.g. a portlet mode changed event, or events from other portlets, e.g. an item was added to the shopping cart event.

The JSR 286 event processing is explained in the following figure.
jsr-286-event-processing

To create portlets that use the eventing feature, follow these steps
1. Declare the events in the portlet.xml
(i) Set the event definition at the portlet application level. This specifies the event name and the object type.

<portlet-app ...>
<portlet>
. . .
. . .
</portlet>

<event-definition>
<qname xmlns:x="http:xebia.com/address">x:Address</qname>
<value-type>com.xebia.Address</value-type>
</event-definition>
</portlet-app>

@XmlRootElement
public class Address implements Serializable {
public Address() {
}
private String street;
private String city;
private String country;

//getters and setters
}

Note: The object must be serializable and must be instrumented with valid JAXB annotation. This might be required to ensure that portlets can send events to and receive events from remote portlets. However, in case of local communication, portal containers, for optimization purposes, might not serialize event payload.

(ii) In the portlet section, specify the event name defined above for those portlets that want to publish this event.

<portlet>
<description>ContinentPortlet</description>
<portlet-name>ContinentPortlet</portlet-name>
.................
<supported-publishing-event>
<qname xmlns:x="http:xebia.com/address">x:Address</qname>
</supported-publishing-event>
</portlet>

(iii) In the portlet section, specify the event name defined above for those portlets that want to process this event.

&lt;portlet>
<description>ContinentMapPortlet</description>
<portlet-name>ContinentMapPortlet</portlet-name>
<supported-processing-event>
<qname xmlns:x="http:xebia.com/address">x:Address</qname>
</supported-processing-event>
</portlet>
<portlet>
<description>ContinentInfoPortlet</description>
<portlet-name>ContinentInfoPortlet</portlet-name>
<supported-processing-event>
<qname xmlns:x="http:sun.com/events">x:Address</qname>
</supported-processing-event>
</portlet>

2. Issue an event in the portlet that was specified as supported-publishing-event in the portlet.

public class ContinentPortlet extends GenericPortlet {
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException,IOException {
QName qname = new QName("http:xebia.com/address" , "Address");
Address add = new Address();
//set values in address
response.setEvent(qname, add);
}
}

3. Process the event in the portlet that has specified as supported-processing-event in the portlet

public class ContinentInfoPortlet extends GenericPortlet {
public void processEvent(EventRequest request, EventResponse response) {
Event event = request.getEvent();
if(event.getName().equals("Address")){
Address payload = (Address )event.getValue();
//process payload here
}
}
}

Portlet events provide more sphisticated way of exchanging information between portlets as compared to public render paramters as they can be used to share objects rather than simple string values. They also provide an additional callback method, processEvent, which can be used to process the event information before the view for the portlet in rendered. Also, portlet events share the information in a type safe manner as the event payload id bound to a type which we declare in the portlet.xml. Also, portlet specification does not standardizes how to wire the portlets, so, portal containers are free to choose convenient mechanisms to wire the portlets together.

However, as per the portlet specification, portlet events are not as reliable means of communication as is JMS, since the specification does not mandate the portal containers to persist the portlet event data. So, in case of server failures, the portlet events can be lost.

Summary
In this blog, we discussed about the JSR 286 inter portlet communication features. First, we discussed about the public render parameters and how it works. Secondly, we discussed about the portlet events, and it's working. So, how to decide when to choose either of the above two portlets. I would use the following principle

In case, the receiver portlet, does not need to do any processing/businees logic, it is advisable to use public render parameters as they avoid the overhead for portlets event creation and wiring the portlets together, which is required in case of portlet events. As already discussed, wiring portlets together is portal container specific and is an addtional overhead. However, to allow receiver portlets to process the shared information and sending type safe values, we need to use portlet events.

Overall, JSR 286 portlet coordination features make complex portal applications modular and manageable.




Click here to View more...