Programming in HATS Portlets

Note:
There is no bidirectional support for standard portlet Integration Objects, global variable overrides, portlet communication, Web Services for Remote Portlets, and Light pen (attention) and Light pen (selection) host components.

This chapter assumes that you are familiar with developing portlets for WebSphere® Portal. The HATS User's and Administrator's Guide explains how to create HATS portlets and how to convert HATS Web projects into portlet projects. You must have WebSphere Portal Toolkit installed on your HATS machine. With Portal tools, you can create, manage, deploy, and run portlets in a Rational® SDP environment. WebSphere Portal Toolkit is installed with Rational SDP. When installing Rational SDP, select the Portal tools check box.

You can develop HATS portlets that comply with the IBM® Portlet API, or with the standard Java™ Portlet Specification API (JSR 168), hereafter referred to as the standard portlet API. HATS portlets that comply with the standard portlet API (JSR 168) are referred to as standard portlets.

Portlets can be targeted for WebSphere Portal v6.0 or v6.1. Standard (JSR 168) portlets targeted for either WebSphere Portal v6.0 or v6.1 can also run on WebSphere Application Server v6.1 or v7.0.

The Portal API documentation (Javadoc) is installed with the toolkit and contains information that is useful in performing the tasks that are described in this chapter. You can use the Portal API in business logic or JSPs. A detailed example of using HATS business logic with the Portal API, titled Portlet messaging with IBM Rational Host Access Transformation Services (HATS), can be found on the HATS Information Center.

IBM portlets

The following are specific to IBM portlets.

Adding sample code to new business logic

For some types of portlet customization, you must create business logic classes. When you use the Create Business Logic wizard in HATS Toolkit, you will see a check box labeled Create portlet sample methods. If you select this check box, HATS creates sample methods related to portlet communications and security in your business logic class. These methods are identified in the appropriate sections of this chapter.

Using security

If you are using a credential vault with your WebSphere Portal, you can configure your HATS portlets to work with the credential vault. HATS provides a Web Express Logon plug-in called WebSphere Portal Credential Vault Credential Mapper. This plug-in appears in the Add Credential Mapper plug-in window only for a portlet project. This plug-in retrieves a passive user-password credential from a vault slot whose name is specified using the single plug-in parameter SlotID. The actual vault slot ID that is used is the slot ID concatenated using spaces with the host name, then the application name. The three elements of the slot ID are encoded to replace spaces with underscores. To see how this slot ID is generated, refer to the sample credential vault business logic methods. These methods are added to a new business logic class when you select the Create portlet sample methods check box.

You are responsible for creating and populating the vault slot for your users. The Web Express Logon plug-in can be used directly with credentials created using the business logic setUserCredential() method, because it observes the same naming convention for the slots. You can populate the vault slot with credentials that are specified in your business logic or retrieved from another source. If you want to use the Portal user ID, you can retrieve it using the WebSphere Portal Network Security plug-in. This plug-in appears in the Add Network Security plug-in window only for a portlet project.

As described in Creating plug-ins for Web Express Logon, Web Express Logon uses two types of plug-ins, Network Security plug-ins and Credential Mapper plug-ins. Any of the Network Security plug-ins that are supplied with HATS can be used in a HATS portlet. Table 4 lists some possible combinations of plug-ins you can use in your portlet:

Table 4. Plug-in combinations
Network Security plug-in Credential Mapper plug-in
WebSphere Portal NS plug-in Any supplied or custom CM plug-in or WebSphere Portal Credential Vault CM plug-in
None WebSphere Portal Credential Vault CM plug-in
Custom NS plug-in Custom CM plug-in

The following steps are an example of how you can add Web Express Logon capability to your portlet. Add this logic to the Start event for your HATS portlet.

When a user opens the portlet, check a global variable to determine whether the user's host credentials have already been supplied.

  1. If the host credentials have already been supplied, show the user the first screen to be displayed after authentication. This might be the screen that appears at the end of the Web Express Logon logon macro.
  2. If the host credentials have not already been supplied, use the getUserCredential() method to request the user's credentials from the vault.
    1. If the credentials are received successfully (the method does not return null), do the following:
      1. Set the global variable to show that the user's host credentials have been supplied.
      2. Run the Web Express Logon logon macro.
    2. If getUserCredential() returns null, do the following:
      1. Present a sign-on screen to request the user's information. This can be a transformed host screen or an HTML page you have created for this purpose.
      2. Store the input in global variables and add it to the vault.

Extending the Entry portlet

One way to add function to your HATS portlet is by extending the Entry portlet. For example, you might want to extend it in order to have your portlet listen for messages, or to exchange properties as a cooperative portlet. To extend the Entry portlet you must create a new class file. Follow these steps:

  1. Click File > New > Java > Class file. Your new class must extend com.ibm.hats.runtime.EntryPortlet.
  2. Expand your project and the WEB-INF folder. Open the web.xml file in the Web deployment descriptor editor. On the Servlets tab, select EntryPortlet in the Servlets and JSPs section, then click Browse in the details sections for the Servlet class field. Select the class you created in step 1, and save the descriptor.
  3. Extend any of the following methods to provide custom function. Right click in the source and select Override/Implement methods. You must call the super() when overriding any of these methods. Refer to the WebSphere Portal Javadoc for more information.
  4. Add one of the following interfaces. Refer to the WebSphere Portal Javadoc for more information.

Portlet messaging

Portlets can send messages to one another. A message can be directed toward a particular portlet or broadcast to all portlets. Follow the steps in this section to enable your portlet to send or receive messages.

Sending messages

Follow these steps to send messages from your HATS portlet:

  1. Create new business logic. Right-click in the HATS Project view of the HATS Toolkit, and select New HATS > Business Logic. Select the Create portlet sample methods check box. Use one of the sample functions: broadcastPortletMessage to broadcast a message to all listening portlets, or sendPortletMessage to direct a message to a specific portlet.
  2. Choose a screen customization or application event that you want to use to trigger the message.
  3. Create a prepresentation block in the screen customization or application event. Add an execute business logic action to this block to execute the business logic you just created.

Receiving messages

To receive messages, you must extend the Entry portlet, as described in Extending the Entry portlet. Your custom class must implement the org.apache.jetspeed.portlet.event.MessageListener interface. Implement the corresponding method. When you retrieve the information from the message, store it in a shared global variable so it can be accessed in a normal HATS fashion, or used in a screen recognition. A sample method follows:

public void messageReceived(MessageEvent event) throws PortletException {
	PortletRequest request = event.getRequest();
	PortletSession session = request.getPortletSession();
	DefaultPortletMessage dpm = (DefaultPortletMessage) event.getMessage();
	ClientSpecificInfo csi = 
		ClientContainer.getInstance().accessClient(session.getId());
	if (csi == null) {
		System.out.println("mesg receiver can not access csi");
		return;
	}
	Hashtable gvs = csi.getGlobalVariables();
	IGlobalVariable gv = new GlobalVariable("msg", dpm.getMessage());
	gvs.put("msg", gv);		
}	

Cooperative portlets

Cooperative portlets are portlets that exchange information through the property broker. Cooperative portlets can react to changes to other cooperative portlets on the page, resulting in a simultaneous update to multiple portlets with minimal user intervention. For more information, see the section, Cooperative portlets, in the WebSphere Portal Information Center at http://publib.boulder.ibm.com/infocenter/wpdoc/v6r1m0/index.jsp.

If you use IBM Click-to-Action implementation, wires can be created within the portlet by holding either CTRL or ALT while clicking the Click-to-Action icon and confirming through a dialog that the user wants to automate the current action choice. To successfully support the wiring, the name attribute of the <c2a:encodeProperty/> tag used to render the Click-to-Action icon must refer to an output property that has been registered with the property broker.

Implementing cooperative portlets requires three steps. These steps are described in the following sections.

Enabling Click-to-Action (C2A) between portlets involves configuring the following:

Modify the web.xml file of your HATS portlet application to wrap the portlet in a special class as follows:

<servlet id="Servlet_1">
   <servlet-name>EntryPortlet</servlet-name>
   <display-name>entry</display-name>
   <servlet-class>com.ibm.wps.pb.wrapper.PortletWrapper</servlet-class>
  <init-param>
	<param-name>c2a-application-portlet-class</param-name>
	<param-value>com.ibm.hats.runtime.EntryPortlet</param-value>
  </init-param>
  	<load-on-startup>-1</load-on-startup>
 </servlet>    

Publishing properties from your HATS portlet

To publish properties, you must first register the properties that you will publish. The publishPortletProperty method, which is created in new business logic classes when you select the Create portlet sample methods check box, always passes a HATS global variable. Then follow these steps:

  1. Choose one or more global variables that you will use to contain the properties that you will publish.
  2. Create a business logic class. Select the Create portlet sample methods check box.
  3. Use the registerProducedProperty sample method to register the names of all the global variables you plan to share.
  4. Add this business logic to the Start event for your application. Refer to HATS User's and Administrator's Guide for information about adding actions to events.

To publish the properties, follow these steps:

  1. Create a business logic class. Select the Create portlet sample methods check box.
  2. Use the publishPortletProperty sample method to publish a global variable. This method informs the property broker that the value of the property, which is contained in the global variable, has changed.
  3. Choose a screen customization or application event that you want to use to publish the global variable.
  4. Create a prepresentation block in the screen customization or application event. Add an execute business logic action to this block to execute the business logic you just created.

Receiving properties in your HATS portlet

Just as you must register the names of the global variables you plan to publish, you must also register the names of the global variables for which you want to receive updates. Follow these steps:

  1. Create a business logic class. Select the Create portlet sample methods check box.
  2. Use the registerConsumedProperty sample method to register the names of all the global variables for which you want to receive updates.
  3. Add this business logic to the Start event for your application. Refer to HATS User's and Administrator's Guide for information about adding actions to events.

To receive property update messages, you must extend the Entry portlet, as described in Extending the Entry portlet. Your custom class must implement the PropertyListener interface. Implement the corresponding method. You can retrieve properties from the array of Properties and modify your current set of global variables in much the same way as in the portlet messaging case.

Following is an example of tracing the incoming properties. You can use a similar technique to step through the received properties and trace them.

public void setProperties(PortletRequest arg0, PropertyValue[] pvs) {
		for(int i=0;i<pvs.length;i++) {
			PropertyValue pv = pvs[i];
			System.out.println("prop name: "+pv.getProperty().getName()+" type "
						+pv.getProperty().getType());
			System.out.println("with val: "+pv.getValue().toString());
		}
	}

Example of converting a HATS Model 1 application to an IBM portlet

If you have a HATS project application that is based on Model 1 pages, you can create a portlet with the same functionality. This approach requires that your application contain Integration Objects that are driven by Java Server Pages (JSPs). For information about HATS Model 1 Web pages see Create Model 1 Web pages in the HATS User's and Administrator's Guide.

Follow these steps to create the portlet:

  1. Create a new portlet project. Click File > New > Portal > Portlet Project.
  2. Name the project, accept the default values, and complete the wizard. For the purpose of these instructions, suppose you name the project model1. You might see a confirmation dialog for switching the perspective. You can select the perspective of your choice.
  3. Export all your Integration Objects to your new project by following steps 1 through 6 of Using an Integration Object in a Web container (custom servlet or JSP). The portlet project that you create in step 1 serves as the target project to which you will export the Integration Objects. The main portlet class referenced by portlet.xml is the custom servlet used to drive the Integration Objects. Any method calls used for initiating the HATS runtime should be added to the init method of the portlet class.
  4. Copy all of your Model 1 JSPs to your new project. For example, copy Input.jsp and Output.jsp to the Web Content/model1/jsp/html folder. Choose one of your JSPs to be the default view. This is the JSP that displays when the portlet is first accessed.
  5. Modify your portlet to emulate the Model 1 application. Locate the Java source file referenced by portlet.xml. This file extends the PortletAdapter class and is typically Java Source/model1/model1Portlet.java. Add the following to the class:
    public static final String HP_PAGE_TARGET   = "/model1/jsp/Output.jsp"; 
    public static final String DEFAULT_VIEW_JSP = "/model1/jsp/Input.jsp";
    	
    public static HashMap actionMap = new HashMap();
    static {
    	actionMap.put("action1","/model1/jsp/Output.jsp"");
    	actionMap.put("action2","/jsp/HPPage2.jsp");
    	actionMap.put("action3","/jsp/HPPage3.jsp");
    }
  6. Replace the doView method and the actionPerformed method with the following methods:
    public void doView(PortletRequest request, PortletResponse response) 
    				throws PortletException, IOException {
    		String jspTarget = (String) request.getAttribute(HP_PAGE_TARGET);
    		if(jspTarget==null) { //for a simple refresh
    			jspTarget = (String) 
    				request.getPortletSession().getAttribute(HP_PAGE_TARGET);
    		}
    		if(jspTarget==null) { //for the initial portlet view
    			jspTarget = DEFAULT_VIEW_JSP;
    		}
    		request.getPortletSession().setAttribute(HP_PAGE_TARGET,jspTarget);
    	      getPortletConfig().getContext().include(jspTarget, request, response);
    }
    public void actionPerformed(ActionEvent event) throws PortletException {		
    		String actionString = event.getActionString();		
            	PortletRequest request = event.getRequest();
    		if(actionMap.containsKey(actionString)) {		
    			request.setAttribute(HP_PAGE_TARGET,actionMap.get(actionString));
    		}        		
    	}
  7. Create an action name for every JSP to which information is submitted using a form, and add it to the actionMap as in the static block of code in step 5.
  8. Modify each JSP file.
    1. Strip the HTML, HEAD, and BODY tags so that each JSP is a fragment. Refer to the WebSphere Portal Coding Practices for fragment guidelines at http://www.ibm.com/developerworks/websphere/library/techarticles/portlet/portletcodingguidelines.html
    2. Replace the FORM tag's action attribute with the following JSP tag, replacing the value of the action attribute with the mapping you used in step 5.
      <portletAPI:createURI>
      	<portletAPI:URIAction name="action1" />
      </portletAPI:createURI>
    3. For every page that you add the portletAPI as described, add the <portletAPI:init/> tag before any other portlet tag processing.
  9. Remove the reference to hats.tld from the JSPs.
  10. Remove the reference to BasicIoError.jsp from the JSPs.
  11. Open the deployment descriptor located at Web Content/WEB-INF/web.xml for the portlet and add a period (.) at the beginning of the display name tag value. For example, change <display-name>model1</display-name> to <display-name>.model1</display-name>.

Standard portlets

The following are specific to standard portlets.

Using security

If you are using a credential vault with your WebSphere Portal, you can configure your HATS portlets to work with the credential vault. HATS provides a Web Express Logon plug-in called WebSphere Portal Credential Vault Credential Mapper. This plug-in appears in the Add Credential Mapper plug-in window only for a portlet project. This plug-in retrieves a passive user-password credential from a vault slot.

The following classes are provided to aid the access to the Portal Credential Vault for standard portlets.

The CredentialVaultHelper class has the following public methods. Note that the getInstance() method returns a unique instance of CredentialVaultHelper.

public static CredentialVaultHelper getInstance();
public static String generateSlotName(String vaultId,String hostDestination,String hostAppId);
public String getSlotId(PortletRequest portletRequest, String slotName, int slotType);
public void setCredential(String slotId,UserPasswordCredential credential,PortletRequest portletRequest);
public UserPasswordCredential getCredential(String slotId,PortletRequest portletRequest);

The UserPasswordCredential class has the following public methods.

public UserPasswordCredential();
public UserPasswordCredential(String user,char[] password);
public void setUser(String user);
public void setPassword(char[] password);
public void setPassword(String password);
public String getUser();
public String getPassword();

Refer to the HATS API References (Javadoc) in the HATS Information Center at http://publib.boulder.ibm.com/infocenter/hatshelp/v75/index.jsp for detailed information about the com.ibm.hats.portlet.cv.CredentialVaultHelper and com.ibm.hats.portlet.cv.UserPasswordCredential classes.

You are responsible for creating and populating the vault slot for your users. The Web Express Logon plug-in can be used directly with credentials created using the setCredential() method of the com.ibm.hats.portlet.cv.CredentialVaultHelper class, because it observes the same naming convention for the slots. The vault slot name can be generated using the generateSlotName() method of the com.ibm.hats.portlet.cv.CredentialVaultHelper class, where you pass in the plug-in parameter SLOT_ID, the host name, and the application name (use null if the application name is not applicable, for example, when connecting to an IBM i server). Note that the generated slot name is the SLOT_ID concatenated using spaces with the host name, then the application name. The three elements of the slot name are encoded to replace spaces with underscores. The actual vault slot ID can then be retrieved using the getSlotId() method of the com.ibm.hats.portlet.cv.CredentialVaultHelper class, where you pass in the PortletRequest, the slot name, and the SLOT_TYPE. Note that if the SLOT_TYPE is 2 or 3, the slot ID is equal to the slot name.

You can populate the vault slot with credentials that are specified in your business logic or retrieved from another source. If you want to use the Portal user ID, you can retrieve it using the WebSphere Portal Network Security plug-in. This plug-in appears in the Add Network Security plug-in window only for a portlet project.

As described in Creating plug-ins for Web Express Logon, Web Express Logon uses two types of plug-ins, Network Security plug-ins and Credential Mapper plug-ins. Any of the Network Security plug-ins that are supplied with HATS can be used in a HATS portlet. Table 5 lists some possible combinations of plug-ins you can use in your portlet:

Table 5. Plug-in combinations
Network Security plug-in Credential Mapper plug-in
WebSphere Portal NS plug-in Any supplied or custom CM plug-in or WebSphere Portal Credential Vault CM plug-in
None WebSphere Portal Credential Vault CM plug-in
Custom NS plug-in Custom CM plug-in

The following steps are an example of how you can add Web Express Logon capability to your portlet. Add this logic to the Start event for your HATS portlet. When a user opens the portlet, check a global variable to determine whether the user's host credentials have already been supplied.

  1. If the host credentials have already been supplied, show the user the first screen to be displayed after authentication. This might be the screen that appears at the end of the Web Express Logon logon macro.
  2. If the host credentials have not already been supplied, use the getCredential() method of the com.ibm.hats.portlet.cv.CredentialVaultHelper class to request the user's credentials from the vault.
    1. If the credentials are received successfully (the method does not return null), do the following:
      1. Set the global variable to show that the user's host credentials have been supplied.
      2. Run the Web Express Logon logon macro.
    2. If getCredential() returns null, do the following:
      1. Present a sign-on screen to request the user's information. This can be a transformed host screen or an HTML page you have created for this purpose.
      2. Store the input in global variables and add it to the vault.

Extending the Entry portlet

You can extend the HATS standard portlet to provide additional functions or to customize the portlet. For example, you can extend the portlet to provide connection parameter and global variable overrides.

To extend the standard Entry portlet you must customize the Java class file.

  1. Use the new Java Class wizard to create the new Java class that extends com.ibm.hats.portlet.Jsr168EntryPortlet.
    1. Click File > New > Java > Class file.
    2. Provide the package and the name of the new class. Make sure the Superclass field contains the value com.ibm.hats.portlet.Jsr168EntryPortlet.
  2. Modify the name of the portlet class in the portlet deployment descriptor.
    1. Open the portlet.xml file in the Portlet deployment descriptor editor.
    2. Replace the text in the <portlet-class>com.ibm.hats.portlet.Jsr168EntryPortlet</portlet-class> with the following: <portlet-class>myPackage.myClass</portlet-class>; where myPackage and myClass are values you entered in the new Java Class wizard above.

The following example shows how to provide connection parameter and global variable overrides with the extended portlet class:

  1. Edit the Java source file of the extended portlet class.
  2. Override the getInitParameters() method as follows:
    public Properties getInitParameters(IRequest request)
    {
      Properties initParams = new Properties();		
      initParams.setProperty(com.ibm.eNetwork.beans.HOD.Session.HOST, "129.12.11.2");
      initParams.setProperty(com.ibm.eNetwork.beans.HOD.Session.PORT, "623");
      initParams.setProperty("hatsgv_userName", "some user");
      initParams.setProperty("hatsgv_password", "xxxxx");
      initParams.setProperty("hatssharedgv_someVariable", "zzzzz");
      return initParams;
    }

Note:
If you set the connection parameter or global variable overrides through the extended portlet class and use the same overrides in Edit mode, the Edit mode settings override the settings in the extended portlet class.

You must also configure the project's security settings to allow overrides of your chosen connection parameters or global variables. To do this, use the Connection Parameter Overrides panel and the Global Variable Overrides panel in the Project Settings>Other tab. If you do not allow overrides in the security panels, then any overrides set by extending the portlet class or by using the portlet Edit mode are implicitly ignored.

Running Integration Objects

The processRequest() method is used to run Integration Objects in standard portlets and special considerations have to be made for Integration Object chaining.

For Integration Object chaining (see Integration Object chaining) the same connection must be used by all Integration Objects in the chain. When using the processRequest() method to run the Integration Object, the key that represents the connection for the Integration Object chain must be extracted from the first Integration Object in the chain and set on subsequent Integration Objects in the chain. The connection can be extracted from the first Integration Object using the getHPubLinkKey() method and set on subsequent IOs using the setHPubLinkKey().

The key representing the connection is passed across JSP as a parameter on the HttpServletRequest object by adding a hidden input field to a FORM as shown:

<INPUT TYPE="HIDDEN" NAME="<%CommonConstants.HPUB_LINK_KEY%>"VALUE="<%=FirstInChainIO.getHPubLinkKey()%>"/>

The subsequent JSP then retrieves it using the getParameter() method and sets it on the subsequent Integration Object as shown:

<% MiddleInChainIO.setHPubLinkKey((String)request.getParameter(CommonConstants.HPUB_LINK_KEY)); %>

When the Forward To URL action is used to pass the connection being used by the HATS Portlet to the Integration Object(s), the key representing the connection is saved in the CommonConstants.HPUB_LINK_KEY attribute of the PortletRequest object.

In this case, the user must edit the JSP that gets control from the Forward To URL Action to retrieve the key from the PortletRequest object and set it for the first Integration Object calling the setHpubLinkKey() method, as shown below:

<% ExampleIO.setHPubLinkKey((String)request.getAttribute(CommonConstants.HPUB_LINK_KEY)); %>

The following statements also have to be added to the JSP that gets control from the Forward To URL action, regardless of whether it's an input page that gathers the data required by the Integration Object, or an output page that presents the results after the Integration Object is run:

<%@ taglib uri="http://java.sun.com/portlet" prefix="portletAPI" %>
<portletAPI:defineObjects/>

If the JSP that gets control from the Forward To URL action is an input page, the application developer is also required to modify the FORM statement by replacing the use of the request and response objects with the portlet renderRequest and renderResponse objects as shown below:

<FORM NAME="iojsp_ExampleIOOutput" METHOD="POST"
ACTION='<%= renderResponse.encodeURL(renderRequest.getContextPath() + "/iojsp/ExampleIOOutput.jsp")%>'>

Common to IBM portlets and standard portlets

The following is common to both IBM portlets and standard portlets.

Adding JavaServer Pages to a portlet

If you copy a .jsp file from a non-portlet project into a HATS portlet project, you must convert it by right-clicking the file name and selecting Convert JSP for Portal. You can convert several .jsp files at a time by selecting them in the tree view. This menu item is available only if the Portal Toolkit has been installed and the .jsp is in a HATS portlet project and has not already been converted. If you select several .jsp files and one or more of the files have already been converted, they will be skipped.