Showing posts with label Utility. Show all posts
Showing posts with label Utility. 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
 

Content decompress (Base64 + Zlib)

I wanted to decompress data getting send to GSA (google search appliance) to verify the actual content. Google Search Appliance uses Base64 encode and Zlib compress technique which improves performance, because less data is sent across the network.

Here is link on GSA Content Compression: https://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/feedsguide/feedsguide.html#1074587

There is api provides by Java that can be used to  compress and decompress data using the java.util.zip package. - http://www.oracle.com/technetwork/articles/java/compress-1565076.html

To decode base64 string you can use class org.apache.commons.codec.binary.Base64 provided by apache commons library.

code snippet that follows:  
String string = "SmF2YWNvZGVnZWVrcw==";
// Get bytes from string
byte[] byteArray = Base64.decodeBase64(string.getBytes());
// Print the decoded array
System.out.println(Arrays.toString(byteArray));


To decompress zlib content you can use Java Byte Array Using Inflater
code snippet that follows: 
public static byte[] decompress(byte[] data) throws IOException, DataFormatException {
    Inflater inflater = new Inflater();  
    inflater.setInput(data); 
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); 
    byte[] buffer = new byte[1024]; 
    while (!inflater.finished()) { 
        int count = inflater.inflate(buffer); 
        outputStream.write(buffer, 0, count); 
    } 
    outputStream.close(); 
    byte[] output = outputStream.toByteArray(); 
    LOG.debug("Original: " + data.length); 
    LOG.debug("Compressed: " + output.length); 
    return output; 
}  

Here is the reference link: https://dzone.com/articles/how-compress-and-uncompress


Download complete source code: https://app.box.com/s/w2wyffurcwdpeetouk56kg2tmg40wjtl

Monday, June 13, 2016

How to set Ephox Edit Live editor as default WCM editor?

Below are the simple steps to changes the WCM editor from default rich text to Ephox edit Live. First of all you have to download Ephox edit live from https://greenhouse.lotus.com/ and install the same application on to your portal server if not already installed.
  • Login to WAS Console.
  • Navigate to Applications->Application Types -> WebSphere enterprise applications.
  • Click on Install and select the .ear file you downloaded and click Next. Keep the default options keep going to next pages.
  • Make sure you select websphere_portal as the server not server1 while installing the .ear and finish the installation and save the configuration.
  • Start the application if its not already started.
  • Login to portal as administrator and navigate to WCM Authoring portlet -> Preferences > Configure.
  • Expand the Rich Text Options section , select Custom Editor in the drop down and enter the following in the text box "/wps/ephox/;jsp/html/EditLiveJavaEditor.jsp"and click OK.
  • Now navigate to WCM Authoring portlet -> Preferences > Edit Shared Settings.
  • Expand the RichTextOptions section , select Custom Editor in the drop down and enter the following in the text box "/wps/ephox/;jsp/html/EditLiveJavaEditor.jsp"and click OK.
  • Now go to any content item that uses rich text and you can see its using ephox edit live edit instead of IBM's default RTE.
  •  You can easily toggle between the design view and code view in the bottom left corner.
 Ephox edit Live is a Java Editor and Java Runtime is required on wcm author's machine to be able to use this applet in a browser.

Ephox has also released a javascript based rich text editor that you can apply on WebSphere Portal 8.5.0.0 with CF06 or higher.
Here is some more info on this: https://greenhouse.lotus.com/plugins/plugincatalog.nsf/assetDetails.xsp?action=editDocument&documentId=86189C1DAC5B1D3B85257E4500199F1B

About Rich Text editor options on WCM: https://www.ibm.com/support/knowledgecenter/SS3JLV_8.0.0/wcm/wcm_config_authoringportlet_richtext.html

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

Sunday, July 1, 2012

clearing wcm cache

Simple JSP Utility to clear IBM WCM cache on below URL which might be needed sometime as to clear cached WCM data. You just need to follow two steps -

1)      Place the JSP  under <Profile
Root>\installedApps\<nodename>
\wcm.ear\ilwwcm.war\jsp\html

2)      access it by using the following URL -
http://<hostname>:<port>/wps/wcm/jsp/html/clearcaches.jsp

https://wiki.base22.com/display/btg/IBM+Lotus+Web+Content+Management+%28WCM%29+6.1+Clear+Caches+JSP+Utility

Tuesday, March 6, 2012

Class Finder

A simple utility to find a particular class name in a directory containing jar, war, and ear files. The application recursively decends into the directory looking for files that end in ".jar", ".war", and ".ear" (case insensitive which is not really the standard). Additionally, the program finds any normal files that end in .class also.
Why did I write this? Because I find that when I'm looking for a particular class to compile with I never seem to know which jar file it is in. This utility simplifies that task. It is basically like a Unix "find" command piped to the "jar" command that would "grep" for the class name. Cross-platform issues made it easier to put this into a small java application rather than have to install Cygwin on every Windows box I use.

Downloads

ClassFinder can be downloaded from:
These files contain a precompiled jar file along with all of the source code and an ant build file.

Usage

A sample command line might look like (should be all on one line):
java -classpath lib/classfinder.jar com.xigole.util.ClassFinder -d some/directory/name -c SomeClassName
or
java -jar lib/classfinder.jar -d some/directory/name -c SomeClassName
The command line arguments are:
  • -d specifies the directory name to use. This must be a directory. This is a required argument.
  • -c specifies the class name to look for in the jar files. The search is case insensitive unless you specify the -p option. This is a required argument. Note that this argument can be a class name like MyClassName in which case ClassFinder will look for the provided name regardless of the package. Alternately, you can specify a package declaration like com.xigole.MyClassName. Either way ClassFinder is simply looking for a pattern that looks like the given string. Regular expressions are not supported.
  • -p pay attention to the class name case. This makes it easier to find something like "Log" when many classes may be in the "logging" package
  • -v an optional argument that verbosely prints out each file that is being searched.

Important!

ClassFinder requires a 1.4 and above JDK.

Eclipse/RSA/RAD Shortcuts

Open Resource (ctrl+shift+r)
This shortcut allows to open any file in your workspace by only typing the first letters of a file name or a mask, like applic*.xml. The only drawback of this shortcut is that it is not available in all perspectives. To enable this: Right click on the toolbar, select Customise Perspective and make sure 'Open Resource' is checked.

Open Type (ctrl+shift+t)
This shortcut allows to browse the workbench for a type to open in an editor or type hierarchy.

Friday, September 23, 2011

Dojo Charts

Dojo comes with an amazing charting library, in the form of dojox.charting. You can create various 2D chart, 3D Chart, Pie, Animated Chart. Follow link : http://docs.dojocampus.org/dojox/charting/

Sample html code for Columns chart using dojo :
<html>   
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" djConfig="parseOnLoad: true">
        </script>
        <script type="text/javascript">
            dojo.require("dojox.charting.Chart2D");
            dojo.addOnLoad(function() {
                var c = new dojox.charting.Chart2D("chartOne",{
                    title: "Revenue per year",
                    titlePos: "bottom",
                    titleGap: 5,
                    titleFont: "normal normal normal 15pt Arial",
                    titleFontColor: "orange"
                });

                c.addPlot("default",{type: "Columns", gap: 5, minBarSize: 3, maxBarSize: 20})
                .addAxis("x", {
                    fixLower: "major",
                    fixUpper: "minor",
                    labels: [{value: 1, text: "Item1"}, {value: 2, text: "Item2"},{value: 3, text: "Item3"}]})
                .addAxis("y", {
                    title: "Revenue ($ Million)",
                    vertical: true,
                    fixLower: "major",
                    fixUpper: "major",
                    includeZero: true})
                .addSeries("Series A",
                    [{y: 4, color: "red"},{y: 2, color: "green"},{y: 6, color: "blue"}]);
                c.render();
            });
        </script>
    </head>
    <body>
        <div id="chartOne" style="width: 400px; height: 240px; margin: 30px auto 0px auto;">
        </div>
    </body>
</html>

Thursday, September 15, 2011

AJAX proxy

AJAX proxy is required to connect several different target hosts and make cross domain calls. As browsers don't allow to send ajax request to different host other than origin server so, there is a need of intermediate server side handler to serve request.
In websphere either you can add Ajax proxy capability in your own project or you can use websphere default Global Ajax proxy.

The global proxy configuration of the portal is located in a separate enterprise application that is deployed during the portal installation. The corresponding enterprise application archive is named AJAX Proxy Configuration.ear. The file proxy-config.xml that represents the global configuration is located in the WAR file wp.config.proxy.war.
To update the global proxy configuration, redeploy the enterprise application archive that contains the modified proxy-config.xml file and restart it. You do not need to restart the entire portal server.
For security reasons the global proxy configuration does not define any specific access policies. In other words, by default, the proxy blocks each request unless you add access policies to "unlock" your trusted sites.

AJAX proxy configurations file (proxy-config.xml) allows you to create specific access policy to restrict the set of allowed HTTP operations
You can also configure AJAX proxy to support single sign-on, the configuration makes the proxy forward the respective LTPA and JSessionID cookies.

URL format to use proxy is
<protocol>://<portal-domain>/<proxyurl>/<protocol>/<host>%3a<port>/<url>?<query>
Examples
Refer to the following sample proxy URLs. They show how you can load a URL via the proxy depending on the context path mapping in the proxy configuration.
URL: http://www.ibm.com/developerworks/news/dw_dwtp.rss
Context path mapping (from proxy-config.xml): <mapping contextpath="/proxy" url="*"/>
Proxy URL: http://myportal.com:10040/wps/proxy/http/www.ibm.com/developerworks/news/dw_dwtp.rss

You can also specify timeout in proxy-config.xml, this will be applicable to each proxy:policy urls
i.e.
<proxy:meta-data>
<proxy:name>connection-timeout</proxy:name>
<proxy:value>600000</proxy:value>
</proxy:meta-data>

Proxy also support http basic authentication and you can also automate passing user/password using jquery
To support http basic authentication modify proxy-config.xml
<proxy:policy acf="none" url="http://<url>/*" basic-auth-support="true">
To pass user/password using jquery use this :
<script language="JavaScript">
$.ajax({
type: "GET",
cache: false,
dataType: "xml",
url: "http://localhost:10039/.MEMCREST/proxy/http/some.com/getresult",
username: 'username',
password: 'password',
success: function(data) {
var $xml = $(data);
//iterate $xml and generate html markup
},
error : function(jqXHR, textStatus, errorThrown) {
alert("error: "+textStatus);
}
});
</script>

Lets say you want to access youtube channel content inside your webpage, do the following :
1) Edit proxy-config.xml file add followling lines so that only url which start from http://www.youtube.com/user/* will be served from this proxy
<?xml version="1.0" encoding="UTF-8"?><proxy:proxy-rules xmlns:proxy="http://www.ibm.com/xmlns/prod/sw/ajax/proxy-config/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <proxy:mapping contextpath="/proxy" url="*"/>
    <proxy:policy acf="none" url="http://www.youtube.com/user/*">
        <proxy:actions>
            <proxy:method>GET</proxy:method>
            <proxy:method>POST</proxy:method>
        </proxy:actions>
    </proxy:policy>
</proxy:proxy-rules>
2) Call youtube url using proxy, I have used here Jquery ajax
<script src="http://code.jquery.com/jquery-latest.js"></script>
<div id="results"></div>
<script language="JavaScript">
    $.ajax({
         type: "GET",
         cache: false,
         url: "http://localhost:10039/.YouTubeChannel/proxy/http/www.youtube.com/user/BoxOffice", //Requesting to proxy to get response from youtube
         success: function(html) {
             $("#results").append(html);
        },
        error : function(jqXHR, textStatus, errorThrown) {
            alert("error: "+textStatus);
        }
   });
</script>

For More Info Visit IBM Infocenter link : http://publib.boulder.ibm.com/infocenter/wpdoc/v6r1/topic/com.ibm.wp.ent.doc_v6101/dev/ajax_proxy.html

Tuesday, September 13, 2011

Process RSS/ATOM Feed on client side through JavaScript

There are few opensource javascript library API available to parse feed data and it gives you result in dom xml or either in JSON format. Once you get the result iterate through feed items and generate you own html markup
1)  Google feed api (http://code.google.com/apis/feed/)- With the Feed API, you can download any public Atom, RSS, or Media RSS feed using only JavaScript, so you can easily mash up feeds with your content. This work for cross domain website.
There is cloud service hosted by google to test this api. http://code.google.com/apis/ajax/playground/#load_feed
Only limitation of google hosted api are you need to generate api key for you server hostname.

2) JQuery JFeed plugins (http://plugins.jquery.com/project/jFeed): 
jFeed is a generic RSS/ATOM feed parser.
jFeed currently parses RSS 0.91, 0.92, 1.0, 2.0 and Atom 1.0 feeds.
Download sample code from here - https://github.com/jfhovinne/jFeed

Other way of displaying feed data is, send ajax request to feed_url use Ajax proxy(http://absolutebrain.blogspot.com/2011/09/ajax-proxy.html) in case of feed_url is pointing to different server and iterate through xml dom elements to get desired element values.
Starting with 1.5 jQuery has built-in xml parsing capabilities, which makes it pretty easy to do this without plugins or 3rd party services.
Sample Code :
<script src="http://code.jquery.com/jquery-latest.js"></script>
<div id="results"></div>
<script language="JavaScript">
    $.ajax({
         type: "GET",
         cache: false,
         dataType: "xml",
         url: "http://localhost:10039/.YouTubeChannel/proxy/http/toi.timesofindia.indiatimes.com/rssfeedstopstories.cms", //Requesting to proxy to get response from timeofindia
         success: function(data) {
             var $xml = $(data);
            $xml.find("item").each(function() {
                $("#results").append($(this).find("title").text()+":"+$(this).find("pubDate").text()+"<br>");
            });
        },
        error : function(jqXHR, textStatus, errorThrown) {
            alert("error: "+textStatus);
        }
   });
</script>

Tuesday, August 2, 2011

Setting J2EE Module Dependency in Rad


Using the Java Build path you can only configure the compile time dependencies, and there are various options, such as listing a project as referenced project.

However for J2EE applications you also need to take care that the dependencies are resolved at runtime.

It is best to use a method that resolves both runtime and compile time dependencies with the same settings.

Assuming both projects are associated with the same EAR, then you can simply r-click on the project TestMyWebApp and choose:

RAD 7.5: Java EE Module dependencies
RAD 8: Deployment Assembly

and select the project MyWebApp.

For more information, see the InfoCenters:

https://www-304.ibm.com/support/docview.wss?rs=2042&uid=swg27012580

RAD 7.5 Java EE Module dependencies
http://publib.boulder.ibm.com/infocenter/radhelp/v7r5/index.jsp?topic=/com.ibm.jee5.doc/topics/tjdepend.html

RAD 8 Deployment Assembly
http://publib.boulder.ibm.com/infocenter/radhelp/v8/index.jsp?topic=/com.ibm.javaee.doc/topics/cdeploymentassembly.html

Tuesday, June 21, 2011

Image / Thumbnail for PDF

Pdf-renderer - http://java.net/projects/pdf-renderer
Download the source code using SVN and use ant to build.
After running ant build, copy PDFRenderer.jar from dist folder and set into your project classpath.
You can use this api to generate Image/Thumnail for various PDF pages.

Java 5 supports following image types : "bmp jpeg wbmp gif jpg png" and mime types "image/png image/jpeg image/x-png image/vnd.wap.wbmp image/bmp image/gif".

API will fail to generate image If pdf has unsupported java image type like cmyk embedded.
 
PDF Renderer is a LGPL licensed pure-java library that makes this very simple:

public class Pdf2Image {

    /**
     * @param args
     */
    public static void main(String[] args) {
        File file = new File("c:/sample.pdf");
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");

            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            PDFFile pdffile = new PDFFile(buf);
            // draw the first page to an image
            int num=pdffile.getNumPages();
            for(int i=0;i<num;i++)
            {
                PDFPage page = pdffile.getPage(i);
               
                //get the width and height for the doc at the default zoom               
                int width=(int)page.getBBox().getWidth();
                int height=(int)page.getBBox().getHeight();               
               
                Rectangle rect = new Rectangle(0,0,width,height);
                int rotation=page.getRotation();
                Rectangle rect1=rect;
                if(rotation==90 || rotation==270)
                    rect1=new Rectangle(0,0,rect.height,rect.width);
               
                //generate the image
                BufferedImage img = (BufferedImage)page.getImage(
                            rect.width, rect.height, //width & height
                            rect1, // clip rect
                            null, // null for the ImageObserver
                            true, // fill background with white
                            true  // block until drawing is done
                    );

                ImageIO.write(img, "png", new File("c:/"+i+".png"));
            }
        }
        catch (FileNotFoundException e1) {
            System.err.println(e1.getLocalizedMessage());
        } catch (IOException e) {
            System.err.println(e.getLocalizedMessage());
        }
    }
}

Wednesday, June 15, 2011

Visual formatting model - DIV HTML Floats Issue

A float is a box that is shifted to the left or right on the current line. The most interesting characteristic of a float (or "floated" or "floating" box) is that content may flow along its side (or be prohibited from doing so by the 'clear' property). Content flows down the right side of a left-floated box and down the left side of a right-floated box.

Here is showing what happens when a float overlaps borders of elements in the normal flow.

Image showing a floating image
that overlaps the borders of two paragraphs: the borders are
interrupted by the image.  

A floating image obscures borders of block boxes it overlaps.
The following example illustrates the use of the 'clear' property to prevent content from flowing next to a float.
Example(s):
Assuming a rule such as this:

p { clear: left }
formatting might look like this:
Image showing a floating
image and the effect of 'clear: left' on the two paragraphs.   
Both paragraphs have set 'clear: left', which causes the second paragraph to be "pushed down" to a position below the float — "clearance" is added above its top margin to accomplish this.

Content Source - http://www.w3.org/TR/CSS2/visuren.html

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

}