Monday Dec 29, 2008

Custom Realms and Groups in Glassfish

Glassfish  provides support for Custom Realms and Custom Login Modules that are based on the JAAS framework. This post explains how to write a simple Realm class and its corresponding LoginModule, configure them with an illustration of a simple web application that uses this realm.

Custom Realm

The Custom Realm should extend The Realm class is basically meant to provide user and group-related information. The methods to be implemented are

i) public void init(Properties properties )throws BadRealmException, NoSuchRealmException

This method is invoked during server startup when the realm is initially loaded.  The realm can do any initialization it needs in this method. The Properties is a set of key-value pairs configured while creating the Realm and are present in domain.xml. Among the other custom properties, there is a property jaas-context (which is explained later in this post). This property should be set using the call setProperty method implemented in the parent class. If the method returns without throwing an exception, the Enterprise Server assumes that the realm is ready to service authentication requests. If an exception is thrown, the realm is disabled.

ii) public String getAuthType() - This method returns a descriptive string representing the type of authentication done by this realm.

iii) public Enumeration getGroupNames(String user) throws InvalidOperationException, NoSuchUserException -
This method returns the group names the user belongs to as an Enumeration of Strings.

Custom LoginModule

The Custom LoginModule should extend This class should override the method

abstract protected void authenticateUser() throws LoginException

This method performs the actual custom authentication, by either using a database, or LDAP or a file or even a simple Hashtable as illustrated in the attached sample code. The custom login module must not implement any of the other methods, such as login(), logout(), abort(), commit(), or initialize(). Default implementations are provided in AppservPasswordLoginModule which hook into the Enterprise Server infrastructure.

The custom login module can access the following protected object fields, which it inherits from AppservPasswordLoginModule. These contain the user name, password of the user to be authenticated and the currentRealm class.

protected String _username;

protected String _password;

protected  _currentRealm;

The authenticateUser() method should end with a call to the commitUserAuthentication(String[] authenticatedGroupList) method where the authenticatedGroupList is the list of groups the user belongs to.

As can be observed, the realm class is isolated from the LoginModule. The Realm is capable of capturing arbitrary configuration information and can help in obtaining the Group information. The Group information from the Realm can be  populated into the authenticated JAAS subject during commit() phase following a  successful LoginContext.login() call on the  authentication module. This populated group information is then used by the container in its authorization policy decisions.

Attached here is the source code of a simple sample realm class and the custom module. In this example, the Realm class stores the user-group information in a hashtable. The LoginModule class stores the user-password information in a hashtable and performs authentication. It obtains the authenticatedGroupList from the Realm class' getGroups(username) method.

To test this sample(it works with both GF v2 and v3), download and install Glassfish v3 from here, drop the binaries of this realm and custom module in <GF-ROOT>/domains/domain1/lib/, start the server and create the realm using the Admin console. The realm classname should be specified as com.samplerealm.SampleRealm.

An additional realm property jaas-context should be specified to say sampleRealm. This value should refer to the SampleLoginModule class in the


file as follows:

sampleRealm {
       com.samplerealm.SampleLoginModule required;

where sampleRealm refers to the value defined in the jaas-context property.

As can be seen from the source files, the users configured in this realm are userA, userB whose corresponding passwords are abc123, xyz123. userA has been configured in the group devGroup, while userB belongs to testGroup. To test this realm, this web-application can be used.

Observe that the web.xml of the web-app contains the following :


where  SampleRealm in the <login-conf><realm-name> element points to the name of the configured Realm as can be seen in the server's domain.xml

        <auth-realm classname="com.samplerealm.SampleRealm" name="SampleRealm">
          <property name="jaas-context" value="sampleRealm"></property>

To access the web-app using the group names of the user, the following mapping between the role and group is required in sun-web.xml:


where the role-name matches the configured role in the auth-constraint of web.xml


and group-name is the corresponding group the user belongs to as defined in the custom realm class. So if the application is accessed using the user/password: userA/abc123, the user is authorized to view the pages, since he belongs to the devGroup, but not userB/xyz123 (who belongs to testGroup).

Monday Sep 01, 2008

WSRP Consumer in Liferay

    The OpenPortal WSRP Consumer has been integrated with Liferay Portal, and is available in the stable and community builds of WebSynergy. This blog post would illustrate the basic features of this integration. All the features that are available with the Sun's implementation of WSRP 2.0 with the OpenPortal Portlet Container have been integrated with Liferay and consequently with WebSynergy as well. The admin portlets now have the modified look and feel. Here are some screenshots showcasing the Consumer Admin Portlet in WebSynergy.

The WSRP Consumer Admin Portlet:

LR Consumer Admin Portlet

Creating a Consumer:

Viewing the Details of a Consumer: 

As can be observed, this admin portlet supports the major functionalities in WSRP 2.0 Consumer creation - OutOfBand Registration (using RegistrationHandle), Leasing, Registration Properties amongst others. Producer Integration and Producer Admin Portlet are expected to be integrated with Liferay  in the next stable release of WebSynergy.

Thursday Aug 07, 2008

MBR Repair Utility for Windows

Recently I had the privilege of corrupting the MBR of my laptop. The modus operandi - I formatted the Solaris partition from my Windows boot. That consequently corrputed the grub and the Master Boot Record. Only later did I discover that a lot of people I knew had done this quite frequently. A typical solution for this problem was to boot from a live Windows CD, launch the Revocery Console, and run the fixmbr utility. (For Windows versions previous to 2000, the fdisk utility could be used as well, but for the newer versions, this utility was scrapped, since Recovery Console was provided).

An atypical but useful solution would be to boot Windows from any live CD (I used Belenix), boot Windows from the command prompt, and run this Mbrfix utility. You don't need to have a Windows Live CD or Recovery Console. This atypical solution was provided by an extremely resourceful and benevolent colleague, and it worked.

Tuesday Jun 17, 2008

Leasing for Remote Portlets

WSRP 2.0 offers Leasing of Portlets as part  of the specification. Leasing is the process by which a Consumer registers with a Producer for a specified time period, after which the Consumer Registration is rendered invalid. Lifetime is an optional parameter in the Registration offered by V2 producers. The OpenPortal WSRP project (Sun's open source implementation of WSRP ) has implemented this feature using the Open Source Portlet Container 2.0 . Check this wiki page for more information on portlet leasing.

A quick guide to Leasing with Open WSRP and PC 2.0 

1. Download and install PC 2.0 and WSRP  . For instructions on download, refer to the install instructions

2. Create a V2 producer (supporting Inband Registration) using the Producer Admin Portlet. Publish a few portlets and enable the Producer.

3. Create a V2 consumer. Check the Lifetime Supplied checkbox. Specify the Valid No of Days, Hours and Minutes, say 0,0,15. This means that the Registration is valid only for the next 15 minutes. Click the Consumer to view the time until which Registration is valid.

4. Create  a remote portlet in a window for the Consumer. Check the remote portlet before and after the Registration cut -off time. After the lifetime expires, the remote portlet would not be rendered.


Monday May 19, 2008

What's the site running on?

To get to know the details of a site, like the operating system, hardware, server, IP addresses of the servers among others, check out Netcraft

For instance, here are the details of this site:

unknown Sun-Java-System-Web-Server/7.0 19-May-2008 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 16-Apr-2008 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 18-Feb-2008 SUN MICROSYSTEMS
unknown Sun-Java-System-Web-Server/7.0 17-Feb-2008 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 15-Feb-2008 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 16-Jan-2008 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 4-Nov-2007 SUN MICROSYSTEMS
unknown Sun-Java-System-Web-Server/7.0 25-Oct-2007 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 14-Oct-2007 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 13-Oct-2007 SUN MICROSYSTEMS

Sunday May 18, 2008

Personal Branding

 Personal Branding is a new-age market mantra, synonymous with marketing yourself in a cut-throat competitive world. Here's a very interesting article on how to create a personal brand for yourself.

Am making the highlights redundant: Steps for a successfully branded you:

  1. Know what you want: Identify what you want, and start walking toward it.
  2. Be able to articulate what you do: When someone asks what you do, answer them immediately with a clear, concise, and confident response.
  3. Elevator pitch: Be able to describe who you are and what you do in the time it takes to ride an elevator.
  4. Be positive: Be positive.
  5. Business card: A 3x5 piece of paper or mini-CD that has your personal contact information clearly printed on it.
  6. Have a blog / Website / MySpace, or other online presence: Get your brand online.
  7. Multiple e-mail addresses: Get more than one e-mail address.
  8. Phone: Get a phone.
  9. Signature: Your signature is who you are, your title, and your contact information. You should put this on everything you touch.
  10. Logo: A visual image that positively identifies your brand.
  11. Personal goals: Set goals for yourself that help you reach what you want.
  12. More than one resume: Customize your resume to the potential employer or client.
  13. Mentor: Find a guru and have them teach you.
  14. Networking outlets / contacts: Continually develop your network by attending industry meetings and conferences.
  15. Wardrobe style: When you are going to be near people who you wish to sell your brand to, dress to impress.
  16. Multiple IM accounts: Get more than one IM account.
  17. Alias: Obtain a positive nickname.
  18. Mantra: Collect sayings that enforce your brand.
  19. Speaking and PowerPoint template: Speak about what you do and have a hot-looking PowerPoint template to show.
  20. Passion: Love what you do.



Thursday May 15, 2008

Websites Offering Web Services APIs

Here is a list of web service APIs offered by popular companies that are available for integration with customized applications. Popular ones include the services offered by Yahoo, Google, Amazon, Remember The Milk, Second Life amongst others...


Tuesday May 13, 2008

JavaScript Debugging with FireBug

Firebug is the browser debugger, available as a firefox add-on. Client-side debugging, which becomes particularly important in Ajax applications with extensive JavaScript, is made much simpler with this add-on feature. Some of the features offered are 

1. Http Monitoring and Inspection - The HTTP Requests, Responses, Headers, Response times (along with their Ajax XMLHttpRequest counterparts) can be viewed and monitored.

2. Breakpoint Debugging - Breakpoints can be set and the code flow can be stepped in , stepped out or stepped over.

3. Console Logging - In firefox browsers, an implicit object called console is made available, Log statements can be inserted using console.log("Logged")

4. DOM Inspection - The HTTP DOM tree can be inspected down to the smallest elements

5. Profiling - console.profile() and console.profileEnd() methods could be used to analyse the time elapses within code blocks..

Firebug can be opened in the same browser tab as the HTML page or a different tab. Its as simple to use as it sounds too :). Open Firebug (preferably in the same browser tab), explore the tabs, go to say script tab, the entire Javascript of the HTML page is made available here. Set the breakpoints, and refresh the browser. The requests, headers can be seen and  the debugging cursor stops at the first breakpoint. Step over, step in, step out , monitor and inspect the Javascript objects and HTML objects. If you are still stuck, insert log statements and check them in the console...Go, debug the bugs..

 With Firebug, client side debugging seems to have truly evolved...

Monday May 12, 2008

Expense Reports Widget

    The expense-report widget, that is delivered as a part of the Project WebSynergy bundle, models a typical workflow scenario  where SAW (Simple API for Workflow) could be used. In an organization, employees raise expense reports and submit them to the managers to be approved or rejected. Once submitted, the report triggers a workflow process(in a workflow engine like JavaCAPS), and becomes a pending task for the associated manager. When the manager approves/rejects the report, the report goes to the next step in the workflow process.

This widget has been integrated with a simple JavaCAPS workflow process. If a workflow engine is unavailable, the SAW calls to the  Workflow engine can be disabled using the preferences. If the call to the workflow engine is enabled without configuring the engine, it results in a system error.

In addition to Workflow, this widget has the following features: 

  •  JMaki - Uses JMaki Yahoo Datatable
  •  Usage of ServeResource feature of JSR286 portlets for Ajax requests (For Displaying Report Details)
Using the widget:

An Expense Report is a report comprising details of the expenses (like Business Travel, Relocation, BroadBand Bills Claim) incurred by an employee that he could reclaim from the organisation with the manager approval. The typical claim process works like this:
Creating a New Expense Report
1. Employee (say Paul) logs in to websynergy, navigates to the sunspace tab to the expense report widget, and creates a new expense report, providing details of individual items of the report.
2. He can choose to either save the report or submit the report on creation.
Viewing Reports Summary
3. On login, Paul can view the summary of Saved(to be submitted by him) Reports and Pending(to be approved by the manager) Reports that are raised by him.
4. On clicking a particular Report ID, he can view the details of the report including the individual item details (Viewing Report details is done without a page refresh through Ajax calls).
Submitting Saved Reports
5. When he views a Saved Report Detail, he has an option to Submit it. When a report is submitted, a workflow process is triggered in JCAPS through a web service call.
Manager Login
6. When Paul's manager (Mary)logs in, she can see a list of pending reports that he has raised (in the first table) and a list of pending reports raised by her reportees (second table), waiting for his approval.
7. The list of Pending tasks is obtained from the JCAPS through SAW API
Approval and Rejection of Reports
8. On clicking on any report that is waiting for her approval, she can view the details of the report (without page refresh) and approve or reject it.

Here is a step-by-step screencast showcasing the widget.

Friday Mar 07, 2008

WSRP on Tomcat 5.5

WSRP (Web Services for Remote Portlets) is a protocol specification using which portlets are published and consumed as web services.This enables portlets that are deployed on any container to be rendered in the local container as long as the containers are configured for WSRP.  The major components that make up the WSRP architecture are:

1. Producer - For exposing the portlets as web services, managing consumer registration apart from the others

2. Consumer - For rendering the remote portlets similar to the local portlets in the container

3. Producer/Consumer Administrative Portlets - These provide the UI for managing the administration of the producer and consumer

4. WSRP Test Driver - An environment for deploying, testing remote portlets

5. WSRP Administrative Interface - These consist of Mbeans that perform administrative tasks that the admin portlets use.

For a more detailed understanding of WSRP, refer to this article.

Currently WSRP can be configured on Tomcat 5.5 and Portlet Conainer 2.0 in addition to Glassfish Application server. Here are the instructions.

 Resources for WSRP:

1. The WSRP page

2. Rajesh's blog

Sunday Mar 02, 2008

Intepreted or Compiled?

Here are some of the commonplace jargons about Java that distinguish it from the rest of the object oriented languages...It is interepreted, It is platform independent, it is dynamically linked and extensible, it can transport the state of objects across networks, it has a robust cetera...These are certainly some of the reasons that make Java what it is today(though some of these features have some performance  trade-offs too). One important feature that is associated with the Java brand is "Intepreted, Not Compiled"

There are many good articles that elucidate the difference between interpretation and compilation . This post is but a redundant synopsis of the many discrete articles...

The technical distinction between interpretation and compilation becomes clearer if the semantic(linguistic) distinction between these types of translations is understood. Lets suppose you are given a Spanish document and you intend to translate it to English. You employ two kinds of translators for this -  one an interpreter and another a compiler. The interpreter takes the first Spanish line, translates it to English, voices it aloud to you, proceeds to the next line and so on. So if there are references to a previously read paragraph or line, he does the translation again for them. A compiler on the other hand takes the entire document, translates it to English, and hands over the document to you.

Langauge compilers and interpreters are but similar. In case of Java, the java compiler compiles the java code to bytecode. The bytecode is intepreted  by the JVM and yes, it is line by line interpretation. So as it is obvious, this kind of intrepretation makes Java inherently slow. Here is an overview of the most popular interpretors/compilers for java

Enter JIT Compilers

JIT compilers operate on the Java bytecode, not the source code. So essentially, they are a part of the JVM. They are meant for translating the bytecode one method at a time to a form of native code so that the program executes faster than the usual interpretation.The translated code is stored in cache and is resused during program execution.This implies that JIT compilers do require more RAM attached to the JVM.   JIT compilation is usually done on a separate thread from the application execution thread, so that the application does not have to wait for this compilation.

Enter Adaptive Compilers

JIT compilers  were causing memory issues since they stored all natively compiled methods in cache, Adaptive Optmized compilers where introduced. These compile only those sections of the bytecode that are most frequently accessed into the native code and store them. They give better performance results compared to JIT compilers

Enter AOT compilers

AOT (Ahead of Time) compilers are meant for producing a monolithic executable for a specific platform from the bytecode and are used  predominantly in embedded systems. They use static linking as against the traditional java dynamic linking, require more ROM as against RAM as in case of JIT compilers, since they store the compiled machine code in ROM/flash memory. So AOT compilers are best sutiable for systems where dynamic extensions are not used, but have performance issues with the traditional interpretation techniques/JIT compilation.

So now, is Java compiled or interpreted? The answer is probably, it is a bit of both....

And what makes Java platform neutral? Try this analogy ; Java bytecode is the machine code if the JVM is the OS. In other words, bytecode is the machine code that the JVM expects. So as long as you have the JVM , java bytecodes (that is the java class file) can run on any OS ( Solaris or Linux or Mac or Windows or the mobile phone or a toaster). The JVM is highly platform dependent though. Another feature of the bytecode is that it follows the big-endian representation of bytes for all OS , since it is the JVM that interprets it.

Thursday Feb 28, 2008

How Mutable is an Immutable class?

The  common interview question - What is an immutable class and how would you write an immutable class in Java?

The common interview answer - An immutable class is one whose instance, once created, cannot be modified. The infamous example is the String class. To implement an immutable class, we mark the class final, lest it is extended by any other class, mark the member variables private and remove the setters.

The 'Not-So-Common' addendum to the question - Assume that the getter returns an object reference and the developer modifies the reference. Dosen't that mean that the original supposedly immutable class is modified?

 (eg)  Assume we try to implement an immutable class A as follows:

public final class A {
    private B b;
    public A(B b)
        this.b = b;
    public B getB()
        return b;

class B {
    int i;
    public B() {
    public B(int i) {
        this.i = i;
    public void set(int i) {
        this.i = i;
    public int get() {
        return i;

Class A is final and has no setter. It is supposedly immutable, However it has a reference to an object B. If someone does the following:

        B b = new B(5);
        A t = new A(b);
        B b1 = t.getB();
//prints 5
//prints 6
//prints 7

So since we have the references to the B object (i) that is passed to the constructor and (ii) that is obtained from the getter, Class A is not completely immutable. While these references are modified externally, the object that A has is modified, thus rendering A mutable.

The actual question : How can A be made completely immutable?

A possible (usually expected) answer: In the constructor of the immutable class, have make copies of the objects that are passed and store the copied objects, not the passed object reference.Similarly in the getter of the immutable class, make a copy of the to-be-returned object and return the copy, not the stored object.

So the actual immutable code would look something like:

public final class Test {
    private B b;
    public Test(B b1)
        this.b = new B();
    public B getB()
        B b1 = new B();
        return b1;

Now, on running

        B b = new B(5);
        A t = new A(b);
        B b1 = t.getB();
//prints 5
//prints 5
//prints 5

Now that class was a little less mutable :)

Tuesday Feb 26, 2008

Java Debugging with Netbeans

    Debugging can be quite a wearing experience, especially if it has to be done aidlessly. Nevertheless it is a quintessential technique for Software "bug-fixers". Netbeans offers some good  features which could help in debugging server, applet or command-line processes. Breakpoints, watches, call stack navigation and such additional features help in seeing the code under the hood. This post is a primer on Debugging with Netbeans

     The basic idea of debugging is that there are two processes - one a Serversocket that listens on a specific port and another that attaches itself to that port during the debugging process.Netbeans offers both kinds of sockets  - (i) A "SocketAttach" that attaches to the port  at which  the java process/server process listens to and a (ii) "SocketListen" that listens at the specific port to which another process (say an applet) would attach to.

Steps for Server Process Debugging

This is probably the most widely used form of debugging.

1. Start the server in the debugging mode. (For Glassfish, this is done by setting the debug-enabled flag to true in <DOMAIN-DIR>/config/domains.xml and restarting the server. Note the port no at which the server is listening)

2. In the Netbeans IDE, open the code base which is in sync with the deployed server code.

3. Goto Run-> Attach Debugger -> Choose ServerAttach mode. The NB IDE attaches to the socket opened by the server in this case.

4. Provide details of the server host and port

5. Set breakpoints in the code and launch the application. The thread stops at the breakpoints, and the code could be stepped over or stepped into to debug further.

Steps for Java Command Line Debugging

1. To debug a java command line process, run the command in the debug mode:

java -Xdebug -Xrunjdwp:transport=dt_socket,address=<portNo>,server=y,suspend=y ABCProg

2. Open the code base in Netbeans and Attach the debugger in the SocketAttach mode, provide the host and port information

Steps for Applet Debugging

1. For Applet debugging, go to the Java ControlPanel (In Unix, it is <JAVA_HOME/bin/ControlPanel, in Windows, ControlPanel -> Java). Navigate to the Java tab - View Settings - Edit the Java Runtime settings. Furnish this information:


This makes the browser JRE open a socket connection while launching the applet.

2. Open the NB code base and attach the debugger in the SocketListen mode by furnishing the host and port information.


Happy Debugging!!!

Monday Dec 24, 2007

An Ajax Based Yahoo Suggest and Search Portlet

Recently I got to try the Yahoo Search API . Yahoo offer many REST based service APIs which could be consumed for web-applications. Tried to develop a JSR 286 portlet (Portlet spec v2.0) that uses Ajax and serveResource feature of JSR286 specification to make aysnchronous API calls to the portlet which in turn makes calls the Yahoo REST services through Apache HttpClient. Since the result of the REST calls are JSON based, it is not difficult to extrace the suggest or search results.

From the Portlet Perspective, the XMLHttpRequest from the VIEW Jsp sends a resourceURL with the search keywords as the input parameters to the portlet.The portlet implements the ResourceServingPortlet interface, and thus implements the abstract method serveResource, in which calls to the REST services are made. The response type is set as 'application/json' and the resultant JSON object is embedded in the resourceResponse. The onReadyStateChange action handler of the JSP processes this JSON response and displays the search results.

To the end user, the portlet offers a search box, which offers suggestions as the user keys down letters, (with each keypress, aysnchronous REST calls are made to the yahoo related search API  and the resultant suggestions are displayed as a dropdown and when the Search button is pressed with a specific user-entered or user-selected keyword, aynschronous calls are made to retrieve the search results similar to the previous case. 

Though this portlet was initially a product of academic interest, it could be further developed to adapt to Google and other custom search engines, which Im currently trying to enhance.  The pre-requisites are a Portlet V 2.0 portlet container (Sun's OSPC 2.0 could be used) and Apache HttpClient.

 This portlet is available for download and use here






« April 2014