Please see the code below:
try {
//InitialContext ic = new InitialContext();
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.enterprise.naming.SerialInitContextFactory");
Context ctx = new InitialContext(env);
MySessionRemote hb = (MySessionRemote) ctx.lookup("MySessionRemote");
System.out.println(hb.getResult());
} catch (NamingException ex) {
ex.printStackTrace();
}
The error I get from a Swing app is:(javax.naming.NoInitialContextException) javax.naming.NoInitialContextException: Cannot instantiate class: com.sun.enterprise.naming.SerialInitContextFactory [Root exception is java.lang.ClassNotFoundException: com.sun.enterprise.naming.SerialInitContextFactory]
I have not worked with Java for a while so this could be quite straightforward.
Update
I am using version 4.1 of Glassfish. I have added references to the following jars inside the NetBeans project:
appserv-rt.jar
gf-client.jar
javaee.jar
I can now get an InitialContext. However, I cannot lookup the bean i.e. this line fails:
MySessionRemote hb = (MySessionRemote) ctx.lookup("ejb.MySessionRemote");
The exception is a NamingException
i.e. Lookup Failed
. I believe the name of the bean may be wrong. Here is the bean:
package ejb;
import javax.annotation.Resource;
import javax.ejb.Remote;
@Resource(name = "MySessionRemote")
@Remote
public interface MySessionRemote {
public String getResult();
}
What should the name of the bean be?
Which application server are you using? E.g. when using Glassfish that class can be found in the glassfish-naming.jar
file. That JAR needs to be on your classpath. I assume other application servers have a similar JAR file.
In fact, when you have that JAR on your classpath you could simply use the no-args constructor of InitialContext
since the JAR already contains a jndi.properties
file with the following content:
java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory
java.naming.factory.url.pkgs=com.sun.enterprise.naming
# Required to add a javax.naming.spi.StateFactory for CosNaming that
# supports dynamic RMI-IIOP.
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl