Access Portlet Session as Anonymous User In WebSphere Portal

By default, WebSphere Portal does not enable session tracking for anonymous users, hence the following request.getPortletSession() code snippet will always return null for anonymous users:

private static SideNavigationPortletSessionBean getSessionBean(PortletRequest request) {
 PortletSession session = request.getPortletSession();
 if (session == null)
 return null; // <-- will always return null for anonymous users
 SideNavigationPortletSessionBean sessionBean = (SideNavigationPortletSessionBean) session.getAttribute(SESSION_BEAN);
 if (sessionBean == null) {
  sessionBean = new SideNavigationPortletSessionBean();
  session.setAttribute(SESSION_BEAN, sessionBean);
 return sessionBean;

And this set the team wondering on how does the out of the box IBM portlets like Sitemap portlet (PA_SearchSitemapPort.ear) transports the information to JSP? We de-compiled the sitemap.jar and found out that they are transporting the information through the render parameters which is something that matches the paragraph found in Accessing the portlet session on the anonymous page:

If you need to enable session tracking across requests for non-authenticated users, you can do so by setting the public.session parameter in the portal Navigator service configuration or by setting the container run time option in a JSR 286 portlet deployment descriptor. Note that this may result in significantly increased memory consumption. … Instead of using these options, portlets that need to maintain interaction state even for non-authenticated users should use render parameters to keep this information instead of the portlet session, as recommended by the Java Portlet Specification.


How to pass information using render parameters?

  1. Under doView method, set the information to RenderRequest’s parameters
    public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
     // ...
     request.setAttribute("rootPage", rootPage);
     // Invoke the JSP to render
     PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(JSP_FOLDER + VIEW_JSP);
     rd.include(request, response);
  2. At JSP, retrieve the information as follows:
    <jsp:useBean id="rootElement" class="" scope="request"/>
     PageElement rootPage = (PageElement)request.getAttribute("rootPage");
     if (rootPage != null) {
      // logic ...

How to Merge PDF Files with PDFBox in Java?

Merging PDF files in java is made easier with Apache PDFBox.

The codes below illustrate how to sort and merge all PDF files found in a particular directory according by their last modified date:

import java.util.Arrays;
import java.util.Comparator;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.util.PDFMergerUtility;

public class test {
 public static void main(String[] args) throws IOException, COSVisitorException {
  int maxPdf = 1000; // use this to troubleshoot java/lang/OutOfMemoryError exception
  String pdfDirPath = "C:\\circulars_and_notices\\pdfs\\port_marine_notices";

  File pdfDir = new File(pdfDirPath);
  if (pdfDir.isDirectory()) {
   // proceed to crawl thru the folder and merge the pdf according to last mod date
   File[] pdfs = pdfDir.listFiles();
   int cnt = pdfs.length;

   if (cnt > 0) {
    // sort the pdfs by last mod date in desc order
    Arrays.sort(pdfs, new Comparator() {
    public int compare(File f1, File f2) {
     return, f1.lastModified());

    if (maxPdf != 0 && maxPdf < cnt) {
     cnt = maxPdf;

    // start add merging sources
    PDFMergerUtility pdfMerger = new PDFMergerUtility();

    // set destination

    // add in pdf source
    for (int i = 0; i < cnt; i++) {
     File file = pdfs[i];

    // merge pdfs

   } else {
    System.out.println("Target directory is empty.");
  } else {
   System.out.println("Target is not a directory (" + pdfDirPath + ").");

The codes above should works fine in most scenarios. But if you are merging large PDFs files like in my case, then the chances of encountering “java/lang/OutOfMemoryError” exception is high. Of course a quick solution is to increase heap size but this will only be a temporary solution.

Lucky for us, PDFBox offers another alternative way of merging PDFs by storing the PDF streams into a temp file. See below code for illustrations:

// codes

[21/4/2014] We have encountered org.apache.pdfbox.exceptions.COSVisitorException: java.lang.NullPointerException when we tried to merge large number of PDFs (<850 pdfs) at once. Hence we decided to revise our codes by merge our PDFs in smaller quantities before merging them as one.

How to Access SharePoint Web Services via Javascript?

Been tasked by my boss with another tight deadline project (understand client’s requirement and developed 2 mobile app within 1 month). Both of the apps required to read data from SharePoint Web Services using Javascript.

Before we proceed, it is important to know what are the types of SharePoint web services that are available to us? Click here for a list of SharePoint services.

Next, we need to understand how to read and call web services’ methods. In the example below, we will demonstrate how we derived and constructed our SOAP message to retrieve list’s items (API: List.GetListItems method):

  1. Always wrapped our SOAP message block with the following header and footer:

    <soapenv:Envelope xmlns:soapenv=''>
     <soapenv:Body xmlns=''>


  2. Construct the web service’s method and parameters exactly as shown in MSDN. In our example, we will input listName and sort the result according to the title:
        <FieldRef Ascending='TRUE' Name='Title'/>

Lastly wrapped the SOAP message that you form above and sent it thru using jQuery.ajax method (example like the one below):

 type: "POST",
 url: url /* the url will be as stated in MSDN Web Reference, for all list related services, it will be http://<Site>/_vti_bin/Lists.asmx*/,
 data: q.join("") /* the soap message that we have construct earlier*/,
 contentType: "text/xml; charset=utf-8",
 dataType: "html" /* can be xml */,
 success: function(xdata){
 error: function(a,b,c){
  result.css("color","red").html("Unable to connect ("+c+").");

WebSphere Portal: AuthorizationException Is Thrown While Calling Workspace getById Method

Below looks like an innocent block of codes written to retrieve WCM items:

 Content content = null;
 Workspace ws=WCM_API.getRepository().getWorkspace();
 DocumentIdIterator iter = ws.findByPath(path, Workspace.WORKFLOWSTATUS_ALL);

 if(iter.hasNext()) {
  DocumentId docId = iter.nextId();
  if (docId.isOfType(DocumentTypes.Content)) {
   content = (Content)ws.getById(docId,true,true);

But as soon as you try to retrieve WCM items with “User” access, an “AuthorizationException” will be thrown (even though you are able to view the items in WCM Authoring Portlet). This is because getById method by default required min “Contributor” rights.

In order to resolve the issue, call Workspace.useUserAccess(true) before you call the getById method.

WebSphere Portal: Customize Authoring Template’s Elements With JSP

WebSphere Portal allows you to customize some of the Authoring Template’s elements using “Custom JSP” field (usually we would use TEXT element type for out of the box customization). This feature will comes in handy when our clients have special requirements which Authoring Template can’t fulfil. Naming a few examples that we have encountered:

  • “Can you display the email’s WCM url in the Authoring Template (refers to the email that is send by WCM Workflow Email Action)?”
  • “Can we have a Color picker function like the JSColor (”
  • “Can we have a dynamic product list where we can sort using drag and drop action, as we already have this feature in our old system?”
  • and so on…

Anyway, there are currently 2 ways to reference custom jsp:

PA_WCM_Authoring_UI and  PA_WCMLRingPortJSR286 can be found at <wp_profile>\installedApps\<cell> (example: C:\IBM\WebSphere\wp_profile\installedApps\WPS80Cell).

  • Stored the jsp within the respective application folders (like PA_WCM_Authoring_UI and PA_WCMLRingPortJSR286) and reference the custom jsp by /jsp/html/xxx.jsp.
  • *Our Preferred Method* Or stored the jsp in one of the application folders and reference it using the following path: contextPath;<jsp path>.In our case, we would usually create a new folder called “custom” in PA_WCM_Authoring_UI folder and deposit our custom jsp there. We find this solution neater and easier to maintain. Then we would reference the custom jsp as >  “/wps/PA_WCM_Authoring_UI;/jsp/html/custom/xxx.jsp“.

In order to fully replicate existing Authoring Template’s behaviour (Read, Edit and Render modes), usually we would need to create at least 2 custom jsp (for Read and Edit modes) and save them into the PA_WCM_Authoring_UI folder. In some rare cases, we usually do not need Render mode to String.split the result in Presentation Temple.

Below is a simple example of a color picker example (I have omit out the colour selection feature as it makes the post unwanted draggy):

Step 1: Create AT-ColourSelection_EditMode.jsp for Edit Mode

<%@ page import=""%>
    // Retrieve the custom item bean
    CustomItemBean customItem = (CustomItemBean) request.getAttribute("CustomItemBean");

    // Initialize variable
   String fieldName = customItem.getFieldName();
   String value = (String)customItem.getFieldValue();

    // Set the name of the submit function
    customItem.setSubmitFunctionName(fieldName + "_mysubmit");

Color : <input id="<%=fieldName%>_txtColor" type="text" value="<%=value%>"></input>

<script language='Javascript'>
<!-- Submit function for multifield, collapses fields into one -->
function <%=fieldName%>_mysubmit()
document.getElementById("<%=fieldName%>").value = document.getElementById('<%=fieldName%>_txtColor').value;

Step 2: Create AT-ColorSelection_ReadMode.jsp for Read Mode.
The custom jsp should just contains codes that are sufficient for reading purpose.

<%@ page import=""%>
    // Retrieve the custom item bean
    CustomItemBean customItem = (CustomItemBean) request.getAttribute("CustomItemBean");

    // Initialize variable
   String fieldName = customItem.getFieldName();
   String value = (String)customItem.getFieldValue();

Color : <input id="<%=fieldName%>_txtColor" type="text" value="<%=value%>"></input>

Step 3: Add in a Text element in Authoring Template and set the Custom JSP path


More Examples:

WebSphere Portal: Setting up SMTP for WCM Workflow

Do the following to configure your SMTP server for WCM workflow notification:

  1. Log in to WebSphere Integrated Solutions Console (https://<server ip>:<port:10032>/ibm/console).
  2. Go to “Resource Environment > Resource Environment Providers” and click on “WCM WCMConfigService.
  3. Click on “Custom properties” link.
  4. Add in the following properties:
    1. connect.connector.mailconnector.defaultsmtpserver = Smtp server ip / hostname (
    2. connect.connector.mailconnector.defaultfromaddress = Default From email address (
    3. connect.connector.mailconnector.defaultreplytoaddress = Default Reply-to Field ( *optional*
  5. If you are using a secure SMTP server, add in the following properties as well:
    1. connect.connector.mailconnector.defaultusername = Username
    2. connect.connector.mailconnector.defaultpassword = Password
  6. If your SMTP server is running other than port 25, add in “connect.connector.mailconnector.defaultsmtpport” and state the port.
  7. Restart portal.

WebSphere Portal: How to get HttpServletRequest and HttpServletResponse from Portlet Request?

Like most portlet developments, there are some scenarios where you might need to retrieve HttpServletRequest and HttpServletResponse from Portlet Request (RenderRequest/RenderResponse/ActionRequest/ActionResponse etc).

In WebSphere Portal, there is a PortletUtils utility class that provides the method you need:


// call the respective methods to get HttpServletRequest/HttpServletResponse you need

[10/9/2014]: As highlighted by Stefan Schmitt, the above mentioned method is not supported by IBM. We found out about this class when we de-compiled “Sitemap” portlet. There is 7 or more PortletUtils types if you viewed it from your RAD “Quick fix”, use it at your own discretion.

How to Create WebSphere Portal Theme

Disclaimer: This article merely follows the steps listed in Developing Themes for WebSphere Portal 8.5 with bits and pieces of my notes. My example will fall short in creating a new set of skin and layout. There are other additional things you might want to consider for example should you enable friendly url in the portal?

Step 1: Copy The Static Resources for Your Theme:

  1. You will need a WebDAV client for this exercise. IBM recommended WebDrive (commercial) or AnyClient (free) as WebDAV client but we still prefer Cyberduck (always had a thing with rubber duck).
  2. Connect to http://<server ip>:<port>/wps/mycontenthandler/dav/themelist via WebDAV client.
    Note: in our screenshot, you might notice that we are pointing to “/web/” instead of the default “/wps/“, please ignore that as we are trying out other configuration at the same time. By default, it will be pointing to “/wps/”.
  3. Download ibm.portal.85Theme to your local disk and rename the folder to your custom theme’s name (like CorporateTheme).
  4. Locate in the metadata folder. Change the “title” value  to your custom theme’s display title.
    (if you intended to support locale other than en, please edit respective locale files accordingly)
  5. Edit the file and replace Portal8.0 in “” value to your new custom theme’s name (As set in point 3).\:fs-type1/themes/<custom theme name>/layout-templates/2ColumnEqual/
  6. Upload your new custom theme back to http://<server ip>:<port>/wps/mycontenthandler/dav/themelist.
  7. Go to Administration page (Administration > Portal User Interface > Themes and Skins) to verify that your new custom theme has been successfully deployed. The theme’s display name should looks exactly as set in the file.
What we have done so far?
We have successfully replicate the theme's static resources (as in the "frontend"), but the new theme is still referencing the default theme's dynamic resources (css/js/navigation, page menu, footer etc). 

To understand the static resources portion, go via WebDAV to http://<server ip>:<port:10039>/wps/mycontenthandler/dav/fs-type1/themes/<custom theme>/nls and play around with theme_en.html file. (depending on client's requirements, sometimes the theme customization can be stop at this stage)


Step 2: Copy The Dynamic Resources for Your Theme

  1. Open your Eclipse or IBM® Rational® Application Developer and make sure Java EE developer tools add-on is installed.
    (note that the screenshots will varies between different RAD versions, I am currently using RAD 9.0)
  2. Click on File > New > Web Project.
  3. Key in your custom theme’s name. Select “Simple” as Project Templates and “Java EE” as Programming Model.
  4. Under Deployment tab, select “2.4” as Web module version and checked “Add project to an EAR“.
    Click on the “Finish” button.
  5. Go to <portal_server_root>\theme\wp.theme.themes\default85\installedApps\DefaultTheme85.ear\DefaultTheme85.war and copy the following folders to your web project’s WebContent folder:
    • skins folder
    • themes folder
  6. Go to <portal_server_root>\theme\wp.theme.themes\default85\installedApps\DefaultTheme85.ear\DefaultTheme85.war\WEB-INF and copy the following files/folders to your web project’s WEB-INF folder:
    • decorations.xml
    • tld folder
  7. Under the same DefaultTheme85.war\WEB-INF folder, make a copy of plugin.xml and edit the following references:
    • wp_dynamicContentSpots_85” to your custom theme references (“wp_dynamicContentSpots_corporateTheme“)
    • All <title> and <description> tags to match your custom theme’s title and description
    • all “default85” to your custom theme references (“corporateTheme“)
    • More examples: IBM: Modify the dynamic resource references for your theme.
  8. Copy the edited plugin.xml to your web project’s WEB-INF folder. Remember to constant update the plugin.xml whenever you have add in new dynamic resources.
  9. Right-click your custom EAR project and export it as EAR file.
  10. Log on to the WebSphere® Integrated Solutions Console (https://<server ip>:10041/ibm/console/logon.jsp) and go to Applications > Application Types > WebSphere enterprise applications.
  11. Click on the Install button and select your exported custom EAR file.
  12. Select Fast Path, expand Choose to generate default bindings and mappings, select Generate Default Bindings, and click Next button.
  13. Click on the Next button again (unless you wish to edit the default installation options).
  14. Checked the custom module and click on the Apply button. Click on the Next button.
  15. Click on the Finish button.
  16. When the EAR file is done installing, click Save directly to the master configuration link.
  17. Checked the custom application and click on the Start button.
  18. If the entire process is successfully, you should be able to find your new dynamic resources at <wp_profile_root>\installedApps\<cell>\<CustomThemeEAR.ear>\<CustomTheme.war> folder.
What we have done so far?
We have successfully replicate a new set of dynamic resources for our custom theme (as in the "backend codes"). But unlike Step 1, we are unable to test the changes immediately as our custom theme is still referencing the default theme's dynamic resources. Hence, this brings us to the 3rd step!


Step 3: Modify The Dynamic Resource References For Your Theme:

  1. Connect to http://<server ip>:<port>/wps/mycontenthandler/dav/themelist/<custom theme> via WebDAV client.
  2. Go to “profiles” folder and replace all “wp_dynamicContentSpots_85occurrences  in profile_*.json files to the new custom theme reference that you have defined in the plugin.xml (“wp_dynamicContentSpots_corporateTheme“).
  3. At the <custom theme>/nls folder, edit theme_en.html and replace all “85theme” occurrences to the new custom theme reference you have defined in the plugin.xml (“corporateTheme“). For example dyn-cs:id:85theme_head becomes dyn-cs:id:corporateTheme_head.
  4. Restart WebSphere Portal (even though I suspect that this step is not necessary).
What we have done so far?
We have successfully modify our custom theme to reference the new set of dynamic resources which we have created in Step 2. To verify, make changes to your dynamic resources jsp and restart WebSphere Portal, the changes should reflect.


Step 4: Enable Development Mode

To prevent restarting WebSphere Portal whenever you have make changes to the dynamic resources,  locate ibm-web-ext.xmi under web project’s WEB-INF folder. Add in the following jspAttributes under <webappext:WebAppExtension> tag and re-deploy your EAR file (for me, I would prefer to un-install the original EAR application instead of doing a direct update).

 <jspAttributes name="reloadEnabled" value="true"/>
 <jspAttributes name="reloadInterval" value="1"/>

The ibm-web-ext.xmi will looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<webappext:WebAppExtension xmi:version="2.0" xmlns:xmi="" xmlns:webappext="webappext.xmi" xmi:id="WebAppExtension_1409130625729" reloadInterval="3" reloadingEnabled="true" additionalClassPath="" fileServingEnabled="true" directoryBrowsingEnabled="false">
 <webApp href="WEB-INF/web.xml#WebApp_ID"/>
 <jspAttributes name="reloadEnabled" value="true"/>
 <jspAttributes name="reloadInterval" value="1"/>


Another tip! Most of the time there is a need to hide WebSphere Portal default toolbar and header from the public (anonymous users). As highlighted in red:

Use <r:dataSource> to call dynamics resource references in JSP (for example, call <r:dataSource uri=’dyn-cs:id:corporateTheme_toolbar’ escape=”none”/>  to call <a rel=”dynamic-content” href=”dyn-cs:id:corporateTheme_toolbar”></a>). Below is the actual code snippet that I have implement for one of my clients:

<%@ page session="false" buffer="none" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib uri="" prefix="c" %>
<%@ taglib uri="" prefix="fn" %>
<%@ include file="../includePortalTaglibs.jspf" %>
<portal-logic:if loggedIn="yes">
<header role="banner">
 <r:dataSource uri='dyn-cs:id:corporateTheme_toolbar' escape="none"/>
 <div class="wpthemeHeader">
  <div class="wpthemeInner">
   <div class="wpthemeLogo wpthemeLeft">
    <span class="wpthemeAltText">IBM WebSphere Portal</span>
   <a rel="dynamic-content" href="dyn-cs:id:corporateTheme_defaultTopNav"></a>
 <div class="wpthemeBanner">
  <div class="wpthemeBannerInner">
   <div class="wpthemeInner">
    <r:dataSource uri='dyn-cs:id:wp_search_dynspot' escape="none"/>
    <r:dataSource uri='dyn-cs:id:corporateTheme_commonActions' escape="none"/>
    <div class="wpthemeClear"></div>




  1. Theme Customization 8.0 Quick Reference
  2. Developing Themes for WebSphere Portal 8.5

WebSphere Portal: Theme Development Useful References

WebSphere Portal API

WebSphere Portal Library Tags | link
Our trusty library tags since WebSphere Portal 6.0 (maybe earlier)!
(The tags mentioned are only for use in theme and skin JSPs. Do not use portal tags in portlet JSPs.)

  • <portal-core/> tags – Used to provide portal core functionality such as entering the main render flow as well as URL-related aspects of the page.
  • <portal-dynamicui/> tags – Used to enable dynamic user interface features such as closing dynamic portlets and pages.
  • <portal-fmt/> tags – Used to provide enhanced portal formatting capabilities.
  • <portal-logic/> tags – Used to provide conditional logic.
  • <portal-navigation/> tags – Used to implement navigation tasks such as generating URLs and traversing the portal navigation model.
  • <portal-showtools/> tags – Used to provide administrative tools on the theme and skin level.
  • <portal-skin/> tags – Used to build a portlet title bar as well as make various functional icons available in the title bar.
  • <portal-theme-ext/> tags – Used to provide extended functionality to enhance the portal themes.

WebSphere Portal EL Beans | link
Since WebSphere Portal 7.0, Expression Language (EL) beans has been added for easy access to WebSphere Programming models. The beans are accessed in the global wp namespace. For more information on specific models, refer to the Portal 8.5 SPI Javadoc external link. Examples of the common used beans:

  • ${wp.metadata[node]}
  • ${wp.node.contentNode}
  • ${wp.identification[node]}
  • ${wp.node.metadata['metaDataKey']}
  • ${wp.navigationModel}

Missing from the documentation:

  • “INTERNALURL” is missing from ContentNodeBean.contentNodeType documentation.

WebSphere Portal EL Available Variables (WebSphere Portal 8.0)
Do remember to check out bootstrap.jspf before init your variables, as some of the useful variables have already been initialized by the jsp fragment. Examples:

  • ${pageTitle} – current page’s title
  • ${currentNavNode} – current page’s navigation node
  •  ${aggMD} – an aggregated metadata of the current page
  • ${deviceClass} – device class, values available [<empty string>/tablet/smartphone]

Setting Dynamic Content Spot Mapping with mvc:URI | link
The mvc:URI scheme is a special URI format that accesses different resources, depending on the device class. This scheme is used by the Portal 8001 theme in the definition of several dynamic content spots. Example of possible combinations:

  • mvc:res:/hello.jsp: Uses a single default URI.
  • mvc:res:/hello.jsp,smartphone@res:/hello_smartphone.jsp: Uses res:/hello.jsp as the default URI and res:/hello_smartphone.jsp as the URI for smartphones.
  • mvc:res:/hello.jsp,smartphone/tablet@res:/hello_mobile.jsp: Uses res:/hello.jsp as the default URI and res:/hello_mobile.jsp as the URI for smartphones and tablets.
  • mvc:res:/hello.jsp,smartphone@,tablet@res:/hello_tablet.jsp: Uses res:/hello.jsp as the default URI and res:/hello_tablet.jsp as the URI for tablets. No URI is assigned for smartphones.

2014 – Big Leap Forward


Being forced to wear the bunny’s ear T.T

Other than hitting the big 30, it is also the year which we will be receiving our flat and start preparing for our marriage in 2015. Another step closer in starting out a family on our own! A rough schedule for us to follow:

  • Jan – Apr: We will be busy brainstorming for renovation ideas and things to look out for (especially hidden renovation costs).
    Our research sources: Interior Design Magazine, Blogs and Friends (House-warming)!
  • May – Jun: Source for quotations based on our design and decided if we should go for ID or manage the contractors on our own.
  • Jul – Sep: Should be collecting our keys during this period, perhaps we can use this time to plan for our wedding! Again our main wedding research sources will be: Wedding Magazine, Blogs and Friends!
  • Nov – Dec: Renovation completed! *random estimation*

Side Note for Me:
While we will be busy with our renovation and marriage’s preparation, we should not neglect spending time with our parents. Being 30 would also means that our parents is in their last stage of life. As one aged, we (everyone) tended to get stubborn and forgetful. Talking to us suddenly becomes a frustrating affair.

So before we get angry with your parents, take a deep breath and think.

Have your parents ever neglect you when you are still a baby (while you wake them in the middle of the night for milk)? How many times your parents have been putting up with your stubbornness while they are just trying to teach you the right values?

Or how many times they have been there for you when you need help? Now this is the time where they need you the most, don’t let them down. Lastly think of the quote below and reflect upon yourself whenever you get frustrated:

Love your parents and treat them with love and care. For you will only know their value when you see their empty chair.

Empty Rocking Chair on a Deck