⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 config.java

📁 中国移动定位引擎的客户端
💻 JAVA
字号:
package ffcs.config;

import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

import ffcs.util.Resources;
import ffcs.util.XmlTransformUtil;

/**
 * <p>Title: </p>
 * <p>Description:采用单例模式,读取配置文件,并初始化配置文件的信息到相应的配置类中 </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: 福建福富软件技术股份有限公司</p>
 * @author Huangcm
 */
/**
 * example:
 * <code>
 * <pre>
 		Config config = Config.getInstance();
		Module module =config.getModeule("smsc");
		System.out.println(module.getPort());
		System.out.println(module.getProperties("LoginMode"));
		String globalProp = config.getGlobalProp("alertPort");
		System.out.println(globalProp);
 * </pre>
 * </code>
 */

public class Config {
	private final static String DEFAULT_CONFIG_NAME = "config.xml";

	private static final String MODULE_CONFIG_ELEMENT = "module-config";

	private static final String GLOBAL_PROPERTYS_ELEMENT = "global-propertys";

	private static final String PROPERTY_ELEMENT = "property";

	private static final String MODULES_ELEMENT = "modules";

	private static final String MODULE_ELEMENT = "module";
	
	private static Map instances = new HashMap(5);

	private Properties globalProp = null; //保存全局配置变量

	private Map modulesMap = null; //保存模块的配置信息
	
	private String cfgFileName=null;//配置文件名称
	
	private long cfgLastModified=System.currentTimeMillis();
	
	private File pFile = null;
	
	/**
	 * 私有的构造函数,保证外部无法初始化
	 * @throws ConfigException
	 */
	private Config(String fileName) {
		this.cfgFileName = fileName;
		try{
			pFile = Resources.getResourceAsFile(cfgFileName);
		}catch(IOException ioe){
			throw new RuntimeException("初始化配置文件出错:" + ioe.getMessage()); 
		}
	
		readConfig();
	}
	
	
	public static synchronized Config getInstance() {
		return getInstance(DEFAULT_CONFIG_NAME);
	}
	/**
	 * 得到配置类的唯一实例
	 * @throws ConfigException
	 * @return Config
	 */
	public static synchronized Config getInstance(String name) {
		if (instances.get(name) == null) {
			Config config = new Config(DEFAULT_CONFIG_NAME);
			instances.put(name,config);
			return config;
		}
		return ((Config)instances.get(name));
	}
	/**
	 * 读取配置文件
	 */
	private void readConfig(){
		InputStream is = null;
		Document doc = null;
		try {
			is = Resources.getResourceAsStream(cfgFileName);
			doc = XmlTransformUtil.builerDocument(is);
		} catch (Exception e) {
			throw new RuntimeException("初始化配置文件出错:" + e.getMessage()); //("初始化配置文件出错:" + e.getMessage());
		}

		Element root = doc.getDocumentElement();
		String rootname = root.getNodeName();
		if (!MODULE_CONFIG_ELEMENT.equals(rootname)) {
			throw new IllegalArgumentException(
					"Error while configuring Module.  The root tag of the MODULE configuration XML "
							+ "document must be '"
							+ MODULE_CONFIG_ELEMENT
							+ "'.");
		}

		NodeList children = root.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			Node child = children.item(i);
			if (child.getNodeType() == Node.ELEMENT_NODE) {
				if (GLOBAL_PROPERTYS_ELEMENT.equals(child.getNodeName())) {
					globalProp = parseGlobal((Element) child);
				} else if (MODULES_ELEMENT.equals(child.getNodeName())) {
					modulesMap = parseModules((Element) child);
				}
			}
		}
	}
	/**
	 * 重新读取配置信息
	 */
	public void resetConfig(){
		if( globalProp != null){
			globalProp.clear();
		}
		if( modulesMap != null){
			modulesMap.clear();
		}
		readConfig();
	}
	/**
	 * 解析
	 * <global-propertys>
	 <property name="变量1" value="值1"></property>
	 </global-propertys>
	 * 标签的值
	 * @param doc Document
	 * @return Properties
	 */
	protected static Properties parseGlobal(Element globalEle) {
		NodeList children = globalEle.getChildNodes();

		Properties globalProp = new Properties();
		for (int i = 0; i < children.getLength(); i++) {
			Node node = children.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				if (PROPERTY_ELEMENT.equals(node.getNodeName())) {
					String propKey = ((Element) node).getAttribute("name");
					String propValue = ((Element) node).getAttribute("value");
					if (propKey == null || propKey.equals("")) {
						System.err
								.println("WARN: Config.parseGlobal Cause: name attribute must be not null "
										+ ((Element) node).toString());
					}

					if (globalProp.getProperty(propKey) != null) {
						System.err
								.println("WARN: Config.parseGlobal Cause: name attribute already define "
										+ ((Element) node).toString());
					} else {
						globalProp.put(propKey, propValue);
					}
				}
			}
		}
		return globalProp;
	}

	/**
	 *  解析modules标签
	 *      <modules>
	 <module id="10001" ip="192.168.21.3" port="9999" name="业务处理机网管接口模块1">
	 <parameter>
	 <name>maxActive</name>
	 <value>10</value>
	 </parameter>
	 <!-- 可以多个parameter子标签-- >
	 </module>
	 </modules>
	 * @param modulesEle Element
	 * @return Map
	 */
	protected static Map parseModules(Element modulesEle) {
		NodeList children = modulesEle.getChildNodes();
		Map tempMap = new HashMap();
		for (int i = 0; i < children.getLength(); i++) {
			Node node = children.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				if (MODULE_ELEMENT.equals(node.getNodeName())) {
					Element tempEle = (Element) node;
					Module module = new Module();
					module.setID(tempEle.getAttribute("id"));
					module.setIP(tempEle.getAttribute("ip"));
					module.setPort(Integer.parseInt(tempEle.getAttribute("port")));
					module.setName(tempEle.getAttribute("name"));

					NodeList paraChilden = tempEle.getChildNodes();
					Properties prop = new Properties();
					/*解析子标签<parameter>
					 <name>maxActive</name>
					 <value>10</value>
					 </parameter>
					 的值,保存到prop中
					 */

					for (int j = 0; j < paraChilden.getLength(); j++) {
						Node paraNode = paraChilden.item(j);
						if (paraNode.getNodeType() == Node.ELEMENT_NODE) {
							String key = ((Element) paraNode)
									.getElementsByTagName("name").item(0)
									.getFirstChild().getNodeValue();
							String value = ((Element) paraNode)
									.getElementsByTagName("value").item(0)
									.getFirstChild().getNodeValue();
							prop.put(key, value);
						}
					}
					module.setProperties(prop);
					tempMap.put(module.getID(), module);
				}
			}
		}
		return tempMap;
	}

	public Properties getGlobalProp() {
		synchFileUpdate();
		return globalProp;
	}

	public String getGlobalProp(String key) {
		if(globalProp==null){
			return null;
		}
		synchFileUpdate();
		return globalProp.getProperty(key);
	}

	public void setGlobalProp(Properties globalProp) {
		this.globalProp = globalProp;
	}

	public void setModulesMap(Map modulesMap) {
		this.modulesMap = modulesMap;
	}

	public Map getModulesMap() {
		synchFileUpdate();
		return modulesMap;
	}

	public Module getModule(String key){
		synchFileUpdate();
		return (Module)modulesMap.get(key);
	}
	/**
	 *同步配置文件
	 *如果配置文件更改了,从新读取配置文件
	 */
	private void synchFileUpdate(){
		long newTime = pFile.lastModified();
	    if(newTime==0 || cfgLastModified == 0){
	    	System.err.println(pFile + " file does not exist!");
	    }else if(newTime>this.cfgLastModified){
			resetConfig();
		}
	    this.cfgLastModified = newTime;
	}
	
	/**
	 * 测试程序
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		for(int i=0;i<100;i++){
			Config config = Config.getInstance();
			String var = config.getGlobalProp("alertPort");
			/*Module module =config.getModule("smsc");
			System.out.println(module.getPort());
			System.out.println(module.getProperties("LoginMode"));*/
			System.out.println(var);
			Thread.sleep(5000);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -