liferay Inter portlet communication Using eventing feature


Example

The eventing mechanism is an extended version of the public render param,with additonal feature to pass custom objects to other portlets,but with an overhead of event phase.

To achieve this,this mechanism consists of

  1. Publisher portlet
  2. Processor(consumer) portlet,where both may be part of different portlet applications.

To start with,

Add <supported-publishing-event> tag to the publisher portlet in portlet.xml

    <security-role-ref>
        <role-name>user</role-name>
    </security-role-ref>
    <supported-publishing-event>
         <qname xmlns:x="http:sun.com/events">x:Employee</qname>
    </supported-publishing-event>
  </portlet>

Add <supported-processing-event> tag to the processor portlet in portlet.xml

<security-role-ref>
        <role-name>user</role-name>
    </security-role-ref>
    <supported-processing-event>
        <qname xmlns:x="http:sun.com/events">x:Employee</qname>
     </supported-processing-event>
</portlet>

Add <event-definition>tag to both the portlets,defining event-name and type in portlet.xml

<event-definition>   
  <qname xmlns:x="http:sun.com/events">x:Employee</qname>
  <value-type>com.sun.portal.portlet.users.Employee</value-type>
</event-definition>
   </portlet-app>

Next we need to create class for the event type(in case of custom type)

public class Employee implements Serializable {
  public Employee() {
  }
  private String name;
  private int userId; 

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getUserId() {
    return userId;
  }
  public void setUserId(int id)
  {
    this.userId = id;
  }

}

Now,in the publisher portlet,the event needs to be published in the action phase

    QName qname = new QName("http:sun.com/events" , "Employee");
    Employee emp = new Employee();
    emp.setName("Rahul");
    emp.setUserId(4567);
    res.setEvent(qname, emp);

Post we have published the event,it needs to be processed by the publisher portlet in the event phase.

The event phase was introduced in JSR 286 and is executed before render phase of the portlet,when applicable

@ProcessEvent(qname = "{http:sun.com/events}Employee")
public void processEvent(EventRequest request, EventResponse response) {

    Event event = request.getEvent();
    if(event.getName().equals("Employee")){
      Employee payload = (Employee)event.getValue();
      response.setRenderParameter("EmpName",
      payload.getName());
    }

}

which can then be retrieved from the render parameter via render request.