Showing posts with label Portal Service. Show all posts
Showing posts with label Portal Service. Show all posts

Tuesday, July 19, 2016

Add the portlet session bean to the Personalization engine

Add the portlet session bean to the Personalization engine
Register the session bean with the Personalization engine. To enable the Personalization engine to leverage data in session bean:
  1. Export the session bean class as a jar file with full class path.
  2. Copy it to <wp>/pzn/v6.0/collections directory on the WebSphere Portal machine.
  3. Restart WebSphere Portal server to load the jar file.
To register the session bean with Personalization:
  1. Create an application object in Personalization.
  2. Session key and class name are required fields for the creation of the application object
  3. Specify the fully qualified class name
Note: Visibility rule uses caching per session so if the visibility rule is meant to use dynamic data, the results will not change based on the dynamic data. To implement visibility rule on dynamic data you need to disable caching.

Same thing can be done using object cache, we can update values in object cache from application and the stored values can be read from the custom pzn SelfInitializationApplicationObject implementation class.

Different technique can be also used to hide the portlet i.e. portlet eventing.

Hide portlet through external class (SelfInitializationApplicationObject): http://wpcertification.blogspot.com/2011/01/how-to-show-or-hide-portal-or-portlet.html

Issue discussed on setting Personalization Attributes from Portlets:
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014177630

Thursday, February 4, 2016

Using Application Server>URL resources to manage J2EE property files and external service url

Use following code to retrieve url resource using jndi
InitialContext initCtx = new InitialContext();
URL url = (java.net.URL) initCtx.lookup(jndi);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();

With this method you can either enter web service url in resource field or properties file path.

Note: You need to restart the server to lookup the url resource from code.

Reference link: http://www.ibm.com/developerworks/websphere/library/techarticles/0502_botzum/0502_botzum.html

How to access authentication alias from WebSphere Application Server> J2C

You can use the following code to obtain credentials from J2C authentication data entry:

import com.ibm.wsspi.security.auth.callback.Constants;
import com.ibm.wsspi.security.auth.callback.WSMappingCallbackHandlerFactory;
import javax.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;

Map map = new HashMap();
map.put(Constants.MAPPING_ALIAS, "YOUR_J2C_DATA_ALIAS");
CallbackHandler callbackHandler = WSMappingCallbackHandlerFactory.getInstance().getCallbackHandler(map, null);

LoginContext loginContext = new LoginContext("DefaultPrincipalMapping", callbackHandler);
loginContext.login();

Subject subject = loginContext.getSubject();
Set credentials = subject.getPrivateCredentials();

PasswordCredential passwordCredential = (PasswordCredential) credentials.iterator().next();

String user = passwordCredential.getUserName();
String password = new String(passwordCredential.getPassword());

Reference link: http://stackoverflow.com/questions/4663534/how-to-access-authentication-alias-from-ejb-deployed-to-websphere-6-1/6355992#6355992

Wednesday, July 8, 2015

Translate portal to myportal when user is logged in

The Problem

Suppose you have a public-facing site for anonymous portal users. But suppose also that the same site also has some private resources requiring users to authenticate for access.
  • In this scenario, an authenticated user will be logged out if they try to access a public resource that has the anonymous context in the URL (i.e. /wps/portal/... instead of /wps/myportal/...).
  • BUT, we cannot just make all of our links contain /wps/myportal to get around the issue because then anonymous users will be prompted to login even if the resource is public.
  • What we need is a way to let links to public resources contain the anonymous context (/wps/portal/...), but we need to automatically transform that into (/wps/myportal) if the user happens to be logged in.

The Solution

There is a configuration option that does exactly this! Here's how you enable it on WPS 7 or greater.
  • In the Deployment Manager or WAS console, navigate to Resource environment providers > WP ConfigService > Custom properties</li>
  • Look for the property 'uri.home.substitution'. If it's not already in the list, add the property (as type java.lang.String) and set the value to 'true'. If it's already in the list, just set the value to true.</li>
  • Apply and save your changes to the master configuration. In a stand-alone environment, you then need to restart your server. In a clustered environment, you need to synchronize the nodes and then restart the cluster.</li>

Summary

The uri.home.substitution option determines whether a public URL should be translated to a protected URL if a user session exists. It is false by default and can be set to <em>true</em>.


Reference Link: https://wiki.base22.com/display/btg/Translate+portal+to+myportal+when+user+is+logged+in

Sunday, February 22, 2015

POC: Piece of Content URL

Passing query parameters to JSR-286 portlets using existing IBM WebSphere Portal capabilities at http://www.lotus.com/ldd/portalwiki.nsf/page.xsp?documentId=0971A3B3CE4F3AEA852578800051E2C7&action=openDocument

Sample Code for PortletPocService in Websphere Portal Server  at
 http://ourwebsphereportal.blogspot.com/2011/10/sample-code-for-portletpocservice-in.html

To pass render or action parameter you need to create DeeplinkResolver project.

Friday, January 30, 2015

Disable managed-pages feature to share wcm library with virtual portal

Portal v8 and above maintains their own wcm library and wcm library can't be shared between base portal and virtual portals until manages-page feature is disabled.

Run the disable-managed-pages task from the WebSphere/ConfigEngine directory.

ConfigEngine.bat disable-managed-pages -DPortalAdminPwd=wpsadmin -DWasPassword=wpsadmin


More Info: http://infolib.lotus.com/resources/portal/8.0.0/doc/nl_NL/PT800ACD002/wcm/wcm_config_mngpages_disable.html

Thursday, January 29, 2015

WebSphere 8 Auto Deploy

You need setup monitor directory to automatically deploy application.
 Log in to the Admin console and click "Global deployment Settings" from the Applications section of the Left-Hand-Side navigation menu.
 
Refer these link :
http://www-01.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.base.doc/ae/urun_app_global_deployment.html
http://www.webspheretools.com/sites/webspheretools.nsf/docs/WebSphere%208%20Auto%20Deploy

Wednesday, January 28, 2015

Enable session on anonymous pages



Enable public sessions for portal. The reason is that the theme/portlet needs a valid session for its run time, and by default, sessions are not enabled on anonymous pages in the portal. By default, sessions are only created when a user authenticates and logs in to the portal.
Enable public sessions by setting the parameter public.session to true (String type) in the portal "WP NavigatorService > Custom properties > New" in the WebSphere Integrated Solutions Console.

Friday, July 6, 2012

How to enable remote debugging for a WebSphere Web application using RAD

Step 1:

To be able to debug an Enterprise Application you must enable the Debugging service for WebSphere Application server.



Ensure you set up an appropriate port that the development client is able to access.
Things to remember here :
1)       You must start server is debug mode either by selecting ‘Enable service at server startup’ or by using RAD
2)       Take a note of JVM Debug port



Step 2:


Using RAD (IBM Rapid Application Developer)

Switch to Debug Perspective
Open Debug configurations and Set-up remote debug details using appropriate port as set in the Application server's Debugging service.



Note: If you get this dialog, it is because the server is not started or you have a firewall issue or incorrect connection details.




Finally Set a break point on deployed web project.


Tuesday, June 14, 2011

Verify Websphere Portal User's Password

There are two ways to verify user's password -

1) Use "UserRegistry"
public static boolean checkUserAuthenticatedLDAP(String userId, String password) {
        try {
              Context ctx = new InitialContext();
              com.ibm.websphere.security.UserRegistry reg = (com.ibm.websphere.security.UserRegistry) ctx.lookup("UserRegistry");
              String res = reg.checkPassword(userId, password);
return res != null;
        } catch (Exception ex) {
              return false;
        }
  }

2) Use "LoginContext"
/**
     * This method validates the user based on the user id and password
     * attributes, If the user id or password is not valid then throws Exception.
     *
     * @param userId
     * @param password
     * @return boolean
     * @throws Exception
     */
    public boolean checkUserAuthenticated(String userId, String password) throws Exception {
        javax.security.auth.login.LoginContext loginContext = null;
        Subject subject = null;
        try {
            loginContext = new javax.security.auth.login.LoginContext("WSLogin", new com.ibm.websphere.security.auth.callback.WSCallbackHandlerImpl(userId, password));
        } catch (javax.security.auth.login.LoginException e) {
            throw new Exception("Cannot create LoginContext", e);
        }
        try {
            loginContext.login();
            subject = loginContext.getSubject();
        } catch (com.ibm.websphere.security.auth.WSLoginFailedException e) {
            throw new Exception("Password is incorrect", e);
        } catch (Exception e) {
            throw new Exception("Unknown username", e);
        }
        if (subject == null)
            throw new Exception("Password is incorrect");

        return true;
    }

Monday, June 13, 2011

Puma Service/User Details in (Theme, Servlet, Portlet)

a) Get details of User in Theme for loggedIn User
1) Use following tag lib to get basic user attribute value
<%@ taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v6.0/portal-fmt" prefix="portal-fmt" %>
<portal-fmt:user attribute="givenName" /> <portal-fmt:user attribute="sn" />
2) To get other info like in which group user belongs to
<%
com.ibm.portal.puma.User portalUser=  (com.ibm.portal.puma.User) request.getAttribute(com.ibm.portal.RequestConstants.REQUEST_USER_OBJECT);
 if(portalUser!=null) {
    java.util.List groups = portalUser.getGroups();
        for (int i=0; i< groups.size() ; i++){
            com.ibm.portal.puma.Group grp = (com.ibm.portal.puma.Group)groups.get(i);
        }
}
%>

b) Get details of User in Servlet for loggedIn User
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.portal.um.PumaHome;
import com.ibm.portal.um.PumaLocator;
import com.ibm.portal.um.PumaProfile;
import com.ibm.portal.um.User;
import com.ibm.portal.um.exceptions.PumaAttributeException;
import com.ibm.portal.um.exceptions.PumaMissingAccessRightsException;
import com.ibm.portal.um.exceptions.PumaModelException;
import com.ibm.portal.um.exceptions.PumaSystemException;

public class UserInfo extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private PumaHome pumaHome;

    @Override
    public void init() throws ServletException {
        super.init();

        try {
            Context context = new InitialContext();
            Name pumaJndiName = new CompositeName(PumaHome.JNDI_NAME);
            pumaHome = (PumaHome) context.lookup(pumaJndiName);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String UIDParam = request.getParameter("uid");

        PumaLocator pLocator = pumaHome.getLocator();
        PumaProfile pProfile = pumaHome.getProfile();

        try {
            List<User> users =pLocator.findUsersByAttribute("uid", UIDParam);

            // get a list of attributes defined for this User
            List attribNames = pProfile.getDefinedUserAttributeNames();
            // Get a map of attribute values for this user
            Map userDetails = pProfile.getAttributes(users.get(0), attribNames);

            String userEmail = (String) userDetails.get("mail");
            System.out.println("UserInfo.doGet()" + UIDParam + ":"+ userEmail + ":" + users.size());
        } catch (PumaSystemException e) {
            e.printStackTrace();
        } catch (PumaAttributeException e) {
            e.printStackTrace();
        } catch (PumaMissingAccessRightsException e) {
            e.printStackTrace();
        } catch (PumaModelException e) {
            e.printStackTrace();
        }
    }

}

c) Get details of User in Portlet for loggedIn User

import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.um.PumaController;
import com.ibm.portal.um.PumaEnvironment;
import com.ibm.portal.um.PumaLocator;
import com.ibm.portal.um.PumaProfile;
import com.ibm.portal.um.User;
import com.ibm.portal.um.portletservice.PumaHome;
import com.ibm.websphere.security.UserRegistry;

public class UserProfileService {
    // This class uses PUMA SPI to access the LDAP and retrieve user profile information
    private static PumaHome pumaHome;

    // List of all Attribute Names that are defined in LDAP for USER group
    public static final String LAST_NAME = "sn";
    public static final String FIRST_NAME = "givenName";
    public static final String EMAIL = "mail";
    public static final String PASSWORD_USER_PROPERTY = "password";
    public static final String USERID_USER_PROPERTY = "uid";
    public static final String COMMONNAME_USER_PROPERTY = "cn";
   
    // Method to connect and create a PumaHome object
    public UserProfileService() {
        try {
            Context ctx = new InitialContext();
            PortletServiceHome psh = (PortletServiceHome) ctx
                    .lookup("portletservice/com.ibm.portal.um.portletservice.PumaHome");

            if (psh != null) {
                pumaHome = (PumaHome) psh.getPortletService(PumaHome.class);
            }

        } catch (Exception ne) {
            // ne.printStackTrace();
            pumaHome = null;
        }

    }

    public Map getUserProfile(PortletRequest req) {
        Map userDetails = null;
        // Util method that uses PUMA SPI to load user attributes from LDAP into
        // // a domain object (LmsUser)
        if (pumaHome == null) {
            return null;
        } else {
            try {
                // first get a PumaProfile object
                PumaProfile pumaProfile = pumaHome.getProfile(req);
                // get a list of attributes defined for this User
                List attribNames = pumaProfile.getDefinedUserAttributeNames();

                // Get a map of attribute values for this user
                userDetails = pumaProfile.getAttributes(pumaProfile
                        .getCurrentUser(), attribNames);
                System.out.println("userDetails::::::"+userDetails);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return userDetails;
    }

    public static PumaHome getPumaHome() {
        if (pumaHome == null) {
            try {
                PortletServiceHome psh;
                Context ctx = new InitialContext();
                psh = (PortletServiceHome) ctx.lookup(PumaHome.JNDI_NAME);
                if (psh != null) {
                    pumaHome = (PumaHome) psh.getPortletService(PumaHome.class);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return pumaHome;
    }

    protected static PumaLocator getPumaLocator(PortletRequest portletRequest) {
        PumaLocator pumaLocator = getPumaHome().getLocator(portletRequest);
        return pumaLocator;
    }
    protected static PumaProfile getPumaProfile(PortletRequest portletRequest) {
        PumaProfile pumaProfile = getPumaHome().getProfile(portletRequest);
        return pumaProfile;
    }

    protected static PumaEnvironment getPumaEnvironment() {
        PumaEnvironment pumaEnvironment = getPumaHome().getEnvironment();
        return pumaEnvironment;
    }
    protected static PumaController getPumaController(PortletRequest portletRequest) {
        PumaController pumaController = getPumaHome().getController((ActionRequest) portletRequest);
        return pumaController;
    }
    public static void changePasswordLDAP(ActionRequest actionRequest, String password) {
        final PumaProfile pf = getPumaProfile(actionRequest);
        final PumaController pc = getPumaController(actionRequest);
        final PumaEnvironment pe = getPumaEnvironment();
        final Map userSetAttr = new HashMap();
        final List passwd=new ArrayList();
        passwd.add(password);
        // set AD password attribute in the Map
        userSetAttr.put(PASSWORD_USER_PROPERTY, passwd);
        try {
            pe.runUnrestricted(new PrivilegedExceptionAction() {
                public Object run() {
                    try {
                            User user = pf.getCurrentUser();
                            pc.setAttributes(user, userSetAttr);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

PumaEnvironment's runUnrestricted

All the users in portal having some access rights associated with it. So this restricts users to update and look for the other users & groups attributes value.
So the solution in this scenario is – run your code as admin.
This can be done through PumaEnvironment's runUnrestricted method.
See the sample code below –

PumaEnvironment pe = pumaHome.getEnvironment();
try {
    pe.runUnrestricted(new PrivilegedExceptionAction() {
        public Object run() {
            //write your logic here to find groups

            return null;
        }
    });
} catch (PrivilegedActionException e) {
    throw e;
}

Reflecting LDAP attribute changes in WebSphere Portal immediately

To fix this problem have to disabling VMM and Puma caching.

There are two scenarios from where LDAP values get changed and those value wouldn't reflect in Portal immediately :
a) Explictly made changes in ADS via some tool or using ADS console
b) Some time ads policies are enforced and sometimes changes in some attribute values change the other attribute value internally.
Like - If we change password for user then password_last_set timestamp value will get updated automatically.

To disable VMM and PUMA caching here are the steps:

a.       Add a new entry in WP Puma Store Service to disable PUMA cache
                                                               i.      Login to IBM console goto “Resource environment entries -> WP PumaStoreService -> Custom properties”
                                                             ii.      Set the property store.puma_default.userManagement.cacheMode to false to turn off the PUMA cache. Ex-
store.puma_default.userManagement.cacheMode        false
b.      Use the $AdminTask to update the cache properties accordingly. To turn off the cache for the LDAP in VMM
                                                               i.      Open a command prompt
                                                             ii.      Switch to wp_profile/bin and type wsadmin
                                                            iii.      Run the following command to disable attribute caching
1.       $AdminTask updateIdMgrLDAPAttrCache {-id TestADS -enabled false}
2.       $AdminConfig save
                                                           iv.      Run the following command to disable searchresult caching
1.       $AdminTask setIdMgrLDAPSearchResultCache {-id TestADS -enabled false}
2.       $AdminConfig save

I had followed this link also tuning of WebSphere Portal Caching is described on this page -
http://www-01.ibm.com/support/docview.wss?uid=swg21379992

Sunday, June 12, 2011

WebSphere SSO & LDAP Configuration Links

Here's the URL for SSO configuration between WebSpherev6.1 & Connection v2.5:
http://publib.boulder.ibm.com/infocenter/ltscnnct/v2r0/index.jsp?topic=/com.ibm.connections.25.help/c_sec_config_sso.html 
Also consider following points when doing SSO : 
* make sure that LDAP is same on Portal and Connections and make sure that the Realm name is exactly the same 
* make sure that both servers are accessed through a common domain like .yourwebsite.com 
* just export LTPA from one server to another and you should be set 
* just make sure that in the Web SSO settings for each server the domain name is the same, and put a period in front of it 
* ex: .yourwebsite.com 
* one last thing, make sure the time and time zones are the same on both servers 
* otherwise you could generate a cookie that has already expired on the next server

Friday, June 10, 2011

LTPAToken from the credential vault (JaasSubjectCredential)

Retrieve the token from the credential vault (JaasSubjectCredential) and build up the http connection from that credential.

JaasSubjectCredential cred = null;
        try {
        cred = getLTPAToken(request);
        } catch (PortletServiceUnavailableException e) {
        e.printStackTrace();
        } catch (NamingException e) {
        e.printStackTrace();
        } catch (CredentialVaultException e) {
        e.printStackTrace();
        }
        URLConnection docConnection = cred.getAuthenticatedConnection(new URL("<inputURL>"));



 private JaasSubjectCredential getLTPAToken(PortletRequest request) throws NamingException, CredentialVaultException,
        PortletServiceUnavailableException {
    Context ctx = new InitialContext();
    PortletServiceHome cvHome = (PortletServiceHome) ctx
        .lookup("portletservice/com.ibm.portal.portlet.service.credentialvault.CredentialVaultService");
    CredentialVaultService cvService = (CredentialVaultService) cvHome.getPortletService(CredentialVaultService.class);
    JaasSubjectCredential credential = null;
    try {
        credential = (JaasSubjectCredential) cvService.getCredential(CredentialVaultService.PREDEFINED_SLOT_USER_JAAS_SUBJECT,
            CredentialTypes.LTPA_TOKEN, new HashMap(), request);
    } catch (CredentialVaultException e) {
        e.printStackTrace();
    }
    return credential;
    }

Thursday, May 26, 2011

Portlet caching issue may occurred when calling portletResponse.getPortletOutputStream()

If portlet caching is enabled and you calling portletResponse.getPortletOutputStream() it will throw exceptions.
To resolve this -
1) Either disabled the portlat caching and restart the portal server
2) Install the fix pack http://www-01.ibm.com/support/docview.wss?uid=swg1PK93614