My EJBHomeFactory.java
package com.sanjiv.ejb.prototype.factories;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
/**
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company:
* @author Sanjiv Pansari
* @version 1.0
*/
public class EJBHomeFactory {
private Map ejbHomes;
private static EJBHomeFactory aFactorySingleton;
Context ctx;
private EJBHomeFactory() throws NamingException {
try {
ctx = getInitialContext();
} catch (Exception e) {
System.out.println("Failed initializing bean access.");
e.printStackTrace();
}
this.ejbHomes = Collections.synchronizedMap(new HashMap());
}
/*
* Returns the singleton instance of the EJBHomeFactory
**/
public static EJBHomeFactory getFactory() throws NamingException {
if (EJBHomeFactory.aFactorySingleton == null ) {
EJBHomeFactory.aFactorySingleton = new EJBHomeFactory();
}
return EJBHomeFactory.aFactorySingleton;
}
/**
* Lookup and cache an EJBHome object
**/
public EJBHome lookUpHome(
String jndiName, Class homeClass) throws NamingException {
EJBHome anEJBHome = (EJBHome)this.ejbHomes.get(homeClass);
if (anEJBHome == null) {
//look up jndi name
Object ref = ctx.lookup(jndiName);
anEJBHome = (EJBHome) PortableRemoteObject.narrow(ref, homeClass);
this.ejbHomes.put(homeClass, anEJBHome);
}
return anEJBHome;
}
private Context getInitialContext() throws Exception {
String url = "t3://localhost:7001";
String user = null;
String password = null;
Properties properties = null;
try {
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
properties.put(Context.PROVIDER_URL, url);
if (user != null) {
properties.put(Context.SECURITY_PRINCIPAL, user);
properties.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password);
}
}
catch(Exception e) {
System.out.println("Unable to connect to WebLogic server at " + url);
System.out.println("Please make sure that the server is running.");
throw e;
}
return new InitialContext(properties);
}
}
/*****/
And this is how I do lookup for an EJB
sessionEJBTestHome = (SessionEJBTestHome) EJBHomeFactory.getFactory().lookUpHome("SessionEJBTest",SessionEJBTestHome.class);
I have defined lookUpHome() method to take 2 parameter
1) Jndi name of the bean
2) HomeInterfaceClass
I hope it helps.
This factory class will work lokup only in the WebLogic Application as you can see the getInitialContext() method is specific to weblogic. Do you know how to optimize it so that the properties can be read from a property file?
rgds
Sanjiv