4 Replies Latest reply on May 18, 2012 11:32 AM by Ben Cantrick

    Making JNDI lookups portable from as 5 to 7.

    Ben Cantrick Newbie

      Hello everyone! I want to start by disclaiming that I'm super new to JBoss. In fact I've been using it for all of a week. So if this is a stupid question, I apologize in advance.


      My situation is that I've been assigned to port several applications originally written for JBoss 5, to JBoss 7. My major sticking point at the moment is the change in JNDI names. In particular, several of the apps have hard-coded the value corresponding to Context.INITIAL_CONTEXT_FACTORY ("java.naming.factory.initial") to be "org.jboss.naming.NamingContextFactory". This is correct for Jboss5, but wrong for JBoss7. In JB7 it's "org.jboss.as.naming.InitialContextFactory".


      Here's the code in question:


      private final static String JNDI_FACTORY    = "org.jboss.naming.NamingContextFactory";


              Properties env = new Properties();
              env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
              env.put(Context.URL_PKG_PREFIXES, FACTORY_PREFIXES);
              String hostname = Config.getDefault().get(Config.MAIN_JNDI_SERVER_NAME);
              String url = protocol(hostname) + hostname + ":" + Config.getDefault().get(Config.MAIN_JNDI_SERVER_PORT);
              //Logger.debug(Logger.SERVLET, "Attempting to initialize JNDI context with url: " + url);
              env.put(Context.PROVIDER_URL, url);
              m_context = new InitialContext(env);


      As you can see, the value of JNDI_FACTORY is correct for JBoss 5 but wrong for JBoss 7.


      At the moment, I'm just going in and changing the hard-coded value for this string. However, that's not a good long-term solution. It means that the code will only run correctly on JBoss7, and not on JBoss5. What I would like is to have the same code run on both with no modifications necessary.


      I've considered and rejected a couple of options already. One is to just hardcode it, as above. I feel like that's a bad way to do things. Another option is to stuff the correct value in a config file and read it out at startup time. This depends on the user knowing which version of JBoss they're running the code under and putting the right thing in the config file. Another option is to have some kind of logic to detect the version of JBoss at runtime, and then pick which JNDI_SERVER_NAME to use. This sounds like it could be a lot of hassle.


      So, my question is: Is there an EASY way to obtain the correct value for my JNDI_FACTORY string above, that is also portable between JBoss5 and JBoss7? As I said, I'm pretty new at this, but it feels to me like this is exactly the kind of problem that dependency injection was created for. I believe there must be a better way to do this than the way the code is doing it now. Any clues for me?