27.2.4 Updating the EchoSource portlet code
The next steps describe the changes you have to make to the EchoSource portlet code:
1. Open the EchoSource portlet double-clicking in EchoSource/Java Resources/JavaSource/echo.actions/EchoAction.java from the Project Explorer view.
2. You will set an attribute in the session object to indicate whether the Cooperative Portlets service must be initialized or not. Include the following import statement: import javax.portlet.PortletSession;
3. In EchoAction class, declare two new variables (pbService and pbServiceAvailable). Example 27-3 Declaring variables
public class EchoAction extends StrutsAction {
PropertyBrokerService pbService = null; boolean pbServiceAvailable = false;
![]()
JSR 168 portlets using cooperation should be programmed so that they perform correctly in other containers other than IBM Portal container. A good practice is to use a boolean variable that indicates if the PropertyBrokerService interface is available. The variable pbServiceAvailable will set to true only if the service is available. This variable can be used to guard accesses to IBM-only services and it is used to ensure that the portlet can still function in environments where the service is unavailable.
4. Modify the execute method to obtain a reference to the property broker only the first time the method is invoked. For purposes of this sample, you will use the portlet session to set an attribute the first time the method is invoked and avoid referencing the property broker for successive method invocations. Example 27-4 Obtaining a reference to the property broker service
public ActionForward execute(ActionMapping mapping, ActionForm form, PortletRequest request, PortletResponse response) throws Exception { PortletSession session = request.getPortletSession(true); if (session.getAttribute("INIT")==null) { System.out.println("obtaining a reference to the property broker services ======"); session.setAttribute("INIT","INIT"); try { Context ctx = new InitialContext(); PortletServiceHome serviceHome = (PortletServiceHome)ctx.lookup("portletservice/com.ibm.portal.propertybroker.service.PropertyBrokerService"); pbService = (PropertyBrokerService)serviceHome.getPortletService(com.ibm.portal.propertybroker.service.PropertyBrokerService.class); pbServiceAvailable = true; } catch(Throwable t){ System.out.println("Echo portlet could not find property broker service!"); } } System.out.println("executing action======"); UserBean userBean = (UserBean) form; if (userBean.getInmsg()== "") userBean.setInmsg("No message"); else userBean.setInmsg("Message received: " + userBean.getInmsg()); ActionForward forward = mapping.findForward("result"); return forward; }
![]()
5. Save the EchoSource.java file.
ibm.com/redbooks