Tuesday, June 22, 2010

Create Custom JNDI URL Resource Provider for Glassfish

Again very simple requirement, again Glassfish and again it cannot be satisfied by default. May be my requirement is not a part of reference implementation :))

Anyway, one of my collegue requested that "put the application properties file outside of the application and look up the property file from JNDI". First I thought that it should be very easy since we define JDBC Datasource zillion times and how can it be different?
Answer is; it is totally different in Glassfish!

Bad New: You need to develop your own ObjectFactory implemantation for URL resources.
Good New: It is so simple to do.

Let me summarize how you can do that:

  1. Create a java project in your favorite IDE. Name can be GlassfishUrlFactory
  2. Create the package that you will put the "javax.naming.spi.ObjectFactory" implementation. Suggestion com.xxx.glassfish.jndi.resource 
  3. Create the ObjectFactory implementation class. Source code looks like:
package com.xxx.glassfish.urlfactory;
import java.net.URL;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class GlassfishUrlFactory implements ObjectFactory {

    
    
    public Object getObjectInstance(Object obj, Name name, Context nameCtx,
            Hashtable environment) throws Exception {

        Reference ref = (Reference) obj;
        String propertyFileUrl=null;
       
        if(ref!=null){
            propertyFileUrl=ref.get("fileUrl").getContent().toString();
        }else{
            throw new Exception("Please Add 'fileUrl' property to JNDI Resource Definition!!");
        }
       
        URL url = new URL(propertyFileUrl);
        return url;
    }
    
    
}

    
Reference is something similar to java.util.Map. It is used to get the parameters that you pass when you define JNDI Resource in your application server. For example imagine that you defined a JDBC datasource and set the username property from the admin console. JDBC Factory class will get it like 

username=ref.get("username").getContent().toString();



       4. Export the project as JAR file. 

       5. Put the JAR file under Glassfish lib folder.
      6. Define a Custom JNDI Resource in Glassfish

       7. Restart the Application Server.

     Here is a sample code how can you look up properties file from Spring:


No comments:

Post a Comment