I've been head down in several fun XPages projects for a while, and it has left me little time to blog as of late. Something I intend to rectify going forward.
So here's a small example of something you can do with managed beans, different from what I've shown in the past. This managed bean creates a Gravatar object that you can use to insert a user's Gravatar image into your XPage. It's uses the Java code example from gravatar.com, and expands upon it a little bit to create a simple function to create the url.
To create this, open your java package explorer, and create your source folder as I have explained in previous posts, and create a new Java package. In this example, I'm using my com.ZetaOne.util package. Next, inside the package, create a Java class called "Gravatar"
Paste in the following expanded Java code from gravatar.com
package com.ZetaOne.util;
import java.io.*;
import java.security.*;
import java.net.URLEncoder;
public class Gravatar {
public static String hex(byte[] array) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i]
& 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
}
public static String md5Hex (String message) {
try {
MessageDigest md =
MessageDigest.getInstance("MD5");
return hex (md.digest(message.getBytes("CP1252")));
} catch (NoSuchAlgorithmException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
public static String generateURL(String emailAddress, String defaultURL, String imageSize) {
try {
return "http://www.gravatar.com/avatar/" + md5Hex(emailAddress) + ".jpg?size=" + imageSize + "&d=" + URLEncoder.encode(defaultURL, "UTF-8");
} catch (Exception e) {
return defaultURL;
}
}
}
The key function here is generateURL, which takes three arguments, the user's Email Address, a URL to an image to use if the user has no gravatar, and the size of the gravatar image returned.
Next, you create the entry in your faces-config.xml file in the WebContent/WEB-INF folder of your NSF.
Gravatar
com.ZetaOne.util.Gravatar
none
Notice here the managed-bean-scope is set to none. This means that the object is created and discarded each time it is used. Since we aren't using the object to store any data, or provide any persistence, this is fine.
Now you can use the gravatar object in your XPage like this:
And there you go! An example on how to use custom Java code as a managed bean to generate objects you can use in XPages.