lundi 3 mai 2010

J2EE : ejb serviceLocator

Voici, le code classique d'un serviceLocator. Ce service utilise des caches, des ressources récupérés par JNDI, et les mets en cache.

A noter : que l'on utilise le code ejbHome.getHomeHandle() pour garder une reference sur les EJB distants ...


/**
* Donne l'instance de l'EJBHome. Celui-ci est placé dans un cache, d'où il sera extrait au prochain appel.
* @param jndiAdress String
* @param jndiHomeName String
* @param homeClass Class
* @throws ServiceLocatorException
* @return EJBHome ou EJBLocalHome
*/
private Object getHome(String jndiAdress, String jndiHomeName, Class homeClass, boolean homeDistante)
throws ServiceLocatorException {
Object home = null;
InitialContext context = null;
String cacheKey = jndiAdress + jndiHomeName;

try {
//On prend la home dans le cache si elle y est.
if (cacheEnabled && cache.get(cacheKey) != null) {
if (homeDistante) {
HomeHandle homeHandle = (HomeHandle) cache.get(cacheKey);
home = (EJBHome) homeHandle.getEJBHome();
}
}
if (cacheEnabled && cacheLocal.get(cacheKey) != null) {
if (!homeDistante) {
home = (EJBLocalHome) cacheLocal.get(cacheKey);
}
}
//Sinon on la cherche dans l'annuaire JNDI
else {
context = InitialContextManager.getInitialContext(jndiAdress);
Object objReference = context.lookup(jndiHomeName);

//Si la home est distante il faut faire un narrow
if (homeDistante) {
home = (EJBHome) PortableRemoteObject.narrow(objReference, homeClass);
EJBHome ejbHome = (EJBHome) home;
if (cacheEnabled) {
cache.put(cacheKey, ejbHome.getHomeHandle());
}
}
//Pas besoin de narrow si elle est locale
else {
home = (EJBLocalHome) objReference;
EJBLocalHome ejbLocalHome = (EJBLocalHome) home;
if (cacheEnabled) {
cacheLocal.put(cacheKey, ejbLocalHome);
}
}
}

}
catch (RemoteException rex) {
throw new ServiceLocatorException(rex);
}
catch (NamingException ex) {
throw new ServiceLocatorException(ex);
}
finally {
if (context != null) {
try {
context.close();
}
catch (NamingException ex1) { //rien
}
}
}

return home;
}

Aucun commentaire:

Enregistrer un commentaire