Showing posts with label Custom Portlet. Show all posts
Showing posts with label Custom Portlet. Show all posts

Friday, June 17, 2016

Create a url to change language on Portal

You can use following code to change the language on Portal.
<portal-navigation:url command="ChangeLanguage">
  <portal-navigation:urlParam name="locale" value="<language>"/>
</portal-navigation:url>
 
There was a problem with this when navigational state is cleared. 
This happens if  bookmarks to friendly URLs are used for navigation or 
the navigational state is cleared intentionally.
 
You can this technique to store language value in cookie temporarily and 
It sets the locale information, if no locale information can be 
found in the navigational state.
 
Configure cookie support language using this 
url: http://www-01.ibm.com/support/docview.wss?uid=swg1PM17679
 

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, December 21, 2012

ResourceServing Portlet JSR286



In general to implement serveResource you need to follow these steps :
 
1) Implement serveResource method in Portlet
 
2) Define the content Page - This content page is JSP that the serveResource() method forwards. Always create a separate content page for the output of the serveResource() method. A resource JSP is not mandatory because the output can be written directly on the response. The output of the serveResource() method can be HTML, XML, JSON, static resource and so on.
i.e.
public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {
                String targetJsp="sample_resource.jsp";
                //Invoke business methods here
                //.......
                PortletRequestDispatcher rd=getPortetContext().getRequestDispatcher(targetJsp);
                rd.include(request,response);
}
Note : Don't use renderRequest and renderResponse object in resource.jsp instead use resourceRequest and resourceResponse if required

3) Generate the ResourceServing URL : The resource serving URL targets the serveResource() method
<div id="divToReplace">
                Content will be fetched dynamically
</div>

<form id="myForm" method="post" action="<portlet:resourceURL/>">
                <input type="submit" value="Get Data"/>
</form>
<script>
                var form=dojo.byId("myForm");
                dojo.connect(form,"onsubmit",function(event) {
                                //stop the submit event since we want to control form submission
                                event.preventDefault();
                                event.stopPropagation();

                                var xhrArgs={
                                                form: dojo.byId("myForm"),
                                                handleAs : "text",
                                                load : function(data) {
                                                                //callback function invoked when the response comes back successfully
                                                                dojo.byId("divToReplace").innerHTML=data;
                                                }
                                };
                                //perform AJAX call
                                dojo.xhrPost(xhrArgs);
                });
</script>

Tuesday, June 26, 2012

Sitemap portlet for WebSphere Portal v7

Default Sitemap out of box portlet in websphere portal v7 was stopped working after applying fix pack2, so I had to develop Sitemap portlet in JSR286 with some basic features -
1) Pulling page and its sub-pages using navigational service
2) Portlet has view and config mode, from the config mode this portlet can be customized to pull specific portal pages only and upto certain subpage level.

Download Sitemap.war with source code -
 https://www.box.com/s/1af1eb84c99af6448c6b

Thursday, June 23, 2011

Portal Rich Text editor

If your portlet is extended from FacesPortlet then you can easily place a rich text editor in the jsp page through jsf/rte tag library.

Sample code :
<h:form styleClass="form" id="form1>
    <h:panelGrid styleClass="panelGrid" id="grid1">
        <hx:commandExButton type="submit" value="Submit" styleClass="commandExButton" id="button1"></hx:commandExButton>
        <r:inputRichText width="702" height="352" id="richTextEditor1" value="#{pc_TextEditorView.richText}"></r:inputRichText>
    </h:panelGrid>
</h:form>

If you just want to display the RTE submitted text in an JSF output tag then all the extra RTE characters are also displayed. Like - &lt;span style="font-weight: bold;"&gt;Name : Mike&lt;/span&gt;&lt;br style="font-weight: bold;"&gt;

So u need to set the "escape" attribute of the h:outputText command controls whether HTML characters are "escaped" (turned into text) or sent to the browser as HTML characters. To pass the HTML through instead of escaping it, set "escape='false'" on the outputText tag. After setting the value for “escape=false”, you will get value in HTML format like. Ex- <span style="font-weight: bold;">Name : Mike</span><br style="font-weight: bold;">
The output text includes the HTML tags instead of using them to format the text.

This is because of Portal server has a "cross site scripting" protection setting that is ON by default. This protection escapes all HTML being passed in request parameters. Since RTE uses HTML, it also gets escaped and the result is what you see.

Portal server Administrator can turn it off, via parameter
security.css.protection in ConfigService.properties
Or we can manually unescapeHtml, while request is summited -
org.apache.commons.lang.StringEscapeUtils.unescapeHtml(richTextEscapedHtml);


Note -
1)Make sure you have classloader set to PARENT_LAST for your portlet.
Side note:

2)Use the escape attribute with extreme care. If someone somehow got javascript into the text:
code
<script type="text/javascript">alert("i can do anything now");</script>
This would be executed by the browser when rendered. You need to make sure the text being rendered with escape="false" is safe text.

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();
        }
    }

}

Personalizing Page & Portlet using external data (user resource)

Objective : The objective of this documentation is to introduce you to an important feature in Portal 6.1 called Attribute Based Administration using external resource collection

Overview : Attribute Based Administration provides a facility to customize the site layout for individual users or groups of users via “Visibility Rules”. Visibility Rules instruct Portal to: Show or hide pages and portlets  based on dynamic characteristics that are determined at runtime according to business rules.

Note: All the screenshots are captured from RSAv7.5.4

1)     For running this Lab exercise prerequisites are :
a.     Portal Server v6.1.0.3 or higher
b.    Derby10.1(Network Server) – Derby Client JDBC Driver
c.     RSA or RAD v7.0 or higher
2)     Start derby database
a.     Start derby service using the following command  -
${WebSphere_AppServer_HOME)\derby\bin\networkServer\startNetworkServer.bat
3)     Create a database and table in derby using RSA/RAD
a.     Setting JDBC Driver for Derby10.1  client
                                          i.    Open the RSA – ignore if already open
                                         ii.    Goto Window-> Preferences (
                                        iii.    Expand “Data Management”->”Connectivity” tab then click on “Driver Definitions”
                                        iv.    From the list of Database driver name , select “Derby 10.1 – Derby Client JDBC Driver Default” and click on edit button, “Edit Driver Definition” a new window will open
                                         v.    Switch to “Jar List” tab
                                        vi.    Specify correct JDBC driver jar file for Derby10.1 client Ex - ${WebSphere_AppServer_HOME)\derby\lib\derbyclient.jar By clicking on “Add Jar/Zip” button.
b.    Create the database & table required
                                          i.    Open the RSA – ignore if already open
                                         ii.    Switch to “Database Development” perspective
                                        iii.    Define “Database Connections” – Right click on “Database Connections” and chose “New…” option from context menu. Specify database connection parameters similar to below captured screenshot. Password is user

                                        iv.    Click on “Test Connection” button to check Derby DB availability. Once db pinged successfully click on Finish button
                                         v.    Right click on “pzn_user_resource” database connection and choose “New Sql Script” option
                                        vi.    In SQL Script window paste following SQL Scripts to generate sample table and its data
Note: Users_id column must contain the same value for user’s uid attribute that is defined in WPS server user repository Like – LDAP

CREATE TABLE app.USERS (
            USER_ID VARCHAR(100) NOT NULL primary key,
            DEPT_ID INTEGER
);
insert into app.users values('uid=wpadmin,o=defaultWIMFileBasedRealm',1);      
insert into app.users values('uid=shashi,o=defaultWIMFileBasedRealm',2);

                                       vii.    Right click on “SQL Script window” and select “Run SQL” option; it will execute all the sql statement written in SQL editor window. Resultant user’s table will create and be populated with sample data.

4)     Create a empty portlet project
a.     Open the RSA – ignore if already open
b.    Switch to web perspective
c.     Create a new empty portlet project and specify filed value similar to below captured screenshot and click on finish button.



5)     Create “Content or User Resource”
a.     Open the RSA – ignore if already open
b.    Select & Right Click on “PZN_demo” portlet project and select “New->Other” option
c.     Expand “Portal”->”Personalization” and select “Content or User Resource” and click on next button.
d.    Chose “SQL” as a protocol and “Web users” as resource collection as captured in below screenshot. Click on next button.





e.     Select “pzn_user_resource” as existing database connection and click on next button



f.     The personalization resource wizard opens. On the Tables tab, highlight USERS by single clicking on it. Click the arrow button pointing to the right to select the table. Click Primary Table to mark it as the primary table.





g.    Select the Columns tab. On the Columns tab, move all columns to the right by clicking the double arrow button. Notice the primary key is the column User_ID.



h.     Click the Mappings tab. On the Mappings tab, select Dept_id and click Populate.





i.      Click the Select buttons and expand APP > USERS to select DEPT_ID for the Description and Value fields. Click OK.



j.      Click the Deployment tab.
k.     On the Deployment tab, change the datasource to jdbc/pzndemo. This datasource is required to define in WAS.



l.      Click Next


m.   Set the package name as pzndemo. Select Include schema names in the generated Resource Runtime Manager.




n.     Click Finish.
You can now see the new JAVA classes in your project:





6)     Create a datasource using appserver console
a.     Start the portal sever – if not already started
b.    Open a browser and type https://localhost:10041/ibm/console and enter logic credentials
c.     Define “J2c Authentication Data”
                                          i.    Expand "Security" section and click on "Secure administration, applications and infrastructure"
From right side box "Java Authentication and Authorization Service" expand it and click on "J2C authentication data"



                                         ii.    Click on New Button
                                        iii.    Specify pzndemo_derby as alias, user as user and password as user





                                        iv.    Click on apply button, then click on save link
Once you click on save link you will get screen similar to below, newly create “J2c authentication data is listed”



d.    Define Derby JDBC provider
                                          i.    Expand "Resources">JDBC and click on JDBC Provider
In the JDBC Provider block, select Server as websphere_portal and click on new button





                                         ii.    Specify JDBC provider information then click on next button then finish button



                                        iii.    Click on Save link





e.     Create a databsource with JNDI name “jdbc/pzndemo”
                                          i.    Expand "Resources"> "JDBC" click on "Data sources" link
In the Data Sources block, select Server as WebSphere_Portal and click on New Button



                                         ii.    Specify datasource name, JNDI name & Component-managed based authentication alias



                                        iii.    Click on Next.



                                        iv.    Select JDBC Provider just created




                                         v.    Click on next
                                        vi.    Specify database name “pzn_user_resource” and click on next button then Finish button



                                       vii.    Click on save link. Select the newly created Datasource and click on “Test Connection” button. If all setting is correct then you will get following message.


7)     Deploy & Import Personalization Workspace resource collections
a.     Deploy pzn_demo personalization code
                                          i.    Place pzndemo class files into a directory accessible by that portlet. To do this, export the pzndemo folder in RSA under PZN_demo/Java Resources: src as a JAR file. Make the target location PortalServer_root/pzn/prereq.pzn/collections/pzndemo.jar. Accept the defaults and click Finish



b.    Restart Portal Server
c.     Import Personalization resource collections
                                          i.    Login to portal server using admin credentials
                                         ii.    Click the Applications>Content>Personalization>Business Rules
                                        iii.    In the Personalization Navigator portlet, click New > Folder



                                        iv.    Enter the name Pzn demo and click save





                                         v.    Change to the Pzn demo folder.



                                        vi.    Click Import
                                       vii.    Browse to find the Users.hrf file in your {RSA workspace}/PZN_demo/WebContent/WEB-INF/pzn-resourceCollections/pzndemo project directory.
                                      viii.    See the resource collection in the Workspace.





8)     Create Simple Visibility Rules (We need to display or hide a portlet based on personalized rule)
a.     Login to the portal server using admin credentials
b.    Click the Applications>Content>Personalization>Business Rules
c.     In the Personalization Navigator portlet, Change to the Pzn demo folder
Then click New > Rule



d.    Type "PZN_demo Visibility Rule" in the New Rule field.





e.     Select “Visibility Rule” from the Rule Type drop-down list.
f.     click on “attribute” on the rule editor and select Users -> Dept_id



g.    Specify 1 for the value and click submit.



h.     Click Save. The completed rule will list like the following example.



9)     Apply Personalization Rule to Page or Portlet
a.     Open a Web Browser window and browse to http://localhost:10040/wps/portal Login using admin credentials
b.    Create a new page under Home ex.“About WebSphere” using portal administration and add some out-of-box portlet like – “About WebSphere Portal”. Move your mouse to the About WebSphere & click on the down arrow icon to open the context menu.  Click on “Edit Page Layout”





c.     Click on Show Portlet Rule Mappings



d.    Click on Select Rule





e.     From Personalization Picker select “PZN demo Visibility Rule” rule and click on ok


f.     Click Done on the Page Layout Page.  Depending on the users dept_id the portlet that was configured with this rule would be visible or not.




*****Lab Files are here
http://www.box.net/shared/b00thbvypqqrazt19hyb
http://www.box.net/shared/r9nyfmccba87nc4ot0sl