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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值