Thursday, October 22, 2009

How to get path(/wps/portal or /wps/myportal) in IBM WebSphere Portal V6.1 theme

Import following object in jsp or class

import com.ibm.portal.state.accessors.url.ServerContext;
import com.ibm.wps.services.ServiceManager;
import com.ibm.wps.services.config.ConfigService;
import com.ibm.wps.state.accessors.url.ServerContextOnConfigFactory;
import com.ibm.wps.state.phases.ServerContextFactory;


ConfigService configService = (ConfigService)ServiceManager.getService(com.ibm.wps.services.config.ConfigService.class);
ServerContextFactory ctxFactory = new ServerContextOnConfigFactory(configService);
ServerContext serverContext = ctxFactory.newServerContext((HttpServletRequest)(request));

System.out.println(serverContext.getContextPath());
System.out.println(serverContext.getHomeProtected());
System.out.println(serverContext.getHomePublic());

Wednesday, October 21, 2009

Configuring a stand‐alone LDAP user registry on Windows

The LDAP configuration is quite quick to perform using a parent properties file.
Copy the attached file, wp_security_ids.properties you’re your
\ConfigEngine\config\helpers folder. Then from a command
prompt run the following commands

cd \ConfigEngine
.\ConfigEngine.bat validate-standalone-ldap
-DWasPassword=
-DparentProperties=config/helpers/wp_security_ids.properties

This will validate the wp_security_ids.properties file to ensure that you have
sufficient LDAP connectivity and the properties file is correct before actually making
the LDAP configuration in the portal server. Do not proceed unless the results end
with the following text:

Return Value: 0

Once the validation has passed, run the command to set up the LDAP security:
.\ConfigEngine.bat wp-modify-ldap-security
-DWasPassword=
-DparentProperties=config/helpers/wp_security_ids.properties
Ensure the output from this also ends with the result text:

Return Value: 0

At this point, the portal should be configured. To confirm this, start the portal and
attempt to log in. The user name and password should be as follows:

User ID: ( user id from wp_security_ids.properties)
Password: ( password from wp_security_ids.properties)


Sample wp_security_ids.properties

# *****************************************************************
#
# Licensed Materials - Property of IBM
#
# 5724-L21
#
# Copyright IBM Corp. 2008 All Rights Reserved.
#
# US Government Users Restricted Rights - Use, duplication or
# disclosure restricted by GSA ADP Schedule Contract with
# IBM Corp.
#
# *****************************************************************

###############################################################################
###############################################################################
##
##
## VMM Stand-alone LDAP configuration
## wp-modify-ldap-security
## wp-update-standalone-ldap
##
## IDS, SECUREWAY
##
###############################################################################
###############################################################################

# The id specifies a unique identifier for the repository within the cell
# Characters that are not allowed in normal XML strings ( & < > " ' ) cannot be used in the repository ID.
standalone.ldap.id=

# Specifies the host name of the primary LDAP server. This host name is either an IP address or a domain name service (DNS) name.
standalone.ldap.host=

# Specifies the LDAP server port.
standalone.ldap.port=389

# Specifies the distinguished name for the application server to use when binding to the LDAP repository.
standalone.ldap.bindDN=uid=hrcdevbind,cn=people,cn=dev,ou=hrc,o=hb

# Specifies the password for the application server to use when binding to the LDAP repository.
standalone.ldap.bindPassword=pswd1wpsbind

# Specifies the type of LDAP server to which you connect
# Supported values on WAS 6.1: IDS4, IDS51, IDS52, IDS6, SECUREWAY
# Note: If your LDAP server version is not listed, enter the value for the highest listed version of your server
# Supported values on WAS 7: IDS
standalone.ldap.ldapServerType=IDS6

# Specifies the LDAP filter that maps the short name of a user to an LDAP entry.
# For example, to display entries of the object class = inetOrgPerson type by their IDs, specify inetOrgPerson:uid.
# This field takes multiple objectclass:property pairs delimited by a semicolon (;).
# note: not used during node federation to DMGR with WAS ldap security enabled
standalone.ldap.userIdMap=*:uid

# Specifies the LDAP filter that maps the short name of a group to an LDAP entry.
# Specifies the piece of information that represents groups when groups display. For example, to display groups by their names, specify *:cn.
# The asterisk (*) is a wildcard character that searches on any object class in this case.
# This field takes multiple objectclass:property pairs, delimited by a semicolon (;).
# note: not used during node federation to DMGR with WAS ldap security enabled
standalone.ldap.groupIdMap=*:cn

# Specifies the LDAP filter that identifies user-to-group relationships.
# Specifies which property of an objectclass stores the list of members belonging to the group represented by the objectclass.
# For directory types SecureWay, and Domino, this field takes multiple objectclass:property pairs, delimited by a semicolon (;).
# For IBM Directory Server, Sun ONE, and Active Directory, this field takes multiple group attribute:member attribute pairs delimited by a semicolon (;).
# For more information about this syntax, see the LDAP directory service documentation.
# note: not used during node federation to DMGR with WAS ldap security enabled
standalone.ldap.groupMemberIdMap=

# Specifies the LDAP user filter that searches the user registry for users.
# For example, to look up users based on their user IDs, specify (&(uid=%v)(objectclass=inetOrgPerson))
# note: not used during node federation to DMGR with WAS ldap security enabled
standalone.ldap.userFilter=(&(uid=%v)(objectclass=inetOrgPerson))

# Specifies the LDAP group filter that searches the user registry for groups.
# note: not used during node federation to DMGR with WAS ldap security enabled
standalone.ldap.groupFilter=(&(cn=%v)(|(objectclass=groupOfNames)(objectclass=groupOfUniqueNames)))

# Specifies a user ID and password in the repository that is used for internal process communication.
# note: not used during node federation to DMGR with WAS ldap security enabled
standalone.ldap.serverId=uid=hrcdevbind,cn=people,cn=dev,ou=hrc,o=hb
standalone.ldap.serverPassword=pswd1wpsbind

# The security context of this server. A realm with this name will be created.
standalone.ldap.realm=hrcdevrealm1


# The ID of the WAS admin user. The ID must exist in the LDAP server.
standalone.ldap.primaryAdminId=uid=hrcdevbind,cn=people,cn=dev,ou=hrc,o=hb
standalone.ldap.primaryAdminPassword=pswd1wpsbind

# The ID of the portal admin user. The ID must exist in the LDAP server.
standalone.ldap.primaryPortalAdminId=uid=hrcdevadmin,cn=people,cn=dev,ou=hrc,o=hb
standalone.ldap.primaryPortalAdminPassword=passw0rd

# The user group with admin permission in portal. The group must exist in the LDAP server.
standalone.ldap.primaryPortalAdminGroup=cn=hrcdevadmins,cn=groups,cn=dev,ou=hrc,o=hb

# The LDAP base entry.
# This is the startpoint for all LDAP searches of Websphere Application Server Security
standalone.ldap.baseDN=cn=dev,ou=hrc,o=hb

########################
##
## LDAP entity types
##
########################

# Entity type Group

# The search filter that you want to use to search the entity type.
# VMM uses this filter as an addition during search requests in your environment
# The syntax is like a standard LDAP searchfilter like (objectclass=groupOfUniqueNames)
# In general this value can be left blank
standalone.ldap.et.group.searchFilter=

# One or more object classes (separated by ';') for the entity type.
standalone.ldap.et.group.objectClasses=groupOfUniqueNames

# The object class(es) (separated by ';') to use when an entity type is created. If the value of this parameter is the same as the objectClass parameter, you do not need to specify this parameter.
standalone.ldap.et.group.objectClassesForCreate=

# The search base or bases to use while searching the entity type.
standalone.ldap.et.group.searchBases=


# Entity type PersonAccount

# The search filter that you want to use to search the entity type.
# VMM uses this filter as an addition during search requests in your environment
# The syntax is like a standard LDAP searchfilter like (objectclass=inetOrgPerson)
# In general this value can be left blank
standalone.ldap.et.personaccount.searchFilter=

# One or more object classes (separated by ';') for the entity type.
# Please check this value with the objectclass used in your LDAP for type User
standalone.ldap.et.personaccount.objectClasses=inetOrgPerson

# The object class(es) (separated by ';') to use when an entity type is created. If the value of this parameter is the same as the objectClass parameter, you do not need to specify this parameter.
standalone.ldap.et.personaccount.objectClassesForCreate=

# The search base or bases to use while searching the entity type.
standalone.ldap.et.personaccount.searchBases=

########################
##
## End LDAP entity types
##
########################

###################################################
##
## Group member attributes
##
###################################################

# The name of the LDAP attribute that is used as the group member attribute. For example, member or uniqueMember.
standalone.ldap.gm.groupMemberName=member

# The group object class that contains the member attribute. For example, groupOfNames or groupOfUnqiueNames.
# If you do not define this parameter, the member attribute applies to all group object classes.
standalone.ldap.gm.objectClass=groupOfNames

# The scope of the member attribute. The valid values for this parameter include the following:
# direct - The member attribute only contains direct members.
# nested - The member attribute that contains the direct members and the nested members.
standalone.ldap.gm.scope=direct

# If you create a group without specifying a member, a dummy member will be filled in to avoid creating an exception about missing a mandatory attribute.
standalone.ldap.gm.dummyMember=uid=test


###############################
# Default parent, RDN attribute
###############################

# The default parents to be set for the the entity types PersonAccount and Group
standalone.ldap.personAccountParent=cn=people,cn=dev,ou=hrc,o=hb
standalone.ldap.groupParent=cn=groups,cn=dev,ou=hrc,o=hb

# The RDN attribute names for the entity types PersonAccount and Group
# To reset all the values of the rdnProperties parameter, specify a blank string ("").
standalone.ldap.personAccountRdnProperties=uid
standalone.ldap.groupRdnProperties=cn

###################################################
##
## End Group member attributes
##
###################################################



###############################################################################
##
## Advanced Properties
##
###############################################################################


###################
# Group config
###################

# The name of the membership attribute. For example, memberOf in an active directory server and ibm-allGroups in IDS.
standalone.ldap.gc.name=

# Updates the group membership if the member is deleted or renamed. Some LDAP servers, for example, Domino server, do not clean up
# the membership of the user when a user is deleted or renamed. If you choose these LDAP server types in the ldapServerType property,
# the value of this parameter is set to true. Use this parameter to change the value. The default value is false.
standalone.ldap.gc.updateGroupMembership=

# The scope of the membership attribute. The valid values for this parameter include the following:
# direct - The membership attribute only contains direct groups.
# nested - The membership attribute that contains the direct groups and the nested groups.
# all - The membership attribute contains direct groups, nested groups, and dynamic members.
# The default value is direct.
standalone.ldap.gc.scope=direct


# Controls how aliases are dereferenced. The default value is always. Valid values include:
# always - always deference aliases
# never - never deference aliases
# finding - deference aliases only during name resolution
# searching - deference aliases only after name resolution
standalone.ldap.derefAliases=always

# Indicates the authentication method to use. The default value is simple. Valid values include: none or strong.
standalone.ldap.authentication=simple

# The LDAP referral. The default value is ignore. Valid values include: follow, throw, or false.
standalone.ldap.referral=ignore

# Specifies the delimiter used for this realm. The default value is /.
standalone.ldap.delimiter=/

# Whether the query matches case sensitivity.
# note: not used during node federation to DMGR with WAS ldap security enabled
standalone.ldap.ignoreCase=true

# Specifies whether secure socket communication is enabled to the LDAP server.
# When enabled (sslEnabled=true), the Secure Sockets Layer (SSL) settings for LDAP are used.
# The default value is false.
standalone.ldap.sslEnabled=false

# Specifies the name of the application server SSL configuration to be used for SSL enabled LDAP server.
# This property is used to specify a non default SSL configuration if standalone.ldap.sslEnabled=true is set
standalone.ldap.sslConfiguration=

# Specifies whether to map X.509 certificates into a LDAP directory by exact distinguished name or certificate filter.
# Specify the certificate filter to use the specified filter for the mapping, if client certificate authentication is used
# for portal server.
# Valid values include: EXACT_DN, CERTIFICATE_FILTER
standalone.ldap.certificateMapMode=EXACT_DN

# Specifies the filter certificate mapping property for the LDAP filter, if client certificate authentication is used
# for portal server.
# The filter is used to map attributes in the client certificate to entries within the LDAP repository.
standalone.ldap.certificateFilter=

# Should be set to true by default to reuse the LDAP connection.
# note: not used during node federation to DMGR with WAS ldap security enabled
standalone.ldap.reuseConnection=true

# Specifies the timeout value in miliseconds for an LDAP server to respond before aborting a request.
standalone.ldap.searchTimeLimit=120000

# Defines if VMM will enable the ConnectionPool
standalone.ldap.connectionPool=false

# Indicates if sorting is supported or not. The default value is false.
standalone.ldap.supportSorting=false

# Indicates if paging is supported or not.
standalone.ldap.supportPaging=false

# Indicates if transactions are supported or not. The default value is false.
standalone.ldap.supportTransactions=false

# Specifies if the external ID is unique. The default value is true.
standalone.ldap.isExtIdUnique=true

# Indicates if external names are supported or not. The default value is false.
standalone.ldap.supportExternalName=false

# Indicates to translate RDN or not. The default value is false.
standalone.ldap.translateRDN=false

# The value of the search count limit.
standalone.ldap.searchCountLimit=500

# The value of search page size.
standalone.ldap.searchPageSize=

# Indicates to return to the primary LDAP server when it is available. The default value is true.
standalone.ldap.returnToPrimaryServer=

# Indicates the polling interval for testing the primary server availability.
# The value of this parameter is specified in minutes. The default value is 15.
standalone.ldap.primaryServerQueryTimeInterval=

# Indicates the property name used for login.
standalone.ldap.loginProperties=uid

# The maximum number of context instances that can be maintained concurrently by the context pool.
# The default value is 20.
standalone.ldap.cp.maxPoolSize=20

###############################################################################
###############################################################################
##
##
## End - VMM Stand-alone LDAP configuration
##
##
###############################################################################
###############################################################################

Enable Remember Me Cookie in IBM WebSphere Portal V6.1

You can follow these steps to Enable Stepup Authentication on your server.After following the enablement steps,you should be able to see the Authentication Level in Resource Permissions portlet from portal admin

Log into the WAS Administrative Console and go to Security >Secure administration, applications, and infrastructure > Web security > Single sign-on (SSO)










Verify that both Interoperability Mode and Web inbound security attribute propagation are enabled

Open the wkplc.properties file and set values for following properties

# Defines the key which is used to enc
# sua_user does not need to match to a real user e.g use myname as
value
# sua_serversecret_password will be used as the key
sua_user=remembermeuser
sua_serversecret_password=remembermepassword
#Defines if Rememberme should be
authenticatoin
#
#
enable_rememberme=true

Execute the enable-stepup - authentication Configuration task by executing this command
ConfigEngine.bat enable-setup-aunthentication - DWasUserId = -DWasPassword=

Sample Remember Me cookie Portlet

This sample Portlet demonstrate how to use Remember Me cookie service to find out userId for
the user on anonymous page.

public class RememberMePortlet extends javax.portlet.GenericPortlet {
PortletServiceHome psh;
/**
* @see javax.portlet.Portlet#init()
*/
public void init() throws PortletException{
super.init();
try {
javax.naming.Context ctx = new javax.naming.InitialContext();
psh = (PortletServiceHome)ctx.lookup(RememberMeCookieService.JNDI_NAME);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


public void doView(RenderRequest request, RenderResponse response) throws
PortletException, IOException {
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());
try {
RememberMeCookieService rememberMeService =
psh.getPortletService(RememberMeCookieService.class);
if(rememberMeService.isRememberMeCookieEnabled()){
System.out.println("RememberMeCookie is enabled");
System.out.println("User Name " + rememberMeService.getUserID(request));
System.out.println("Is Remember Me Cookie Set " +
rememberMeService.isCookieSet(request));
response.getWriter().println("Invalidate remember me cookie");
}else{
System.out.println("RememberMeCookie is disabled");
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
}

Monday, October 19, 2009

Access the url parameter from IBM WebSphere Portal V6.1 by using RunData

Here I have simple Portlet Code.

public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {

String phoneId = getparamter("PhoneId" request);
}

private String getparamter(String key, RenderRequest request) {
String value = null;

try {
RunData rd = RunData.from((ServletRequest) request);
String strURL = rd.getRequestURL();
log.info("Request URL is " + strURL);
String strSplit = strURL.substring(strURL.indexOf('?') + 1);
log.info("Parameter URL is" + strSplit);
StringTokenizer tokenizer = new StringTokenizer(strSplit);
while (tokenizer.hasMoreElements()) {
String token = (String) tokenizer.nextElement();
if (token.indexOf(key) != -1) {
value = token.substring(token.indexOf("=") + 1);
break;
}
}
log.info("key value in getparamter :" + value);
if (value.indexOf("&") > 0) {
value = value.substring(0, value.indexOf("&"));
log.info("Parameter URL is" + value);
}
} catch (Exception e) {
log.error("No value retrieved from URL");
e.printStackTrace();
}
return value;
}

Thursday, October 15, 2009

How to use Httpsession for user data sharing in IBM WebSphere Portlet V6.0

1) Basic classes

package com.session;

import java.io.Serializable;
import java.util.Iterator;

public interface SharedSession {

public abstract void setAttribute(Serializable key, Serializable value);

public abstract Serializable getAttribute(Serializable key);

public abstract void removeAttribute(Serializable key);

public abstract Iterator iterator();


public abstract String getId();
}

-------------------------------------------------------------------------------
package com.session;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

public class SharedSessionFactory {
private static ThreadLocal tl = new ThreadLocal() {
protected Object initialValue() {
return null;
}
};

/**
* Used by filter, do not use directly
* @param ss
*/
public static void set(SharedSession ss) {
tl.set(ss);
}

public static SharedSession getSession() {
return (SharedSession)tl.get();
}

/**
*
* @param hs
* @return
* @deprecated Use getSession()
*/
public static SharedSession getSession(HttpSession hs) {
return getSession();
}

/**
* @param fc
* @return
* @deprecated Use getSession()
*/
public static SharedSession getSession(FacesContext fc) {
return getSession();
}


}

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

package com.session.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.session.SharedSession;
import com.session.SharedSessionFactory;
import com.session.impl.SimpleSharedSessionImpl;

public class SharedSessionFilter implements Filter {
private final static String SHARED_SESSION_LABEL = "SharedSessionFilter.SharedSession";

public void destroy() {
// nop
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

System.out.println("SharedSessionFilter.doFilter called");

if (request instanceof HttpServletRequest) {
HttpSession hs = ((HttpServletRequest)request).getSession(false);
if (hs != null) {
SharedSession ss = (SharedSession)hs.getAttribute(SHARED_SESSION_LABEL);
if (ss == null) {
// create new and attach to session
ss = new SimpleSharedSessionImpl(hs);
hs.setAttribute(SHARED_SESSION_LABEL, ss);
}
SharedSessionFactory.set(ss);
}
}
chain.doFilter(request, response);
SharedSessionFactory.set(null);
}

public void init(FilterConfig arg0) throws ServletException {
// nop
}

}

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

package com.session.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.session.SharedSession;

public class SimpleSharedSessionImpl implements SharedSession {

private Map attributes = null;
private String id = null;

public SimpleSharedSessionImpl(HttpSession hs) {
super();
attributes = new HashMap();
id = hs.getId();
}

/**
* @see nl.pv.mpb.session.SharedSession#setAttribute(java.io.Serializable, java.io.Serializable)
*/
public void setAttribute(Serializable key, Serializable value) {
attributes.put(key, value);
}

/**
* @see nl.pv.mpb.session.SharedSession#getAttribute(java.io.Serializable)
*/
public Serializable getAttribute(Serializable key) {
return (Serializable)attributes.get(key);
}

/**
* @see nl.pv.mpb.session.SharedSession#removeAttribute(java.io.Serializable)
*/
public void removeAttribute(Serializable key) {
attributes.remove(key);
}

/**
* @see nl.pv.mpb.session.SharedSession#destroy()
*/
public void destroy() {
attributes = null;
}

/**
* @see nl.pv.mpb.session.SharedSession#iterator()
*/
public Iterator iterator() {
return attributes.keySet().iterator();
}

/**
* @see nl.pv.mpb.session.SharedSession#getId()
*/
public String getId() {
return id;
}

public String toString() {
return id + ": " + attributes;
}

}

------------------------------------------------------------------------------------------
Location : C:\IBM\WebSphere\profiles\wp_profile\config\cells\win2k\applications\wps.ear\deployments\wps\wps.war\WEB-INF


sharedsession
com.session.filter.SharedSessionFilter



sharedsession
/portal/*


sharedsession
/myportal/*


-------------------------------------------------------------------------------------------------
Uses :

package com.ibm.testsharedsessionportletone.nl;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.session.SharedSession;
import com.session.SharedSessionFactory;
import com.ibm.faces.portlet.FacesPortlet;

public class TestPortletOne extends FacesPortlet {

public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
System.out.println("value set in session : TestPortletOne");
SharedSession session = SharedSessionFactory.getSession();
session.setAttribute("name", "harish");
super.doView(request, response);
}

public void processAction(ActionRequest arg0, ActionResponse arg1)
throws PortletException {
// TODO Auto-generated method stub
super.processAction(arg0, arg1);
}

}

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

package com.ibm.testsharedsessionportlettwo.nl;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.ibm.faces.portlet.FacesPortlet;
import com.session.SharedSession;
import com.session.SharedSessionFactory;

public class TestPortletTwo extends FacesPortlet {

public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {

SharedSession session = SharedSessionFactory.getSession();
session.getAttribute("name");

System.out.println("value get in session : TestPortletTwo :"+session.getAttribute("name"));

super.doView(request, response);
}

public void processAction(ActionRequest arg0, ActionResponse arg1)
throws PortletException {
// TODO Auto-generated method stub
super.processAction(arg0, arg1);
}

}

Wednesday, October 7, 2009

IBM Websphere Application Server to initialize a session for an anonymous user for WebShere Portal

Do the following configuration in Websphere Application Server to initialize a session for an anonymous user.



1. from the WebSphere Application Server administration console, select Resources > Resource Environment Providers.

2. Click WP NavigatorService. Under Additional Properties select Custom Properties.

3. Click New to create new custom properties.

4. In the Name field, type public.session .

5. In the Value field, type true.

6. Click OK to confirm the changes.

7. Save the configuration.

8. Stop WAS server

9. Stop Portal server

9. Start Portal server

Accessing parameter from QueryString in IBM WebSphere Portal V6.1

This is very simple in IBM WebSphere Portal V 6.1
Consider we have url : https://localhost:60035/wps/portal/test?PhoneId=35102

Import com.ibm.ws.portletcontainer.core.impl.RenderRequestImpl


Write down code in Portlet.

public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {


RenderRequestImpl renderRequestImpl = (RenderRequestImpl)request;
String phoneId = renderRequestImpl.getRequest().getParameter("PhoneId");
super.doView(request, response);
}

Accessing parameter from QueryString in IBM WebSphere Portal V6.0(any version) by Filter

We can access the parameter from QueryString in IBM WebSphere Portal(any version) by creating J2EE Filter.

Follow the following steps

1) Create Filter classes

package com.filter;

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

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class ParameterFilter implements Filter {

public void destroy() {

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

ServletRequestParameters.set(request.getParameterMap());

// forward the wrapped request to the next filter in the chain
if (chain != null){
chain.doFilter(request, response);
}
ServletRequestParameters.set(null);


}

public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}
}

package com.filter;

import java.util.HashMap;
import java.util.Map;

public class ServletRequestParameters {

private static ThreadLocal tl = new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
}
};

public static Map getAll() {
return (Map)tl.get();
}

static void set(Map params) {
tl.set(params);
}

public static String getParameter(String key) {
String[] values = (String[])getAll().get(key);
if (values != null && values.length > 0) {
return values[0];
}
return null;
}

public static String[] getParameters(String key) {
return (String[])getAll().get(key);
}

public static String getParameter(String key, String defaultValue) {
String value = getParameter(key);
if (value == null) {
value = defaultValue;
}
return value;
}
}


2) Create the jar file of above classes and put it in portal shared dir e.g ../shared/app

3) Register these filter in WPS web.xml. The location web.xml varies by portal version. make sure you find out correct location.


Parameter Filter
com.filter.ParameterFilter



Parameter Filter
/myportal/*



Parameter Filter
/portal/*



4) Access the parameter in Portlet

package com.portal.

import java.io.IOException;
import javax.portlet.*;
import com.alltel.filter.ServletRequestParameters;


public class TestPortlet extends com.ibm.faces.portlet.FacesPortlet {

public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {


String phoneId =ServletRequestParameters.getParameter("phoneId");

System.out.println("name phoneId :"+phoneId);
request.setAttribute("phoneId", phoneId);
super.doView(request, response);
}

}

Accessing parameter from QueryString in IBM WebSphere Portal V6.0

You can access the parameter from QueryString in Portlet. Consider QueryString is like this
http://localhost:60035/wps/portal/checkout?PhoneId=35102


Portlet Code as below :

public class TestPortlet com.ibm.faces.portlet.FacesPortlet {

public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {

String phoneId = getparamter("PhoneId" request);
super.doView(request, response);

}

private String getparamter(String key,RenderRequest request){
String value = null ;
try{
if(request instanceof org.apache.pluto.core.impl.RenderRequestImpl ){
RenderRequestImpl renderRequestImpl = (RenderRequestImpl)request;

if(renderRequestImpl!=null){
String QueryString = renderRequestImpl.getQueryString();
if(QueryString!=null && QueryString.length() > 0){
StringTokenizer tokenizer = new StringTokenizer(renderRequestImpl.getQueryString(),"&");
while (tokenizer.hasMoreElements()) {
String token = (String) tokenizer.nextElement();
if(token.indexOf(key)!=-1){
value = token.substring(token.indexOf("=")+1);
break;
}
}
System.out.println("key value in getparamter :"+value);
}
}

}
}catch(Exception e){
System.out.println("error occured while accessing QueryString "+e.getMessage());
}

return value;
}

Followers