com.alogic.naming.Naming Maven / Gradle / Ivy
package com.alogic.naming;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.anysoft.util.IOTools;
import com.anysoft.util.Expired;
import com.anysoft.util.Properties;
import com.anysoft.util.Reportable;
import com.anysoft.util.Settings;
import com.anysoft.util.Watcher;
import com.anysoft.util.WatcherHub;
import com.anysoft.util.XmlElementProperties;
import com.anysoft.util.XmlTools;
import com.anysoft.util.resource.ResourceFactory;
/**
* 命名服务入口
*
* @author duanyy
* @since 1.6.6.8
*
* @version 1.6.6.10 [duanyy 20161226]
* - 允许缓存对象过期
*
* @version 1.6.7.9 [20170201 duanyy]
* - 采用SLF4j日志框架输出日志
*/
public abstract class Naming implements Context,Watcher {
/**
* a logger of log4j
*/
protected static final Logger LOG = LoggerFactory.getLogger(Naming.class);
/**
* Watcher Hub
*/
protected WatcherHub watcherHub = new WatcherHub(); // NOSONAR
/**
* 缓存的对象
*/
protected Hashtable caches = new Hashtable(); // NOSONAR
/**
* 子配置环境列表
*/
protected List> subContexts = new ArrayList>(); // NOSONAR
/**
* 获取配置文件中代表context的tag名
* @return tag名
*/
protected String getContextName(){
return "context";
}
/**
* 创建Context对象实例
* @param e xml配置节点
* @param p 环境变量
* @param attrName 类名所对应的属性名称
* @return 对象实例
*/
protected abstract Context newInstance(Element e, Properties p, String attrName);
@Override
public void configure(Element root, Properties props) {
Properties p = new XmlElementProperties(root,props);
NodeList children = XmlTools.getNodeListByPath(root, getContextName());
for (int i = 0 ; i < children.getLength() ; i ++){
Node n = children.item(i);
if (n.getNodeType() != Node.ELEMENT_NODE){
continue;
}
Element e = (Element)n;
try {
Context ctx = newInstance(e, p,"module"); // NOSONAR
if (ctx != null){
ctx.addWatcher(this);
subContexts.add(ctx);
}
}catch (Exception ex){
LOG.error("Can not create context instance,check your configuration.",ex);
}
}
configure(p);
}
@Override
public void configure(Properties p) {
// nothing to do
}
@Override
public void close() throws Exception {
caches.clear();
for (Context s:subContexts){
s.removeWatcher(this);
IOTools.close(s);
}
subContexts.clear();
}
@Override
public void report(Element xml) {
if (xml != null) {
xml.setAttribute("module", getClass().getName());
xml.setAttribute("ctxName", getContextName());
Document doc = xml.getOwnerDocument();
for (Context c : subContexts) {
Element context = doc.createElement(getContextName());
c.report(context);
xml.appendChild(context);
}
}
}
@Override
public void report(Map json) {
if (json != null){
json.put("module", getClass().getName());
json.put("ctxName", getContextName());
List