0

I am building a Web Application for class (yes this is a homework assignment). I am using Eclipse and Tomcat 8. I have the following code for a Service Factory:

package com.OrderOnline.model.service.factory;


import javax.naming.Context;
import javax.naming.InitialContext;

import com.OrderOnline.model.service.interfaces.IService;

public class ServiceFactory
{
    public IService getService(String name) throws Exception
    {
        try
        {
            Class<?> newClass = Class.forName(getImplName(name));
            return (IService)newClass.newInstance();
        }
        catch(Exception e)
        {
            throw new Exception(name);
        }
    }

    private String getImplName(String name) throws Exception
    {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");

        String lookupClass = (String) envCtx.lookup(name);
        return lookupClass;
    }
}

I expected this to look in my web.xml file located at OrderOnline/WebContent/WEB-INF/web.xml for the following:

  <env-entry>
    <env-entry-name>IUserSvc</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>com.OrderOnline.model.service.interfaces.IUserSvc</env-entry-value>
  </env-entry>

Instead I am getting an exception thrown when this line is run:

Context envCtx = (Context) initCtx.lookup("java:comp/env");

The Exception is:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

I am very new at this, so I could be missing some important peice of information for you to help me, and I will be more than happy to provide any more information that is needed. I appreciate any assistance that can be provided to help me read the env-entry-value from the web.xml file.

BigDevJames
  • 2,650
  • 5
  • 21
  • 36

1 Answers1

0

You need an initial context factory as stated in this answer on SO.

    System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
              "org.apache.naming.java.javaURLContextFactory");
Community
  • 1
  • 1
Frank
  • 2,036
  • 1
  • 20
  • 32
  • According to the Tomcat documentation, an initial context is automatically provided. My initial context code looks almost identical to what they provide here: https://tomcat.apache.org/tomcat-8.0-doc/jndi-resources-howto.html . That being said, I attempted what you indicated and that is also not working. This one is strange, because I can't seem to catch the exception. I put the contents of the getImplName() inside a try/catch, and when it hits the Context envCtx code it acts like it hits a return statement. No Exception is thrown, it just quits the class. I'll have to look more in the AM – BigDevJames Feb 08 '16 at 07:57