Friday, June 24, 2011

Accessing Query String parameter in WebSphere Portal with Dynacache

1) Create a jar of below class

import com.ibm.websphere.cache.DistributedMap;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class ParameterFilter
implements Filter
{

public static final String PARAMETER_PREFIX = "param.";
public static final String DYNACACHE_NAME = "services/cache/catalog/parameters";
public static final Logger logger = Logger.getLogger(com/ibm/catalog/servlet/filter/ParameterFilter.getName());
private DistributedMap map;

public ParameterFilter()
{
map = null;
}

public void init(FilterConfig arg0)
throws ServletException
{
try
{
InitialContext ic = new InitialContext();
map = (DistributedMap)ic.lookup("services/cache/catalog/parameters");
ic.close();
}
catch(NamingException ne)
{
logger.log(Level.SEVERE, "NamingException error", ne);
}
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession();
Enumeration parms = httpRequest.getParameterNames();
if(logger.isLoggable(Level.INFO))
logger.log(Level.INFO, "Parameter prefix: param.");
while(parms.hasMoreElements())
{
String key = (String)parms.nextElement();
if(key != null && key.startsWith("param."))
{
String cleanKey = key.substring("param.".length());
StringBuffer sb = new StringBuffer(cleanKey);
String values[] = httpRequest.getParameterValues(key);
sb.append(".count");
map.put(sb.toString(), (new Integer(values.length)).toString());
for(int i = 0; i < values.length; i++)
{
sb = new StringBuffer(cleanKey);
sb.append(".");
sb.append((new Integer(i)).toString());
sb.append(".");
sb.append(session.getId());
map.put(sb.toString(), values[i]);
if(logger.isLoggable(Level.INFO))
logger.log(Level.INFO, (new StringBuilder("Parameter Filter: ")).append(sb.toString()).append(" -- ").append(values[i]).toString());
}

}
}
if(chain != null)
chain.doFilter(request, response);
}

public void destroy()
{
}

}
-------------------------------------------------------------------------------------
2)Create Dynacache
JNDI name: services/cache/catalog/parameters

3)Add the following code to the web.xml file:



<filter>
<filter-name>Parameter Filter
<filter-class>
com.ibm.catalog.servlet.filter.ParameterFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>
Parameter Filter
</filter-name>
<url-pattern>/myportal/*
</filter-mapping>
<filter-mapping>
<filter-name>
Parameter Filter
</filter-name>
<url-pattern>/portal/*
</filter-mapping>


---------------------------------------------------------------------

import com.ibm.websphere.cache.DistributedMap;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;

public class AccessManagerUtils
{

public static final String DYNACACHE_NAME = "services/cache/catalog/parameters";
public static final String PARAMETER_PREFIX = "param.";
private static final String EXTERN_PARAMETERS_GOTTEN = "ExternParametersGotten";
private DistributedMap parameterMap;
public static final Logger logger = Logger.getLogger(com/ibm/fs/bic/accessmanager/AccessManagerUtils.getName());

public AccessManagerUtils()
{
parameterMap = null;
parameterMap = getParameterMap("services/cache/catalog/parameters");
}

protected DistributedMap getParameterMap(String mapName)
{
DistributedMap dm = null;
try
{
InitialContext ic = new InitialContext();
if(logger.isLoggable(Level.INFO))
logger.log(Level.INFO, (new StringBuilder("Opening parameter cache with name: ")).append(mapName).toString());
dm = (DistributedMap)ic.lookup(mapName);
ic.close();
}
catch(NamingException e)
{
logger.log(Level.SEVERE, "NamingException while looking up the distributed map.", e);
}
return dm;
}

protected String getExternParameter(RenderRequest request, String name)
{
getDynacacheMultipleParameters(request);
StringBuffer key = new StringBuffer("param.");
key.append(name);
String values[] = (String[])request.getAttribute(key.toString());
if(values != null)
return values[0];
else
return null;
}

protected String[] getExternParameterValues(RenderRequest request, String name)
{
getDynacacheMultipleParameters(request);
StringBuffer key = new StringBuffer("param.");
key.append(name);
String values[] = (String[])request.getAttribute(key.toString());
if(values != null)
return values;
else
return null;
}

protected int getDynacacheSingleParameters(RenderRequest request)
{
PortletSession session = request.getPortletSession();
int parmCount = 0;
Set keys = parameterMap.keySet();
Iterator iter = keys.iterator();
if(request.getAttribute("ExternParametersGotten") != null || parameterMap.isEmpty())
return -1;
while(iter.hasNext())
{
String key = (String)iter.next();
int dot = key.indexOf('.');
if(dot > 0)
key = key.substring(0, dot);
String values[] = getDynacacheParameterValues(key, request.getPortletSession().getId());
if(values != null)
{
parmCount++;
StringBuffer sb = new StringBuffer("param.");
sb.append(key);
request.setAttribute(sb.toString(), values[0]);
session.setAttribute(sb.toString(), values[0]);
}
}
request.setAttribute("ExternParametersGotten", "done");
return parmCount;
}

private int getDynacacheMultipleParameters(RenderRequest request)
{
if(request.getAttribute("ExternParametersGotten") != null)
return -1;
int parmCount = 0;
Set keys = parameterMap.keySet();
for(Iterator iter = keys.iterator(); iter.hasNext();)
{
String key = (String)iter.next();
int dot = key.indexOf('.');
if(dot > 0)
key = key.substring(0, dot);
String values[] = getDynacacheParameterValues(key, request.getPortletSession().getId());
if(values != null)
{
parmCount++;
StringBuffer sb = new StringBuffer("param.");
sb.append(key);
request.setAttribute(sb.toString(), values);
}
}

request.setAttribute("ExternParametersGotten", "done");
return parmCount;
}

private String[] getDynacacheParameterValues(String key, String sessionId)
{
StringBuffer sb = new StringBuffer(key);
sb.append(".count");
String countStr = (String)parameterMap.get(sb.toString());
if(countStr == null)
{
sb = new StringBuffer(key);
sb.append(".");
sb.append(sessionId);
String value = (String)parameterMap.get(sb.toString());
if(value != null)
{
parameterMap.remove(sb.toString());
String values[] = {
value
};
return values;
} else
{
return null;
}
}
parameterMap.remove(sb.toString());
int count = Integer.parseInt(countStr);
ArrayList valList = new ArrayList(count);
for(int i = 0; i < count; i++)
{
sb = new StringBuffer(key);
sb.append(".");
sb.append(i);
sb.append(".");
sb.append(sessionId);
valList.add(parameterMap.get(sb.toString()));
if(logger.isLoggable(Level.INFO))
logger.log(Level.INFO, (new StringBuilder("Portlet parm: ")).append(sb.toString()).append(" -- ").append((String)parameterMap.get(sb.toString())).toString());
parameterMap.remove(sb.toString());
}

String values[] = new String[valList.size()];
for(int i = 0; i < values.length; i++)
values[i] = (String)valList.get(i);

return values;
}

}
------------------------------------------------------------------------

Accessing in portlets.



import java.io.IOException;
import java.io.PrintWriter;
import javax.portlet.*;


public class AccessManager extends GenericPortlet
{

public static final String JSP_FOLDER = "/_BIC_AccessManager/jsp/";
public static final String ACCESS_MANAGER_SERVLET = "/AccessManagerServlet";
public static final String VIEW_JSP = "AccessManagerView";
public static final String SESSION_BEAN = "AccessManagerSessionBean";
public static final String FORM_SUBMIT = "AccessManagerFormSubmit";
public static final String FORM_TEXT = "AccessManagerFormText";
private AccessManagerUtils utils;

public AccessManager()
{
utils = null;
}

public void init()
throws PortletException
{
super.init();
utils = new AccessManagerUtils();
}

public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException
{
response.setContentType(request.getResponseContentType());
utils.getDynacacheSingleParameters(request);
AccessManagerSessionBean sessionBean = getSessionBean(request);
if(sessionBean == null)
{
response.getWriter().println("NO PORTLET SESSION YET");
return;
} else
{
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, "AccessManagerView"));
rd.include(request, response);
return;
}
}
--------------------------------------------------------------------------------

Thursday, June 23, 2011

Portlet URL generation common methods. URL generation services

package com.ibm.wps.l2.urlspihelper.portletrequest;


import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.WindowState;
import javax.servlet.http.HttpServletRequest;

import com.ibm.portal.ModelException;
import com.ibm.portal.ObjectID;
import com.ibm.portal.content.ModifiableLayoutContainer;
import com.ibm.portal.navigation.NavigationNode;
import com.ibm.portal.navigation.NavigationSelectionModel;
import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.model.NavigationSelectionModelProvider;
import com.ibm.portal.portlet.service.model.PortletModelProvider;
import com.ibm.portal.portletmodel.PortletWindow;
import com.ibm.portal.state.Constants;
import com.ibm.portal.state.EngineURL;
import com.ibm.portal.state.PortletStateManager;
import com.ibm.portal.state.StateHolder;
import com.ibm.portal.state.URLFactory;
import com.ibm.portal.state.accessors.StateAccessor;
import com.ibm.portal.state.accessors.StateAccessorFactory;
import com.ibm.portal.state.accessors.portlet.PortletAccessorController;
import com.ibm.portal.state.accessors.portlet.PortletAccessorFactory;
import com.ibm.portal.state.accessors.portlet.PortletTargetAccessorController;
import com.ibm.portal.state.accessors.portlet.PortletTargetAccessorFactory;
import com.ibm.portal.state.accessors.portlet.SharedStateAccessorController;
import com.ibm.portal.state.accessors.portlet.TargetType;
import com.ibm.portal.state.accessors.selection.SelectionAccessor;
import com.ibm.portal.state.accessors.selection.SelectionAccessorController;
import com.ibm.portal.state.accessors.selection.SelectionAccessorFactory;
import com.ibm.portal.state.exceptions.StateException;
import com.ibm.portal.state.service.PortletStateManagerService;

/**
* A Helper class that is used to target other JSR168 portlets from a JSR168 portlet
* @author James Barnes
*
*/
public class PortletURLHelper {
private static PortletServiceHome psHome = null;
private static PortletServiceHome psHomeModel = null;
private static PortletModelProvider modelProvider = null;
protected static PortletServiceHome navSelHome = null;
private ModifiableLayoutContainer cont = null;

/**
* Private method to return the portletstatemanager
* This has to be requested on a per thread bases as it needs to get the manager
* based on the request and response
*
* @param request
* @param response
* @return PortletStateManager
* @throws StateException
* @throws NamingException
*/
private static PortletStateManager getPortletStateManager(PortletRequest request, PortletResponse response) throws StateException, NamingException {
PortletStateManager mgr = null;
if (psHome == null ){
Context ctx = new InitialContext();
psHome = (PortletServiceHome) ctx.lookup("portletservice/com.ibm.portal.state.service.PortletStateManagerService");
}
try {
PortletStateManagerService service = (PortletStateManagerService) psHome.getPortletService(PortletStateManagerService.class);
mgr = service.getPortletStateManager(request, response);
} catch (Exception ex) {
System.out.println("the portlet service was unable to be retrieved");
}
// you need to request the state manager on a per-thread basis
return mgr;
}

/**
* Private method to return the portletstatemanager
* This has to be requested on a per thread bases as it needs to get the manager
* based on the request and response
*
* @param request
* @param response
* @return PortletStateManager
* @throws StateException
* @throws NamingException
*/
private static PortletWindow getPortletWindow(PortletRequest request) throws StateException, NamingException {
PortletWindow pWindow = null;
if (psHomeModel == null ){
Context ctx = new InitialContext();
psHomeModel = (PortletServiceHome) ctx.lookup("portletservice/com.ibm.portal.portlet.service.model.PortletModelProvider");
}
try {
modelProvider = (PortletModelProvider) psHomeModel.getPortletService(PortletModelProvider.class);
pWindow = modelProvider.getCurrentPortletWindow(request);
} catch (Exception ex) {
System.out.println("the portlet window was unable to be retrieved");
}
// you need to request the state manager on a per-thread basis
return pWindow;
}

/**
* Generates a URL to a page, targetting that portlet, You can pass in params
* the Strings must be a string array
*

HashMap map = new HashMap();
String[] value1 = {"testthis"};
map.put("p2psample4_search_text", value1);

* The portletname, and params can be passed in as null and then only the page is targetted
* The saveState flag tells the url generator to either do an empty copy or a smart copy
* of the current state so things like min/max of a portlet are preserved or dropped
*
* Sample usage:
* String targetURLStr = PortletURLGenerator.generateUrl("test.jsf", "test.jsf.portlet", null, false, renderRequest, renderResponse);
*
* @param pageName
* @param portletName
* @param params
* @param saveState
* @param request
* @param response
* @return string of the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
String pageName,
String portletName,
HashMap params,
boolean saveState,
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {

final PortletStateManager mgr = getPortletStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
String finalUrl = "";

try {
final EngineURL url ;

if(saveState) {
url = urlFactory.newURL(Constants.SMART_COPY);
} else {
url = urlFactory.newURL(Constants.EMPTY_COPY);
}
// Set the page this URL should point to
final com.ibm.portal.state.accessors.selection.SelectionAccessorFactory selectionFactory = (com.ibm.portal.state.accessors.selection.SelectionAccessorFactory) mgr.getAccessorFactory(com.ibm.portal.state.accessors.selection.SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletAccessorController(portletName, url.getState());
// Set the render parameter
if(params != null) {
portletCtrl.getParameters().putAll(params);
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}
/**
* Generates a URL to a page, targetting that portlet, all so passing all params as public render params for that page
* the Strings must be a string array
*

HashMap map = new HashMap();
String[] value1 = {"testthis"};
map.put("p2psample4_search_text", value1);

* The portletname, and params can be passed in as null and then only the page is targetted
* The saveState flag tells the url generator to either do an empty copy or a smart copy
* of the current state so things like min/max of a portlet are preserved or dropped
*
* Sample usage:
* String targetURLStr = PortletURLGenerator.generateUrl("test.jsf", "test.jsf.portlet", null, false, renderRequest, renderResponse);
*
* @param pageName
* @param portletName
* @param params
* @param saveState this is a boolean to either save the state or not
* @param request
* @param response
* @return string of the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/

public static String generateUrlPublicParams(
String pageName,
String portletName,
HashMap params,
boolean saveState,
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {

final PortletStateManager mgr = getPortletStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
String finalUrl = "";

try {
final EngineURL url ;

if(saveState) {
url = urlFactory.newURL(Constants.SMART_COPY);
} else {
url = urlFactory.newURL(Constants.EMPTY_COPY);
}


// Set the page this URL should point to
final com.ibm.portal.state.accessors.selection.SelectionAccessorFactory selectionFactory = (com.ibm.portal.state.accessors.selection.SelectionAccessorFactory) mgr.getAccessorFactory(com.ibm.portal.state.accessors.selection.SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletAccessorController(portletName, url.getState());
// Set the render parameter
if(params != null) {
SharedStateAccessorController ssAccCtrl = portletAccessorFactory.getSharedStateAccessorController(SharedStateAccessorController.KEY_GLOBAL_PUBLIC_RENDER_PARAMETERS, url.getState());
ssAccCtrl.getParameters().putAll(params);
//portletCtrl.getParameters().putAll(params);
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* * Generates a URL to a page, targetting that portlet, You can pass in params
* the Strings must be a string array
*

HashMap map = new HashMap();
String[] value1 = {"testthis"};
map.put("p2psample4_search_text", value1);

* The portletname, and params can be passed in as null and then only the page is targetted
* The saveState flag tells the url generator to either do an empty copy or a smart copy
* of the current state so things like min/max of a portlet are preserved or dropped
*
* Sample usage:
* String targetURLStr = PortletURLGenerator.generateUrl(pageOid, portletWindowOid, null, false, renderRequest, renderResponse);
*
* @param pageOid
* @param portletName
* @param params
* @param saveState
* @param request
* @param response
* @return string of the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
ObjectID pageOid,
ObjectID portletName,
HashMap params,
boolean saveState,
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {

String finalUrl = "";
final PortletStateManager mgr = getPortletStateManager(request, response);
// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
final EngineURL url ;
if(saveState) {
url = urlFactory.newURL(Constants.SMART_COPY);
} else {
url = urlFactory.newURL(Constants.EMPTY_COPY);
}
// Set the page this URL should point to
try {
final com.ibm.portal.state.accessors.selection.SelectionAccessorFactory selectionFactory = (com.ibm.portal.state.accessors.selection.SelectionAccessorFactory) mgr.getAccessorFactory(com.ibm.portal.state.accessors.selection.SelectionAccessorFactory.class);

// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageOid);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletAccessorController(portletName, url.getState());
// Set the render parameter
if(params != null) {
portletCtrl.getParameters().putAll(params);
}

// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
finalUrl = url.writeDispose(new StringWriter()).toString();
}
} finally {
urlFactory.dispose();
}

// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
return finalUrl;
}

/**
* targets a specific mode of a portlet
* @param pageName
* @param portletName
* @param params
* @param saveState
* @param request
* @param response
* @param portletModeName
* @return string of the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
String pageName,
String portletName,
HashMap params,
boolean saveState,
PortletRequest request,
PortletResponse response,
String portletModeName)
throws StateException, NamingException, IOException {
String finalUrl = "";
final PortletStateManager mgr = getPortletStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
final EngineURL url ;
if(saveState) {
url = urlFactory.newURL(Constants.SMART_COPY);
} else {
url = urlFactory.newURL(Constants.EMPTY_COPY);
}
try {
// Set the page this URL should point to

final com.ibm.portal.state.accessors.selection.SelectionAccessorFactory selectionFactory = (com.ibm.portal.state.accessors.selection.SelectionAccessorFactory) mgr.getAccessorFactory(com.ibm.portal.state.accessors.selection.SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);

// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletAccessorController(portletName, url.getState());

if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
portletCtrl.setPortletMode(portletMode);
}
// Set the render parameter
if(params != null) {
portletCtrl.getParameters().putAll(params);
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}

// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
return finalUrl;
}
/**
* this will target the action phase of a portlet
* @param pageName
* @param portletName
* @param params
* @param request
* @param response
* @return string of the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
String pageName,
String portletName,
HashMap params,
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {
String finalUrl = "";

final PortletStateManager service = getPortletStateManager(request, response);

final URLFactory urlFactory = service.getURLFactory();

final PortletAccessorFactory pAccFct =(PortletAccessorFactory) service.getAccessorFactory(PortletAccessorFactory.class);

try {
// get a new URL from the URL factory
// null indicates that the current state should be copied
final EngineURL url = urlFactory.newURL(null);
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
// get a target controller that operates on the URL-specific state
final PortletTargetAccessorFactory tAccFct = (PortletTargetAccessorFactory) service.getAccessorFactory(PortletTargetAccessorFactory.class);

final PortletTargetAccessorController tCtrl = tAccFct.getPortletTargetAccessorController(url.getState());
// get a portlet controller that operates on the URL-specific state
final PortletAccessorController pCtrl = pAccFct.getPortletAccessorController(portletName, url.getState());
try {
// set the action target
tCtrl.setTarget(TargetType.PORTLET_ACTION, portletName);
//tCtrl.setActionTarget(portletName);
// set the action parameters
pCtrl.getParameters().putAll(params);
} finally {
tCtrl.dispose();
pCtrl.dispose();
}
// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* this will target the action phase of a portlet
* @param pageName objectid of the page
* @param portletName objectid of the portlet
* @param params
* @param request
* @param response
* @return string of the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
ObjectID pageName,
ObjectID portletName,
HashMap params,
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {
String finalUrl = "";

final PortletStateManager service = getPortletStateManager(request, response);

final URLFactory urlFactory = service.getURLFactory();

final PortletAccessorFactory pAccFct =(PortletAccessorFactory) service.getAccessorFactory(PortletAccessorFactory.class);

try {
// get a new URL from the URL factory
// null indicates that the current state should be copied
final EngineURL url = urlFactory.newURL(null);
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
// get a target controller that operates on the URL-specific state
final PortletTargetAccessorFactory tAccFct = (PortletTargetAccessorFactory) service.getAccessorFactory(PortletTargetAccessorFactory.class);

final PortletTargetAccessorController tCtrl = tAccFct.getPortletTargetAccessorController(url.getState());
// get a portlet controller that operates on the URL-specific state
final PortletAccessorController pCtrl = pAccFct.getPortletAccessorController(portletName, url.getState());
try {
// set the action target
tCtrl.setTarget(TargetType.PORTLET_ACTION, portletName);
//tCtrl.setActionTarget(portletName);
// set the action parameters
pCtrl.getParameters().putAll(params);
} finally {
tCtrl.dispose();
pCtrl.dispose();
}
// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* This will target an action and a mode if specified
* @param pageName
* @param portletName
* @param portletModeName
* @param params
* @param request
* @param response
* @return string of the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
String pageName,
String portletName,
String portletModeName,
HashMap params,
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {
String finalUrl = "";

final PortletStateManager service = getPortletStateManager(request, response);

final URLFactory urlFactory = service.getURLFactory();

final PortletTargetAccessorFactory tAccFct = (PortletTargetAccessorFactory) service.getAccessorFactory(PortletTargetAccessorFactory.class);
final PortletAccessorFactory pAccFct = (PortletAccessorFactory) service.getAccessorFactory(PortletAccessorFactory.class);

try {
// get a new URL from the URL factory
// null indicates that the current state should be copied
final EngineURL url = urlFactory.newURL(null);
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
// get a target controller that operates on the URL-specific state
final PortletTargetAccessorController tCtrl = tAccFct
.getPortletTargetAccessorController(url.getState());
// get a portlet controller that operates on the URL-specific state
final PortletAccessorController pCtrl = pAccFct.getPortletAccessorController(portletName, url.getState());
if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
pCtrl.setPortletMode(portletMode);
}
try {
// set the action target
tCtrl.setTarget(TargetType.PORTLET_ACTION, portletName);
//tCtrl.setActionTarget(portletName);
// set the action parameters
pCtrl.getParameters().putAll(params);
} finally {
tCtrl.dispose();
pCtrl.dispose();
}
// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* this will target just a specific mode of a portlet
* @param pageName
* @param portletName
* @param params
* @param saveState
* @param request
* @param response
* @param portletModeName
* @return string of the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
ObjectID pageName, ObjectID portletName,
HashMap params,
boolean saveState,
PortletRequest request,
PortletResponse response,
String portletModeName)
throws StateException, NamingException, IOException {
String finalUrl = "";
final PortletStateManager mgr = getPortletStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
final EngineURL url ;
if(saveState) {
url = urlFactory.newURL(Constants.SMART_COPY);
} else {
url = urlFactory.newURL(Constants.EMPTY_COPY);
}
try {
// Set the page this URL should point to

final com.ibm.portal.state.accessors.selection.SelectionAccessorFactory selectionFactory = (com.ibm.portal.state.accessors.selection.SelectionAccessorFactory) mgr.getAccessorFactory(com.ibm.portal.state.accessors.selection.SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);

// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletAccessorController(portletName, url.getState());

if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
portletCtrl.setPortletMode(portletMode);
}
// Set the render parameter
if(params != null) {
portletCtrl.getParameters().putAll(params);
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* This will allow you get get the current portlet window id so that you can use it to
* target the portlet on the page
*
* @param request
* @return ObjectID
*/
public static ObjectID getPortletWindowObjectId(PortletRequest request) {
ObjectID id = null;

try {
id = getPortletWindow(request).getObjectID();
} catch (StateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return id;
}
/**
* A helper method to return the portletoid so that you can target it in the above helper methods
* @param request
* @param response
* @return ObjectID of the current portlet
* @throws StateException
* @throws NamingException
*/
public static ObjectID getPortletId(PortletRequest request,
PortletResponse response) throws StateException, NamingException{
final PortletStateManager mgr = getPortletStateManager(request, response);
return mgr.getObjectID();

}

/**
* This is a method on how to get the current page you are on. This can be used when targetting portlets on the same page and you do
* not want to hard code the ObjectId, once you have the ObjectID you can get the uniquename from that. This should only be used when trying to
* get the current page from within a portlet using PPR
*
* @param request PortletRequest
* @param response PortletResponse
* @return ObjectID of the page
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static ObjectID getCurrentPagePPR(PortletRequest request,
PortletResponse response) throws StateException, NamingException, IOException {
ObjectID oId = null;
final PortletStateManager service = getPortletStateManager(request, response);
final StateAccessorFactory stateFct = (StateAccessorFactory) service.getAccessorFactory(StateAccessorFactory.class);
final StateAccessor stateAcc = stateFct.getStateAccessor();
final StateHolder state = stateAcc.getStateHolder((HttpServletRequest)request);
stateAcc.dispose();

final SelectionAccessorFactory selFct = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
final SelectionAccessor selAcc = selFct.getSelectionAccessor(state);
oId = selAcc.getSelection();

return oId;
}

/**
* This is a method on how to get the current page you are on. This can be used when targetting portlets on the same page and you do
* not want to hard code the ObjectId, once you have the ObjectID you can get the uniquename from that. This should only be used when trying to
* get the current page from within a portlet not using PPR
*
* @param request PortletRequest
* @param response PortletResponse
* @return ObjectID of the page
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static ObjectID getCurrentPage(PortletRequest request,
PortletResponse response) throws StateException, NamingException, IOException {
ObjectID oId = null;
try {
NavigationSelectionModelProvider provider = getNavigationSelectionModelProvider();

NavigationSelectionModel model = provider.getNavigationSelectionModel(request, response);
NavigationNode node = (NavigationNode)model.getSelectedNode();
oId = node.getObjectID();
} catch (ModelException e) {
System.err.println("The current page could not be located = " + e);
}

return oId;
}

/**
* This method only works on 601 and later. It can be used to create a url along with ajax
* to cause just that portlet to be rendered, no themes or skin will be rendered, just the
* content of the portlet. This method will point to the processAction method.
*
* @param params
* @param portletModeName
* @param windowState
* @param request
* @param response
* @return
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateSinglePortletRenderURL(
HashMap params,
String portletModeName,
WindowState windowState,
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {

final PortletStateManager mgr = getPortletStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
String finalUrl = "";

try {
final EngineURL url = urlFactory.newURL(null);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelectionMapping(selectionCtrl.getSelection(), getPortletWindow(request).getObjectID());
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = mgr.getPortletAccessorController(url.getState());

if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
portletCtrl.setPortletMode(portletMode);
}
if(windowState != null) {
portletCtrl.setWindowState(windowState);
}
// Set the render parameter
if(params != null) {
portletCtrl.getParameters().putAll(params);
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* This method only works on 601 and later. It can be used to create a url along with ajax
* to cause just that portlet to be rendered, no themes or skin will be rendered, just the
* content of the portlet. This method will point to the processAction method.
*
* @param params
* @param portletModeName
* @param windowState
* @param request
* @param response
* @return
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateSinglePortletActionURL(
HashMap params,
String portletModeName,
WindowState windowState,
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {

final PortletStateManager mgr = getPortletStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
String finalUrl = "";

try {
final EngineURL url = urlFactory.newURL(null);
final PortletTargetAccessorFactory tAccFct = (PortletTargetAccessorFactory) mgr.getAccessorFactory(PortletTargetAccessorFactory.class);


// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelectionMapping(selectionCtrl.getSelection(), getPortletWindow(request).getObjectID());
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = mgr.getPortletAccessorController(url.getState());
final PortletTargetAccessorController tCtrl = tAccFct.getPortletTargetAccessorController(url.getState());
tCtrl.setActionTarget(getPortletWindow(request).getObjectID());

if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
portletCtrl.setPortletMode(portletMode);
}
if(windowState != null) {
portletCtrl.setWindowState(windowState);
}
// Set the render parameter
if(params != null) {
portletCtrl.getParameters().putAll(params);
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
tCtrl.dispose();
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}

protected static NavigationSelectionModelProvider getNavigationSelectionModelProvider() {
NavigationSelectionModelProvider provider = null;
try {
if(navSelHome == null) {
Context ctx = new InitialContext();
navSelHome = (PortletServiceHome)ctx.lookup("portletservice/com.ibm.portal.portlet.service.model.NavigationSelectionModelProvider");
}
provider =(NavigationSelectionModelProvider) navSelHome.getPortletService(NavigationSelectionModelProvider.class);
} catch (Exception e) {
System.err.println("There was an error getting the navigation selection model provider = " + e);
}

return provider;
}

/**
* Will generate a url to allow you to log the user out using the portal logout command
*
* @param request
* @param response
* @return string for the url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateLogOutURL(
PortletRequest request,
PortletResponse response)
throws StateException, NamingException, IOException {
String finalUrl = "";
final PortletStateManager mgr = getPortletStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
final EngineURL url ;
try {
url = urlFactory.newURL(com.ibm.portal.state.Constants.EMPTY_COPY);
com.ibm.portal.state.accessors.action.engine.logout.LogoutActionAccessorFactory logoutFct = (com.ibm.portal.state.accessors.action.engine.logout.LogoutActionAccessorFactory) mgr.getAccessorFactory(com.ibm.portal.state.accessors.action.engine.logout.LogoutActionAccessorFactory.class);
com.ibm.portal.state.accessors.action.engine.logout.LogoutActionAccessorController logoutCtrl=logoutFct.newLogoutActionController(url.getState());
logoutCtrl.dispose();
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}



}
-----------------------------------------------------------------------------------
package com.ibm.wps.l2.urlspihelper.portletrequest;
/* @copyright module */
/* */
/* DISCLAIMER OF WARRANTIES: */
/* ------------------------- */
/* The following [enclosed] code is sample code created by IBM Corporation. */
/* This sample code is provided to you solely for the purpose of assisting */
/* you in the development of your applications. */
/* The code is provided "AS IS", without warranty of any kind. IBM shall */
/* not be liable for any damages arising out of your use of the sample code, */
/* even if they have been advised of the possibility of such damages. */
import java.io.Writer;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;

import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.url.PortalURLGenerationService;
import com.ibm.portal.portlet.service.url.PortalURLWriter;

/**
* @author James Barnes
* This class is a lesser used way to get the url to target a page. It uses a portalUrlWriter instead
* @deprecated
*/
public class PortletURLService {

private static PortletServiceHome psHome = null;


/**
* This method is a way to get the PortalURLGenerationService and you can use it to get a PortalURLWriter
* @param request
* @param response
* @return PortalURLWriter
*/
private static PortalURLWriter getPortletService(PortletRequest request,
PortletResponse response) {
PortalURLWriter urlWriter = null;
try {
if (psHome == null ){
Context ctx = new InitialContext();
psHome = (PortletServiceHome) ctx.lookup("portletservice/com.ibm.portal.portlet.service.url.PortalURLGenerationService");
}
PortalURLGenerationService portalUrlGenerationService = (PortalURLGenerationService) psHome.getPortletService(PortalURLGenerationService.class);
urlWriter = portalUrlGenerationService.getPortalURLWriter(request,response);
} catch (Exception ex) {
System.out.println("the service could not be retrieved ");
}
return urlWriter;
}

/**
* This method will write the url direction to the outputstream
*
* @param request
* @param response
* @param writer
* @param contentNode
* @param portletWindow
* @param params
*/
public static void getURLviaService(PortletRequest request,
PortletResponse response,
Writer writer,
String contentNode,
String portletWindow,
Map params) {
PortalURLWriter urlWriter = getPortletService(request, response);
try {
writer = urlWriter.writePortletRenderURL(writer, contentNode, portletWindow, params);
} catch (Exception ex) {
System.out.println("There was a problem writing the url");
}

}
}
-----------------------------------------------------------------------------
package com.ibm.wps.l2.urlspihelper.servletrequest;


import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.portlet.PortletMode;
import javax.portlet.WindowState;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.portal.ModelException;
import com.ibm.portal.ObjectID;
import com.ibm.portal.model.NavigationSelectionModelHome;
import com.ibm.portal.model.NavigationSelectionModelProvider;
import com.ibm.portal.navigation.NavigationNode;
import com.ibm.portal.navigation.NavigationSelectionModel;
import com.ibm.portal.state.Constants;
import com.ibm.portal.state.EngineURL;
import com.ibm.portal.state.StateHolder;
import com.ibm.portal.state.URLFactory;
import com.ibm.portal.state.accessors.StateAccessor;
import com.ibm.portal.state.accessors.StateAccessorFactory;
import com.ibm.portal.state.accessors.portlet.LegacyPortletTargetAccessorController;
import com.ibm.portal.state.accessors.portlet.PortletAccessorController;
import com.ibm.portal.state.accessors.portlet.PortletAccessorFactory;
import com.ibm.portal.state.accessors.portlet.PortletTargetAccessorController;
import com.ibm.portal.state.accessors.portlet.PortletTargetAccessorFactory;
import com.ibm.portal.state.accessors.portlet.TargetType;
import com.ibm.portal.state.accessors.selection.SelectionAccessor;
import com.ibm.portal.state.accessors.selection.SelectionAccessorController;
import com.ibm.portal.state.accessors.selection.SelectionAccessorFactory;
import com.ibm.portal.state.accessors.url.URLAccessorFactory;
import com.ibm.portal.state.exceptions.StateException;
import com.ibm.portal.state.service.PortalStateManagerService;
import com.ibm.portal.state.service.PortalStateManagerServiceHome;
import com.ibm.wps.l2.urlspihelper.utils.PortletType;

/**
* ServletURLHelper class is used for creating urls to various parts of portal
* These will include targeting pages and portlets, as well as triggering the action
* change the portlet mode and the window state. These will also all you to pass
* params to the specific portlet, if a portlet is targetted.
* this class is designed to be called statically.
*
* @author James Barnes
*
*/
public class ServletURLHelper {
protected static PortalStateManagerServiceHome psmsHome = null;
protected static NavigationSelectionModelHome navSelHome = null;


/**
* This method will return the PORTALStateManager and this is key to understand as there is a seperate one depending
* on if you are in a portlet or calling form a servlet/jsp
*
* @param request this is of type HttpServletRequest
* @param response this is of type HttpServlet Response
* @return will return a PortalStateManagerService instance for this class
* @throws StateException
* @throws NamingException
*/
protected static PortalStateManagerService getStateManager(HttpServletRequest request, HttpServletResponse response) throws StateException, NamingException {
// you can cache the home interface
PortalStateManagerService service = null;
if(psmsHome == null) {
Context ctx = new InitialContext();
psmsHome = (PortalStateManagerServiceHome) ctx.lookup("portal:service/state/PortalStateManager");
}
try {
service = psmsHome.getPortalStateManagerService(request, response);
} catch (Exception ex) {
System.out.println("the state manger service was unable to be retrieved");
}

// you need to request the state manager on a per-thread basis
return service;
}

public static String testURLPublic(
String pageName,
HashMap params,
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);


// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
Map paramsFromPage = selectionCtrl.getParameters();
paramsFromPage.putAll(params);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();


// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
return url.writeDispose(new StringWriter()).toString();
}
/**
* The goal of these classes was to overload the generateUrl command and depending on what you are passing in
* will determine how the url is generated. This simply targets the portlet on a page and passes the params
* to the view phase. You can pass in null for params, and portletName, but pageName MUST not be null
*
* @param pageName This is the uniquename and one thing to be aware of is that this is scoped to the virtual portal
* @param portletName this is the unique name of the portlet window on the page. This can only be set via xmlaccess
* @param params a map of params you want to pass to the portlet, one thing to keep in mind is strings must be passed as a string array
*
*

HashMap map = new HashMap();
String[] value1 = {"testthis"};
map.put("p2psample4_search_text", value1);

* @param request this is of type HttpServletRequest
* @param response this is of type HttpServlet Response
* @return will return a string and this is the url that needs to be done used in the link(DO NOT TRY TO CHANGE IT)
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
String pageName,
String portletName,
HashMap params,
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);


// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletAccessorController(portletName, url.getState());
// Get the modifiable render parameter map
final Map parameters = portletCtrl.getParameters();
// Set the render parameter
if(params != null) {
String key = null;
Iterator paramsIterator = params.keySet().iterator();
while(paramsIterator.hasNext()) {
key = (String)paramsIterator.next();
parameters.put(key, params.get(key));
}
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}

// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
return url.writeDispose(new StringWriter()).toString();
}

/**
* This method is similar to the one above but takes an objectid for the page and portlet instead of the string uniquename.
* The objectid can be retrieved using the identification service if you know the string representation.
*
* You can use the following code in a jsr 168 portlet to get the window id
*

PortletServiceHome psh;
javax.naming.Context ctx = new javax.naming.InitialContext();
psh = (PortletServiceHome) ctx.lookup("portletservice/com.ibm.portal.state.service.PortletStateManagerService");

PortletStateManagerService service = (PortletStateManagerService)psh.getPortletService(PortletStateManagerService.class);
PortletStateManager manager = service.getPortletStateManager(request, response);
ObjectID oid = manager.getObjectID();

*
*

*
* @param pageName This is the objectid of the page(you can get the objectid object from either the content node, or the
* idetification helper class)
* @param portletName this is the unique name of the portlet window on the page. This can only be set via xmlaccess
* @param params a map of params you want to pass to the portlet, one thing to keep in mind is strings must be passed as a string array
* @param request this is of type HttpServletRequest
* @param response this is of type HttpServlet Response
* @return will return a string and this is the url that needs to be done used in the link(DO NOT TRY TO CHANGE IT)
* @return String of the url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
ObjectID pageName,
ObjectID portletName,
HashMap params,
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);


// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

// Request a URL
// The 3rd argument specifies whether the URL points to the protected (authenticated) area;
// pass in "false" if your page is accessible for unauthenticated users

//final EngineURL url = urlFactory.newURL(serverContext, false, nonPublicPage, mgr.newState(), Constants.EMPTY_COPY);
final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletAccessorController(portletName, url.getState());
// Get the modifiable render parameter map
final Map parameters = portletCtrl.getParameters();
// Set the render parameter
if(params != null) {
String key = null;
Iterator paramsIterator = params.keySet().iterator();
while(paramsIterator.hasNext()) {
key = (String)paramsIterator.next();
parameters.put(key, params.get(key));
}
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}

// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
return url.writeDispose(new StringWriter()).toString();
}


// this will target the portlets action phase
/**
* This method is for targetting a portlet specifically and triggering the action phase of the portlet passing params
* @param pageName uniquename of the page
* @param portletName uniquename of the portlet on the page(if you want you can override these methods and pass in ObjectID instead)
* @param params map of params being passed into the target portlet
* @param request of type HttpServletRequest
* @param response of type HttpServletResponse
* @param portletType this is an indicator of whether or not this is legacy or standard portlet being access
* @return a string that is the url to be called
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrlToPortlet(
String pageName,
String portletName,
HashMap params,
HttpServletRequest request,
HttpServletResponse response,
PortletType portletType,
String actionReference)
throws StateException, NamingException, IOException {
String finalUrl = "";

final PortalStateManagerService mgr = getStateManager(request, response);

final URLFactory urlFactory = mgr.getURLFactory();
final PortletTargetAccessorFactory tAccFct = (PortletTargetAccessorFactory) mgr.getAccessorFactory(PortletTargetAccessorFactory.class);
final PortletAccessorFactory pAccFct = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);

try {
// get a new URL from the URL factory
// null indicates that the current state should be copied
final EngineURL url = urlFactory.newURL(null);
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
// get a target controller that operates on the URL-specific state
final PortletTargetAccessorController tCtrl = getPortletTargetAccessor(request, portletType, tAccFct, url, actionReference);
// get a portlet controller that operates on the URL-specific state
final PortletAccessorController pCtrl = getPortletAccessor(portletType, pAccFct, portletName, url);
try {
// set the action target
tCtrl.setTarget(TargetType.PORTLET_ACTION, portletName);

//tCtrl.setActionTarget(portletName);
// set the action parameters
if(params != null) {
pCtrl.getParameters().putAll(params);
}
} finally {
tCtrl.dispose();
pCtrl.dispose();
}
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}

// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
return finalUrl;
}

//
/**
* this will change to a specific mode of a portlet
* @param pageName
* @param portletName
* @param params
* @param request
* @param response
* @param portletModeName
* @param portletType
* @return String of the url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrlToPortlet(
String pageName,
String portletName,
HashMap params,
HttpServletRequest request,
HttpServletResponse response,
String portletModeName,
PortletType portletType)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);


// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
//final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionController(url.getState());
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());

// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

if(portletName != null) {
// Set portlet render parameters
//final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);
final PortletAccessorFactory pAccFct = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);

// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = getPortletAccessor(portletType, pAccFct, portletName, url);
// Get the modifiable render parameter map
final Map parameters = portletCtrl.getParameters();
if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
portletCtrl.setPortletMode(portletMode);
}
// Set the render parameter
if(params != null) {
String key = null;
Iterator paramsIterator = params.keySet().iterator();
while(paramsIterator.hasNext()) {
key = (String)paramsIterator.next();
parameters.put(key, params.get(key));
}
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}
return url.writeDispose(new StringWriter()).toString();
}
//
/**
* this can target the specific mode, window state, and action phase
* @param pageName
* @param portletName
* @param portletModeName
* @param windowState
* @param params
* @param request
* @param response
* @param portletType
* @return String of the url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrlToPortlet(
String pageName,
String portletName,
String portletModeName,
WindowState windowState,
HashMap params,
HttpServletRequest request,
HttpServletResponse response,
PortletType portletType)
throws StateException, NamingException, IOException {
String finalUrl = "";

final PortalStateManagerService service = getStateManager(request, response);

final URLFactory urlFactory = service.getURLFactory();

final PortletTargetAccessorFactory tAccFct = (PortletTargetAccessorFactory) service.getAccessorFactory(PortletTargetAccessorFactory.class);
final PortletAccessorFactory pAccFct = (PortletAccessorFactory) service.getAccessorFactory(PortletAccessorFactory.class);

try {
// get a new URL from the URL factory
// null indicates that the current state should be copied
final EngineURL url = urlFactory.newURL(null);
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
// get a target controller that operates on the URL-specific state
// final PortletTargetAccessorController tCtrl = tAccFct.getPortletTargetAccessorController(url.getState());
final PortletTargetAccessorController tCtrl = getPortletTargetAccessor(request, portletType, tAccFct, url, null);
// get a portlet controller that operates on the URL-specific state
//final PortletAccessorController pCtrl = pAccFct.getPortletAccessorController(portletName, url.getState());
final PortletAccessorController pCtrl = getPortletAccessor(portletType, pAccFct, portletName, url);
if(windowState != null) {
pCtrl.setWindowState(windowState);
}
if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
pCtrl.setPortletMode(portletMode);
}
try {
// set the action target
tCtrl.setTarget(TargetType.PORTLET_ACTION, portletName);
//tCtrl.setActionTarget(portletName);
// set the action parameters
if(params != null) {
pCtrl.getParameters().putAll(params);
}

} finally {
tCtrl.dispose();
pCtrl.dispose();
}
// Now convert the URL to a String; pass in your writer.
// writeDispose() writes the URL to the given writer and disposes the URL afterwards.
// If you want to display this URL a multiple times pls use writeCopy().
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}


/**
* This is a method on how to get the current page you are on. This can be used when targetting portlets on the same page and you do
* not want to hard code the ObjectId, once you have the ObjectID you can get the uniquename from that this should only be used
* when in a PPR portlet otherwise use the regular get current page that retrieves it from the navigationselectionmodel
*
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return ObjectID of the page
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static ObjectID getCurrentPagePPR(HttpServletRequest request, HttpServletResponse response) throws StateException, NamingException, IOException {
ObjectID oId = null;
final PortalStateManagerService service = getStateManager(request, response);
final StateAccessorFactory stateFct = (StateAccessorFactory) service.getAccessorFactory(StateAccessorFactory.class);
final StateAccessor stateAcc = stateFct.getStateAccessor();
final StateHolder state = stateAcc.getStateHolder(request);
stateAcc.dispose();

final SelectionAccessorFactory selFct = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
final SelectionAccessor selAcc = selFct.getSelectionAccessor(state);
oId = selAcc.getSelection();

return oId;
}

/**
* This is a method on how to get the current page you are on. This can be used when targetting portlets on the same page and you do
* not want to hard code the ObjectId, This is the preferred way to get the current page, but cannot be used when using PPR
*
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return ObjectID of the page
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static ObjectID getCurrentPage(HttpServletRequest request, HttpServletResponse response) throws StateException, NamingException, IOException {
ObjectID oId = null;
try {
NavigationSelectionModelProvider provider = getNavigationSelectionModelProvider();

NavigationSelectionModel model = provider.getNavigationSelectionModel(request, response);
NavigationNode node = (NavigationNode)model.getSelectedNode();
oId = node.getObjectID();
} catch (ModelException e) {
System.err.println("The current page could not be located = " + e);
}

return oId;
}

/**
* This is a private method only to be used internally to return the correct PortletAccessor
*
* @param pType PortletType
* @param pAccFct PortletAccessorFactory
* @param portletName uniquename of the portlet on the page
* @param url EngineURL created in the calling method
* @return PortletAccessorController or LegacyPortletAccessorController
*/
private static PortletAccessorController getPortletAccessor(PortletType pType, final PortletAccessorFactory pAccFct, String portletName, EngineURL url) {
try {
if(pType.getPortletType().equals(pType.LEGACY_PORTLET)) {

return pAccFct.getLegacyPortletAccessorController(portletName, url.getState());
} else {
return pAccFct.getPortletAccessorController(portletName, url.getState());
}
} catch (Exception ex){
System.out.println("There was a problem in the getPortletAccessor = " + ex);
return null;
}
}

/**
* @param pType PortletType
* @param tAccFct PortletTargetAccessorFactory
* @param url EngineURL created in calling method
* @return PortletTargetAccessorController this can be of type LegacyPortletTargetAccessorController or just PortletTargetAccessorController
*
*/
private static PortletTargetAccessorController getPortletTargetAccessor(HttpServletRequest request, PortletType pType, final PortletTargetAccessorFactory tAccFct, EngineURL url, String actionReference) {
try {
if(pType.getPortletType().equals(pType.LEGACY_PORTLET)) {
LegacyPortletTargetAccessorController legAcc = tAccFct.getLegacyPortletTargetAccessorController(request, url.getState());
legAcc.setActionReference(actionReference);
return tAccFct.getLegacyPortletTargetAccessorController(request, url.getState());
} else {

return tAccFct.getPortletTargetAccessorController(request, url.getState());
}
} catch(Exception ex) {
System.out.println("There was a problem in getPortletTargetAccessor = " + ex);
return null;
}
}

protected static NavigationSelectionModelProvider getNavigationSelectionModelProvider() {
NavigationSelectionModelProvider provider = null;
try {
if(navSelHome == null) {
Context ctx = new InitialContext();
navSelHome = (NavigationSelectionModelHome) ctx.lookup("portal:service/model/NavigationSelectionModel");
}
provider = navSelHome.getNavigationSelectionModelProvider();
} catch (Exception e) {
System.err.println("There was an error getting the navigation selection model provider = " + e);
}

return provider;
}

}
-----------------------------------------------------------------------------
package com.ibm.wps.l2.urlspihelper.servletrequest;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.Locale;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.portal.ObjectID;
import com.ibm.portal.model.NavigationModelHome;
import com.ibm.portal.model.NavigationSelectionModelProvider;
import com.ibm.portal.navigation.NavigationModel;
import com.ibm.portal.navigation.NavigationNode;
import com.ibm.portal.navigation.NavigationSelectionModel;
import com.ibm.portal.state.Constants;
import com.ibm.portal.state.DisposableURL;
import com.ibm.portal.state.EngineURL;
import com.ibm.portal.state.URLFactory;
import com.ibm.portal.state.accessors.expansionstates.ExpansionStatesAccessorController;
import com.ibm.portal.state.accessors.expansionstates.ExpansionStatesAccessorFactory;
import com.ibm.portal.state.accessors.locale.LocaleAccessorController;
import com.ibm.portal.state.accessors.locale.LocaleAccessorFactory;
import com.ibm.portal.state.accessors.portlet.PortletTargetAccessorController;
import com.ibm.portal.state.accessors.portlet.PortletTargetAccessorFactory;
import com.ibm.portal.state.accessors.selection.SelectionAccessorController;
import com.ibm.portal.state.accessors.selection.SelectionAccessorFactory;
import com.ibm.portal.state.accessors.solo.SoloAccessorController;
import com.ibm.portal.state.accessors.solo.SoloAccessorFactory;
import com.ibm.portal.state.accessors.statepartition.StatePartitionAccessorController;
import com.ibm.portal.state.accessors.statepartition.StatePartitionAccessorFactory;
import com.ibm.portal.state.accessors.themetemplate.ThemeTemplateAccessorController;
import com.ibm.portal.state.accessors.themetemplate.ThemeTemplateAccessorFactory;
import com.ibm.portal.state.accessors.url.URLAccessorFactory;
import com.ibm.portal.state.exceptions.StateException;
import com.ibm.portal.state.service.PortalStateManagerService;

/**
* The ThemeURLHelper is mainly used when creating links within the theme, you can use these
* to target various things, such as changing the locale, theme template, or creating a url
* for flyout. This also includes helpers for login and lout url, as well as getting disposable
* urls which can be used when making links to images for theme extensions and the like
* @author James Barnes
*
*/
public class ThemeURLHelper extends ServletURLHelper {

private static NavigationModelHome nmHome = null;

/**
* This method will generate a url to the node passed with a toggle to expand the current node
* as well as navigate to that page
*
* @param wpsNavNode of type NavigationNode which can be gotten from either the
* navigation loop tag, or the NavigationModel SPI
* @param toggle tells it to expand or collapse these nodes
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return string that represents the selection url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrlStringWithExpansion(
NavigationNode wpsNavNode,
boolean toggle,
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);


// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

// Request a URL
// The 3rd argument specifies whether the URL points to the protected (authenticated) area;
// pass in "false" if your page is accessible for unauthenticated users

//final EngineURL url = urlFactory.newURL(serverContext, false, nonPublicPage, mgr.newState(), Constants.EMPTY_COPY);
final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(wpsNavNode.getObjectID());
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

final ExpansionStatesAccessorFactory expansionFactory = (ExpansionStatesAccessorFactory) mgr.getAccessorFactory(ExpansionStatesAccessorFactory.class);
final ExpansionStatesAccessorController expansionCtrl = expansionFactory.getExpansionStatesAccessorController(url.getState());
expansionCtrl.setToggled(wpsNavNode.getObjectID(), toggle);
expansionCtrl.dispose();

return url.writeDispose(new StringWriter()).toString();
}

public static String generateUrlDropState(
NavigationNode wpsNavNode,
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);


// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

// Request a URL
// The 3rd argument specifies whether the URL points to the protected (authenticated) area;
// pass in "false" if your page is accessible for unauthenticated users

//final EngineURL url = urlFactory.newURL(serverContext, false, nonPublicPage, mgr.newState(), Constants.EMPTY_COPY);
final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(wpsNavNode.getObjectID());
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

return url.writeDispose(new StringWriter()).toString();
}

/**
* This will create a url for a page that genearates the page with the given theme template(plain)
* and can target the portlet if neccessary, this can be used in a theme extension to create the flyout
* or to create a popup window targetting a portlet with no theme elements.
*
* @param pageName UniqueName of the page
* @param portletName uniqueName of the portlet
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return EngineURL of the page
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static EngineURL generateUrlForFlyout(
String pageName, String portletName,
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);

// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);
final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

if(portletName != null) {
// Set portlet render parameters
final PortletTargetAccessorFactory portletAccessorFactory = (PortletTargetAccessorFactory) mgr.getAccessorFactory(PortletTargetAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletTargetAccessorController accessorController = portletAccessorFactory.getPortletTargetAccessorController(url.getState() );
accessorController.setRenderTarget( portletName );

// Dispose the accessor (avoids memory leak)
accessorController.dispose();
}
StatePartitionAccessorFactory stateFactory = (StatePartitionAccessorFactory) mgr.getAccessorFactory( StatePartitionAccessorFactory.class );

StatePartitionAccessorController stateCtrl = stateFactory.getStatePartitionAccessorController( url.getState() );
stateCtrl.includeStatePartitionId();
stateCtrl.dispose();

ThemeTemplateAccessorFactory themeFactory = (ThemeTemplateAccessorFactory) mgr.getAccessorFactory( ThemeTemplateAccessorFactory.class );
ThemeTemplateAccessorController themeCtrl = themeFactory.getThemeTemplateAccessorController( url.getState() );
themeCtrl.setThemeTemplate("Plain" );
themeCtrl.dispose();

if(portletName != null) {
SoloAccessorFactory soloFactory = (SoloAccessorFactory) mgr.getAccessorFactory( SoloAccessorFactory.class );
SoloAccessorController soloCtrl = soloFactory.getSoloAccessorController( url.getState() );
soloCtrl.setSoloPortlet( portletName );
soloCtrl.dispose();
}
return url;
}
/**
* Overloaded Method for above that takes an ObjectID for the page and portlet
* @param pageName
* @param portletName
* @param request
* @param response
* @return EngineURL for the link
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static EngineURL generateUrlForFlyout(
ObjectID pageName,
ObjectID portletName,
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);

// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

if(portletName != null) {
// Set portlet render parameters
final PortletTargetAccessorFactory portletAccessorFactory = (PortletTargetAccessorFactory) mgr.getAccessorFactory(PortletTargetAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletTargetAccessorController accessorController = portletAccessorFactory.getPortletTargetAccessorController(url.getState() );
accessorController.setRenderTarget( portletName );

// Dispose the accessor (avoids memory leak)
accessorController.dispose();
}
StatePartitionAccessorFactory stateFactory = (StatePartitionAccessorFactory) mgr.getAccessorFactory( StatePartitionAccessorFactory.class );

StatePartitionAccessorController stateCtrl = stateFactory.getStatePartitionAccessorController( url.getState() );
stateCtrl.includeStatePartitionId();
stateCtrl.dispose();

ThemeTemplateAccessorFactory themeFactory = (ThemeTemplateAccessorFactory) mgr.getAccessorFactory( ThemeTemplateAccessorFactory.class );
ThemeTemplateAccessorController themeCtrl = themeFactory.getThemeTemplateAccessorController( url.getState() );
themeCtrl.setThemeTemplate("Plain" );
themeCtrl.dispose();

if(portletName != null) {
SoloAccessorFactory soloFactory = (SoloAccessorFactory) mgr.getAccessorFactory( SoloAccessorFactory.class );
SoloAccessorController soloCtrl = soloFactory.getSoloAccessorController( url.getState() );
soloCtrl.setSoloPortlet( portletName );
soloCtrl.dispose();
}
return url;
}


/**
* Will generate a url to allow you to log the user out using the portal logout command
*
* @param request
* @param response
* @return string for the url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateLogOutURL(
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {
String finalUrl = "";
final PortalStateManagerService mgr = getStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
final EngineURL url ;
try {
url = urlFactory.newURL(com.ibm.portal.state.Constants.EMPTY_COPY);
com.ibm.portal.state.accessors.action.engine.logout.LogoutActionAccessorFactory logoutFct = (com.ibm.portal.state.accessors.action.engine.logout.LogoutActionAccessorFactory) mgr.getAccessorFactory(com.ibm.portal.state.accessors.action.engine.logout.LogoutActionAccessorFactory.class);
com.ibm.portal.state.accessors.action.engine.logout.LogoutActionAccessorController logoutCtrl=logoutFct.newLogoutActionController(request, url.getState());
logoutCtrl.dispose();
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}


/**
* Creates a url that you can post to with the correct credentials to log the
* user into portal
*
* @param request
* @param response
* @return string for the url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateLogInURL(
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {
String finalUrl = "";
final PortalStateManagerService mgr = getStateManager(request, response);

// Get the URL factory
URLFactory urlFactory = mgr.getURLFactory();
final EngineURL url ;
try {
url = urlFactory.newURL(com.ibm.portal.state.Constants.EMPTY_COPY);
com.ibm.portal.state.accessors.action.engine.login.LoginActionAccessorFactory logoutFct = (com.ibm.portal.state.accessors.action.engine.login.LoginActionAccessorFactory) mgr.getAccessorFactory(com.ibm.portal.state.accessors.action.engine.login.LoginActionAccessorFactory.class);
com.ibm.portal.state.accessors.action.engine.login.LoginActionAccessorController logoutCtrl=logoutFct.newLoginActionController(request, url.getState());
logoutCtrl.dispose();
finalUrl = url.writeDispose(new StringWriter()).toString();
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* The URL returned is used to generate urls to resources, such as images, javascripts
* and other theme elements
*
* @param request
* @param response
* @param fileName
* @return string for the url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static DisposableURL getDisposableURL(
HttpServletRequest request,
HttpServletResponse response,
String fileName)
throws StateException, NamingException, IOException {

final PortalStateManagerService mgr = getStateManager(request, response);
final URLFactory urlFactory = mgr.getURLFactory();
final DisposableURL url;
try {
url = urlFactory.newResourceURL(fileName, com.ibm.portal.state.accessors.url.PortalResources.Type.TYPE_FILES, com.ibm.portal.state.accessors.url.PortalResources.State.NO_STATE);
} finally {
urlFactory.dispose();
}
return url;

}
/**
* This will create a url that allows you to change the language inuse in the portal, it WILL not change the
* preferred language of the user
*
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param language string representation of the language code
* @return String url representation
* @throws StateException
*/
public String createChangeLanguageURL(
HttpServletRequest request,
HttpServletResponse response,
String language) throws StateException, NamingException, IOException {

String finalUrl = "";
final PortalStateManagerService service = getStateManager(request, response);
final URLFactory urlFactory = service.getURLFactory();

try {
// get the needed factories
final LocaleAccessorFactory locFct = (LocaleAccessorFactory) service.getAccessorFactory(LocaleAccessorFactory.class);
// get a new URL from the URL factory
final EngineURL url = urlFactory.newURL(null);
// get a locale controller which operates on the URL-specific state
final LocaleAccessorController locCtrl =
locFct.getLocaleAccessorController(url.getState());
try {
// change the locale
locCtrl.setLocale(new Locale(language));
// return the URL;
finalUrl = url.toString();
} finally {
locCtrl.dispose();
}
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* This method would allow you to change the theme template for the page you are targetting.
* Your string choices are default, plain, mainMenu, portletMenu, pageMenu
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param pageName uniqueName of the page you are targeting
* @param themeTemplate
* @return string for the url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public String createThemeTemplateChangeUrl (
HttpServletRequest request,
HttpServletResponse response,
String pageName,
String themeTemplate) throws StateException, NamingException, IOException {

String finalUrl = "";
final PortalStateManagerService service = getStateManager(request, response);
final ThemeTemplateAccessorFactory tAccFct = (ThemeTemplateAccessorFactory) service.getAccessorFactory(ThemeTemplateAccessorFactory.class);
final SelectionAccessorFactory sAccFct = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
final URLFactory urlFactory = service.getURLFactory();

try {
// get a new URL from the URL factory
final EngineURL url = urlFactory.newURL(null);
// get a theme template controller which operates on the
// URL-specific state
final ThemeTemplateAccessorController tCtrl = tAccFct.getThemeTemplateAccessorController(url.getState());
// get a selection controller which operates on the
// URL-specific state
final SelectionAccessorController sCtrl = sAccFct.getSelectionAccessorController(url.getState());
try {
// change the theme template
tCtrl.setThemeTemplate(themeTemplate);
// change the page selection
sCtrl.setSelection(pageName);
// return the URL
finalUrl = url.toString();
} finally {
tCtrl.dispose();
sCtrl.dispose();
}
} finally {
urlFactory.dispose();
}
return finalUrl;
}

/**
* This method will allow you to create a method to change the expansion state of the . For performance reasons, this method
* will retrieve the current page from the passed in request, it will also do an EMPTY_COPY of the state, this will cause all state
* information to be dropped(like if you used the change language command to do change language for this state), If you have a need for that
* Change this line
* final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);
*
* to this
* final EngineURL url = urlFactory.newURL(request, Constants.SMART_COPY);
* and then remove the if statment toggle == true that way the expansion state will be set to true or
* false for everything
*
* @param toggle
* @param request
* @param response
* @return
* @throws StateException
* @throws NamingException
* @throws IOException
*/

public static String expandAllPages(
boolean toggle,
HttpServletRequest request,
HttpServletResponse response)
throws StateException, NamingException, IOException {

ObjectID objectID = getCurrentPage(request, response);

final PortalStateManagerService mgr = getStateManager(request, response);
// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

final EngineURL url = urlFactory.newURL(request, response, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(objectID);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

final ExpansionStatesAccessorFactory expansionFactory = (ExpansionStatesAccessorFactory) mgr.getAccessorFactory(ExpansionStatesAccessorFactory.class);
final ExpansionStatesAccessorController expansionCtrl = expansionFactory.getExpansionStatesAccessorController(url.getState());
if(toggle == true) {
try{
if (navSelHome != null) {
NavigationSelectionModelProvider provider = getNavigationSelectionModelProvider();
NavigationSelectionModel model = provider.getNavigationSelectionModel(request, response);
int level = 1;
for (java.util.Iterator i = model.iterator(); i.hasNext(); ) {
NavigationNode node = (NavigationNode) i.next();
NavigationNode childNode2ndLevel = null;
if(level == 3) {
if(nmHome == null) {
Context ctx = new InitialContext();
nmHome = (NavigationModelHome) ctx.lookup("portal:service/model/NavigationModel");
}
NavigationModel nmodel = nmHome.getNavigationModelProvider().getNavigationModel(request, response);
Iterator childrenIter = nmodel.getChildren(node);
while (childrenIter.hasNext()) {
childNode2ndLevel = (NavigationNode)childrenIter.next();
expansionCtrl.setToggled(childNode2ndLevel.getObjectID(), toggle);
}
}
level++;
}
}
} catch (Exception ex) {
System.err.println("there was a problem in the call = " + ex);
}
}
expansionCtrl.setToggled(objectID, toggle);
expansionCtrl.dispose();

return url.writeDispose(new StringWriter()).toString();
}

}
------------------------------------------------------------------------------
package com.ibm.wps.l2.urlspihelper.stateless;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.portlet.PortletMode;
import javax.portlet.WindowState;

import com.ibm.portal.ObjectID;
import com.ibm.portal.state.Constants;
import com.ibm.portal.state.EngineURL;
import com.ibm.portal.state.StateManager;
import com.ibm.portal.state.accessors.portlet.PortletAccessorController;
import com.ibm.portal.state.accessors.portlet.PortletAccessorFactory;
import com.ibm.portal.state.accessors.portlet.PortletTargetAccessorController;
import com.ibm.portal.state.accessors.portlet.PortletTargetAccessorFactory;
import com.ibm.portal.state.accessors.selection.SelectionAccessorController;
import com.ibm.portal.state.accessors.selection.SelectionAccessorFactory;
import com.ibm.portal.state.accessors.url.URLAccessorFactory;
import com.ibm.portal.state.exceptions.StateException;
import com.ibm.portal.state.service.StateManagerHome;
import com.ibm.wps.l2.urlspihelper.stateless.utils.MyServerContext;
import com.ibm.wps.l2.urlspihelper.utils.PortletType;

/**
* @author James Barnes
*
* This class is used for generating urls when you do not want to preserve the state or base them off
* the current request. Additionally when creating urls you cannot use it to target portlet actions
* for authenticated pages, only actions on portlets on unauthenticated pages.
*/
public class OffLineURLHelper {
private static StateManagerHome stateMgrHome = null;

/**
* This will return a generic state manager for portal, it does not base its creation on the request and response
*
* @return generic StateManager
* @throws StateException
* @throws NamingException
*/
private static StateManager getStateManager() throws StateException, NamingException {
if (stateMgrHome == null) {
Context ctx = new InitialContext();
stateMgrHome = (StateManagerHome) ctx.lookup("portalservice/com.ibm.portal.state.StateManager");
return stateMgrHome.getStateManager();
} else {
return stateMgrHome.getStateManager();
}
}

/**
* This will generate a url to a portal page using the ServerContext.
*
* @param pageName uniqueName of a pagename, these are not shareable across virtual portals
* @param portletName uniqueName of the portlet on page, to set this please follow the instructions
* here Technote
* @param params You can pass in params
* the Strings must be a string array
*

HashMap map = new HashMap();
String[] value1 = {"testthis"};
map.put("p2psample4_search_text", value1);

* @param serverContext Use the MyServerContext class or MyVpServerContext
* @param nonPublicPage this tells the generator to create a private or public page
* @return String of the generated url
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
String pageName,
String portletName,
HashMap params,
MyServerContext serverContext,
boolean nonPublicPage)
throws StateException, NamingException, IOException {

final StateManager mgr = getStateManager();

// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

// Request a URL
// The 3rd argument specifies whether the URL points to the protected (authenticated) area;
// pass in "false" if your page is accessible for unauthenticated users

final EngineURL url = urlFactory.newURL(serverContext, false, nonPublicPage, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionController(url.getState());
// Set the page; you need the unique name (String)
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletController(portletName, url.getState());
// Get the modifiable render parameter map
final Map parameters = portletCtrl.getParameters();
// Set the render parameter
if(params != null) {
String key = null;
Iterator paramsIterator = params.keySet().iterator();
while(paramsIterator.hasNext()) {
key = (String)paramsIterator.next();
parameters.put(key, params.get(key));
}
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}
return url.writeDispose(new StringWriter()).toString();
}

/**
* This works the same as above, but takes objectids instead of the uniquename
* @param pageName
* @param portletName
* @param params
* @param serverContext
* @param nonPublicPage
* @return
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
ObjectID pageName,
ObjectID portletName,
HashMap params,
MyServerContext serverContext,
boolean nonPublicPage)
throws StateException, NamingException, IOException {

final StateManager mgr = getStateManager();

// Get the URL factory
final URLAccessorFactory urlFactory = (URLAccessorFactory) mgr.getAccessorFactory(URLAccessorFactory.class);

// Request a URL
// The 3rd argument specifies whether the URL points to the protected (authenticated) area;
// pass in "false" if your page is accessible for unauthenticated users

final EngineURL url = urlFactory.newURL(serverContext, false, nonPublicPage, mgr.newState(), Constants.EMPTY_COPY);

// Set the page this URL should point to
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) mgr.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionController(url.getState());
// Set the page; you need the unique name (String)
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();

if(portletName != null) {
// Set portlet render parameters
final PortletAccessorFactory portletAccessorFactory = (PortletAccessorFactory) mgr.getAccessorFactory(PortletAccessorFactory.class);
// Get the portlet controller to set render parameters; pass in the state associated with rge created URL
final PortletAccessorController portletCtrl = portletAccessorFactory.getPortletController(portletName, url.getState());
// Get the modifiable render parameter map
final Map parameters = portletCtrl.getParameters();
// Set the render parameter
if(params != null) {
String key = null;
Iterator paramsIterator = params.keySet().iterator();
while(paramsIterator.hasNext()) {
key = (String)paramsIterator.next();
parameters.put(key, params.get(key));
}
}
// Dispose the accessor (avoids memory leak)
portletCtrl.dispose();
}
return url.writeDispose(new StringWriter()).toString();
}


/**
* This will target an action and change the portlet mode. can only be used to target an action on a public page
*
* @param pageName
* @param portletName
* @param portletModeName string representation of the portletMode
* @param params
* @param serverContext
* @param nonPublicPage
* @return
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
String pageName,
String portletName,
String portletModeName,
HashMap params,
MyServerContext serverContext,
boolean nonPublicPage,
PortletType portletType)
throws StateException, NamingException, IOException {
String finalUrl = "";

final StateManager service = getStateManager();

final URLAccessorFactory urlFactory = (URLAccessorFactory) service.getAccessorFactory(URLAccessorFactory.class);

// Request a URL
// The 3rd argument specifies whether the URL points to the protected (authenticated) area;
// pass in "false" if your page is accessible for unauthenticated users

final EngineURL url = urlFactory.newURL(serverContext, false, nonPublicPage, service.newState(), Constants.EMPTY_COPY);

final PortletTargetAccessorFactory tAccFct = (PortletTargetAccessorFactory) service.getAccessorFactory(PortletTargetAccessorFactory.class);
final PortletAccessorFactory pAccFct = (PortletAccessorFactory) service.getAccessorFactory(PortletAccessorFactory.class);
// get a new URL from the URL factory
// null indicates that the current state should be copied

final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
// get a target controller that operates on the URL-specific state
final PortletTargetAccessorController tCtrl = getPortletTargetAccessor(portletType, tAccFct, url);
// get a portlet controller that operates on the URL-specific state
final PortletAccessorController pCtrl = getPortletAccessor(portletType, pAccFct, portletName, url);
if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
pCtrl.setPortletMode(portletMode);
}
try {
// set the action target
tCtrl.setActionTarget(portletName);
// set the action parameters
pCtrl.getParameters().putAll(params);
} finally {
tCtrl.dispose();
pCtrl.dispose();
}
finalUrl = url.writeDispose(new StringWriter()).toString();
return finalUrl;
}

/**
* Generates a url to an action, changing the mode, or changing the window state, can only be used to
* target an action on a public page
* @param pageName
* @param portletName
* @param portletModeName
* @param windowState
* @param params
* @param serverContext
* @param nonPublicPage
* @return
* @throws StateException
* @throws NamingException
* @throws IOException
*/
public static String generateUrl(
String pageName,
String portletName,
String portletModeName,
WindowState windowState,
HashMap params,
MyServerContext serverContext,
boolean nonPublicPage,
PortletType portletType)
throws StateException, NamingException, IOException {
String finalUrl = "";

final StateManager service = getStateManager();

final URLAccessorFactory urlFactory = (URLAccessorFactory) service.getAccessorFactory(URLAccessorFactory.class);

final PortletTargetAccessorFactory tAccFct = (PortletTargetAccessorFactory) service.getAccessorFactory(PortletTargetAccessorFactory.class);
final PortletAccessorFactory pAccFct = (PortletAccessorFactory) service.getAccessorFactory(PortletAccessorFactory.class);

// get a new URL from the URL factory
// null indicates that the current state should be copied
final EngineURL url = urlFactory.newURL(serverContext, false, nonPublicPage, service.newState(), Constants.EMPTY_COPY);
final SelectionAccessorFactory selectionFactory = (SelectionAccessorFactory) service.getAccessorFactory(SelectionAccessorFactory.class);
// Request the selection controller to set the page; pass in the state associated with the created URL
final SelectionAccessorController selectionCtrl = selectionFactory.getSelectionAccessorController(url.getState());
// Set the page; you need the unique name (String) or the ObjectID of that page
selectionCtrl.setSelection(pageName);
// Dispose the accessor (avoids memory leak)
selectionCtrl.dispose();
// get a target controller that operates on the URL-specific state
final PortletTargetAccessorController tCtrl = getPortletTargetAccessor(portletType, tAccFct, url);
// get a portlet controller that operates on the URL-specific state
final PortletAccessorController pCtrl = getPortletAccessor(portletType, pAccFct, portletName, url);
if(windowState != null) {
pCtrl.setWindowState(windowState);
}
if (portletModeName != null) {
PortletMode portletMode = new PortletMode(portletModeName);
pCtrl.setPortletMode(portletMode);
}
try {
// set the action target
tCtrl.setActionTarget(portletName);
// set the action parameters
pCtrl.getParameters().putAll(params);
} finally {
tCtrl.dispose();
pCtrl.dispose();
}
finalUrl = url.writeDispose(new StringWriter()).toString();
return finalUrl;
}

/**
* This is a private method only to be used internally to return the correct PortletAccessor
*
* @param pType PortletType
* @param pAccFct PortletAccessorFactory
* @param portletName uniquename of the portlet on the page
* @param url EngineURL created in the calling method
* @return PortletAccessorController or LegacyPortletAccessorController
*/
private static PortletAccessorController getPortletAccessor(PortletType pType, final PortletAccessorFactory pAccFct, String portletName, EngineURL url) {
try {
if(pType.getPortletType().equals(pType.LEGACY_PORTLET)) {

return pAccFct.getLegacyPortletAccessorController(portletName, url.getState());
} else {
return pAccFct.getPortletAccessorController(portletName, url.getState());
}
} catch (Exception ex){
System.out.println("There was a problem in the getPortletAccessor = " + ex);
return null;
}
}

/**
* @param pType PortletType
* @param tAccFct PortletTargetAccessorFactory
* @param url EngineURL created in calling method
* @return PortletTargetAccessorController this can be of type LegacyPortletTargetAccessorController or just PortletTargetAccessorController
*
*/
private static PortletTargetAccessorController getPortletTargetAccessor(PortletType pType, final PortletTargetAccessorFactory tAccFct, EngineURL url) {
try {
if(pType.getPortletType().equals(pType.LEGACY_PORTLET)) {
return tAccFct.getLegacyPortletTargetAccessorController(url.getState());
} else {
return tAccFct.getPortletTargetAccessorController(url.getState());
}
} catch(Exception ex) {
System.out.println("There was a problem in getPortletTargetAccessor = " + ex);
return null;
}
}



}
-------------------------------------------------------------------------------

package com.ibm.wps.l2.urlspihelper.stateless.utils;

import java.nio.charset.Charset;
import com.ibm.portal.state.accessors.url.ServerContext;

/**
* @author James Barnes
*
*/
public class MyServerContext implements ServerContext {

private String hostname = "";
private String port = "";


/**
* This constructor will set it up so that you can create a link to your portal
* based on the hostname and port passed in
* @param hostname
* @param port
*/
public MyServerContext(String hostname, String port) {
super();
this.hostname = hostname;
this.port = port;
}


/**
* Change this if you have changed your portal context root
* @see com.ibm.portal.state.accessors.url.ServerContext#getContextPath()
*/
public String getContextPath() {
return "/wps";
}

/**
* change this if you have changed it as well for your protected url
* @see com.ibm.portal.state.accessors.url.ServerContext#getHomeProtected()
*/
public String getHomeProtected() {
return "/myportal";
}

/**
* Change this if it is different for the public url
* @see com.ibm.portal.state.accessors.url.ServerContext#getHomePublic()
*/
public String getHomePublic() {
return "/portal";
}

/**
* @see com.ibm.portal.state.accessors.url.ServerContext#getHostName()
*/
public String getHostName() {
return hostname;
}

/**
* @see com.ibm.portal.state.accessors.url.ServerContext#getHostPortHTTP()
*/
public String getHostPortHTTP() {
return port;
}

/**
* if you use ssl and it is different that 443 change it to the correct one
* @see com.ibm.portal.state.accessors.url.ServerContext#getHostPortHTTPS()
*/
public String getHostPortHTTPS() {
return "443";
}

/**
* @see com.ibm.portal.state.accessors.url.ServerContext#getURLCharset()
*/
public Charset getURLCharset() {
return Charset.forName("UTF-8");
}
}


----------------------------------------------------------------------------

package com.ibm.wps.l2.urlspihelper.stateless.utils;

import java.nio.charset.Charset;
import com.ibm.portal.state.accessors.url.ServerContext;

/**
* @author James Barnes
*
*/
public class MyVPServerContext extends MyServerContext {

private String vpRoot = "";


/**
* This constructor lets you create a server context specfically for your virtual portal
* @param hostname
* @param port
* @param vpRoot
*/
public MyVPServerContext(String hostname, String port, String vpRoot) {
super(hostname, port);
this.vpRoot = vpRoot;
}

/**
* Change this if your portal default is different
* @see com.ibm.portal.state.accessors.url.ServerContext#getHomeProtected()
*/
public String getHomeProtected() {
return "/myportal/"+vpRoot;
}

/**
* change this if your public url is different
* @see com.ibm.portal.state.accessors.url.ServerContext#getHomePublic()
*/
public String getHomePublic() {
return "/portal/"+vpRoot;
}

}


---------------------------------------------------------------------------------
package com.ibm.wps.l2.urlspihelper.utils;

import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;

import com.ibm.portal.ObjectID;
import com.ibm.portal.identification.Identification;

/**
* @author James Barnes
* A helper class for getting an objectid to be used when targetting a page
* or portlet from the url generation spi
*/
public class IdentificationHelper {

private static Identification idService = null;

/**
* This method will initialize the class variable for the identification service. That way the lookup does not have to be done everytime.
* @return Identification service
*/
private static Identification getIdService() {
if(idService == null) {
try {
Context ctx = new InitialContext();
Name ctxName = new CompositeName("portal:service/Identification");
idService = (Identification)ctx.lookup(ctxName);
} catch (Exception ex) {
System.err.println("There was a problem getting the identification service = " + ex);
}
}
return idService;

}

/**
* Will allow you to take the string representation of a objectid and get the actual objectid from it.
* @param objectid String representation of the ObjectID
* @return ObjectID
*/
public static ObjectID getObjectID(String objectid) {

ObjectID oId = null;
try {
oId = getIdService().deserialize(objectid);
} catch (Exception ex) {
System.err.println("Problem getting the object id from the string = " + ex);
}
return oId;
}

/**
* This method allows you to get a string representation of the objectid that is passed in
* @param objectid
* @return String representation of the ObjectID
*/
public static String getStringForObjectID(ObjectID objectid) {
String stringOID = "";
try {
stringOID = getIdService().serialize(objectid);
} catch (Exception ex) {
System.err.println("Problem getting the object id from the string = " + ex);
}

return stringOID;
}


}
------------------------------------------------------------------------------
package com.ibm.wps.l2.urlspihelper.utils;
/* @copyright module */
/* */
/* DISCLAIMER OF WARRANTIES: */
/* ------------------------- */
/* The following [enclosed] code is sample code created by IBM Corporation. */
/* This sample code is provided to you solely for the purpose of assisting */
/* you in the development of your applications. */
/* The code is provided "AS IS", without warranty of any kind. IBM shall */
/* not be liable for any damages arising out of your use of the sample code, */
/* even if they have been advised of the possibility of such damages. */

/**
* @author James Barnes
* This class allows you to target the proper accessor in the various url generation
* helper classes
*/
public class PortletType {

public static final String LEGACY_PORTLET = "Legacy";
public static final String STANDARD_PORTLET = "Standard";

public static final PortletType LegacyPortletType = new PortletType(LEGACY_PORTLET);
public static final PortletType StandardPortletType = new PortletType(STANDARD_PORTLET);
private String portletType = "";

/**
* Used to create a PortletType with the given portletType
* @param portletType
*/
public PortletType(String portletType) {
super();
this.portletType = portletType;
}

/**
* Used to get the portlettype for this portlettype
* @return String
*/
public String getPortletType() {
return portletType;
}

}
-------------------------------------------------------------------------------------

Followers