java服务定位器(1)

private static ServiceLocator handler;

private Map handlers = null;

private Context context = null;

public void clearCache() {
handlers = Collections.synchronizedMap(new HashMap());
}

private ServiceLocator() throws ServiceLocatorException {
try {
context = new InitialContext();
handlers = Collections.synchronizedMap(new HashMap());
} catch (NamingException e) {
e.printStackTrace();
throw new ServiceLocatorException(
"Initial context failed in career service handler");
}
}

static {
try {
handler = new ServiceLocator();
} catch (ServiceLocatorException e) {
System.err.println("initiate service handler failed.");
e.printStackTrace();
}
}

/**
* 得到服务定位器的实例
*/
public static ServiceLocator getInstance() {
return handler;
}

/**
* 通过J2EE标准方式得到EJB的本地home接口
*
* @param jndiHomeName
* @throws ServiceLocatorException
*/
public EJBLocalHome getLocalHome(String jndiHomeName)
throws ServiceLocatorException {
EJBLocalHome home = null;

try {
if (handlers.containsKey(jndiHomeName)) {
home = (EJBLocalHome) handlers.get(jndiHomeName);
} else {
home = (EJBLocalHome) context.lookup("java:comp/env/"
+ jndiHomeName);
handlers.put(jndiHomeName, home);
}
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return home;
}
/**
* 得到环境变量的名称
*
* @param envName
* @throws ServiceLocatorException
*/
public String getString(String envName) throws ServiceLocatorException {
String envEntry = null;
try {
envEntry = (String) context.lookup(envName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return envEntry;
}

/**
* 得到邮件的会话
*
* @param envName
* @throws ServiceLocatorException
*/
public Session getMailSession(String envName)
throws ServiceLocatorException {
Session session = null;
try {
boolean refresh = false;
if (handlers.containsKey(envName)) {
session = (Session) handlers.get(envName);
Transport transport = null;
try {
transport = session.getTransport();
transport.connect();
} catch (Exception e) {
refresh = true;
session = null;
} finally {
if (null != transport) {
try {
transport.close();
} catch (MessagingException e1) {
}
transport = null;
}
}
}
if ((!handlers.containsKey(envName)) || refresh) {
session = (Session) context.lookup("java:comp/env/" + envName);
handlers.put(envName, session);
}
} catch (NamingException e) {
//
throw new ServiceLocatorException(e);
}
return session;
}

你可能感兴趣的:(java,ejb)