JAVA项目使用jdom初始化xml配置文件类

 单例模式加载配置文件类

 

使用架包:jdom-2.0.5.jar、log4j-1.2.17.jar

代码:

package com.wjq.project.loadFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;


/**
 * @Title:JAVA项目初始化xml配置文件类
 * @Description: 使用jdom解析xml配置文件; 使用单例模式初始化类; 定时重新加载配置文件,时间可配
 * @author wjq
 * @date 2013-07-19
 */
public class LoadXmlFile_jdom {
	//日志
	private static Logger log = Logger.getLogger(LoadXmlFile_jdom.class);
	//配置文件
	private static final String CONFIG_FILE = "loadFile_loadXmlFile.xml";
	
	//dom4j 对象
	private Document document=null;
	
	//IP地址
	private String ip = null;
	//端口号
	private String port = null;
	//重启加载配置文件周期,默认值:12,单位:小时
	private int reloadTime=12;
	//告警级别转换
	private Map<String, String> alarmLevelsMap=new HashMap<String, String>();
	//工单状态数据转换
	private Map<String, String> sheetStatusTransMap=new HashMap<String, String>();
	
	
	/////////////////////////////////////////////	单例模式 start	/////////////////////////////////////////////
	/**
	 * 私有化构造方法
	 */
	private LoadXmlFile_jdom(){
		log.info("加载配置文件: "+CONFIG_FILE);
		loadConfig();
		
		//开启定时加载配置文件的线程
		Thread reloadConfFile = new Thread(new ReloadConfFile());
		reloadConfFile.start();
	}

	/**
	 * 内部静态类,实例化本类对象
	 * @author wjq
	 *
	 */
	public static class ClassInstance{
		//在内部静态类中实例化LoadXmlFile对象
		private static final LoadXmlFile_jdom instance=new LoadXmlFile_jdom();
	}
	
	/**
	 * 对外提供本类实例化对象
	 * @return
	 */
	public static LoadXmlFile_jdom getInstance(){
		return ClassInstance.instance;
	}
	/////////////////////////////////////////////	单例模式 end	/////////////////////////////////////////////
	
	

	/**
     * 加载配置文件信息
     */
    private void loadConfig() {
    	try {
    		InputStream inputStream = LoadXmlFile_jdom.class.getResourceAsStream("/project/"+CONFIG_FILE);
        	if(inputStream!=null){
        		SAXBuilder builder = new SAXBuilder();
        		this.document = builder.build(inputStream);
    			if(document==null){
    				return;
    			}
    			
    			this.ip=loadSingleNode("myProject/ip");
    			this.port=loadSingleNode("myProject/port");
    			this.reloadTime=Integer.valueOf(loadSingleNode("myProject/reloadTime"));
    			this.alarmLevelsMap=loadAttributeMap("myProject/alarmLevels");
    			this.sheetStatusTransMap=loadTextMap("myProject/sheetStatusTrans");
        	}else{
        		log.error("配置文件不存在,请确认已经将配置文件["+CONFIG_FILE+"]已经放在[project]目录下");
        	}
		} catch (Exception e) {
			log.error("解析配置文件["+CONFIG_FILE+"]异常",e);
		}
    }
    
    /**
	 * ReloadConfFile thread
	 * 定时重新加载xml配置文件 线程
	 * 默认每隔12小时加载一次xml配置文件,
	 * @author wjq
	 */
	private class ReloadConfFile implements Runnable {
		public void run() {
			// TODO Auto-generated method stub
			while(true) {
				try {
					Thread.sleep(reloadTime*60*60*1000);
				} catch (InterruptedException e) {
				}
				log.info("重新加载配置文件:"+CONFIG_FILE);
				loadConfig();
			}
		}
	}
	
    
    /**
     * 获取单个节点的文本值
     * @param nodePath
     * @return
     */
    private String loadSingleNode(String nodePath){
    	Element root = document.getRootElement();
		String[] elementsName = nodePath.split("\\/");
		for (int i = 0; i < elementsName.length; i++) {
			root = root.getChild(elementsName[i]);
		}
	
		String nodeText =root.getTextTrim();
		log.info(root.getName()+"="+nodeText);
		return nodeText;
    }
    
    
    
    /**
     * 加载from、to在元素属性节点上的转换关系
     * from为key、to为value
     * @param nodePath 节点路径
     * @return
     */
	private Map<String, String> loadAttributeMap(String nodePath){
		Map<String, String> fromToMap=new HashMap<String, String>();
		//日志信息
		String logMessage="";
		
		//先清空Map内容
		fromToMap.clear();
		Element root = document.getRootElement();
		String[] elementsName = nodePath.split("\\/");
		for (int i = 0; i < elementsName.length; i++) {
			root = root.getChild(elementsName[i]);
		}
		logMessage=root.getName()+":[";
		
		List childrenList = root.getChildren();
		Iterator iter=childrenList.iterator();
		while(iter.hasNext()) {
			Element el=(Element)iter.next();
			String key= el.getAttributeValue("from").trim();
			String value= el.getAttributeValue("to").trim();
			fromToMap.put(key, value);
			logMessage=logMessage+";from="+key+",to="+value;
		}
		
		logMessage=logMessage.replaceFirst(";", "")+"]";
		log.info(logMessage);
		
		return fromToMap;
	}
	
	/**
	 * 加载from、to为单独元素的转换关系
	 * from为key、to为value
	 * @param nodePath 节点路径
	 * @return
	 */
	private Map<String, String> loadTextMap(String nodePath){
		Map<String, String> fromToMap=new HashMap<String, String>();
		//日志信息
		String logMessage="";
		
		//先清空Map内容
		fromToMap.clear();
		Element root = document.getRootElement();
		String[] elementsName = nodePath.split("\\/");
		for (int i = 0; i < elementsName.length; i++) {
			root = root.getChild(elementsName[i]);
		}
		logMessage=root.getName()+":[";
		
		List childrenList = root.getChildren();
		Iterator iter=childrenList.iterator();
		while(iter.hasNext()) {
			Element el=(Element)iter.next();
			String key= el.getChild("from").getTextTrim();
			String value= el.getChild("to").getTextTrim();
			fromToMap.put(key, value);
			logMessage=logMessage+";from="+key+",to="+value;
		}
		
		logMessage=logMessage.replaceFirst(";", "")+"]";
		log.info(logMessage);
		
		return fromToMap;
	}
    

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getPort() {
		return port;
	}
	public void setPort(String port) {
		this.port = port;
	}

	public Map<String, String> getAlarmLevelsMap() {
		return alarmLevelsMap;
	}

	public void setAlarmLevelsMap(Map<String, String> alarmLevelsMap) {
		this.alarmLevelsMap = alarmLevelsMap;
	}

	public Map<String, String> getSheetStatusTransMap() {
		return sheetStatusTransMap;
	}

	public void setSheetStatusTransMap(Map<String, String> sheetStatusTransMap) {
		this.sheetStatusTransMap = sheetStatusTransMap;
	}


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("使用jdom加载xml配置文件");
		LoadXmlFile_jdom loadXmlFile=LoadXmlFile_jdom.getInstance();
	}
}

 

 

配置文件:
<?xml version="1.0" encoding="Gb2312"?>
<config>
	<myProject>
		<!-- IP地址 -->
		<ip>127.0.0.1</ip>
		<!-- 端口号 -->
		<port>51088</port>

		<!-- 第一种数据转换方法  from为key、to为value-->
		<alarmLevels>
			<level from="紧急告警" to="1" />
			<level from="重要告警" to="2" />
			<level from="次要告警" to="3" />
			<level from="警告告警" to="4" />
		</alarmLevels>

		<!-- 第二种数据转换方法  from为key、to为value-->
		<sheetStatusTrans>
			<sheetStatusRecord>
				<from>草稿</from><to>1</to>
			</sheetStatusRecord>
			<sheetStatusRecord>
				<from>一级处理中</from><to>2</to>
			</sheetStatusRecord>
			<sheetStatusRecord>
				<from>二级处理中</from><to>3</to>
			</sheetStatusRecord>
			<sheetStatusRecord>
				<from>三级处理中</from><to>4</to>
			</sheetStatusRecord>
		</sheetStatusTrans>
		
		<!-- 重新读取配置文件周期,默认值:12,单位:小时 -->
		<reloadTime>12</reloadTime>
	</myProject>
</config>
 

你可能感兴趣的:(单例,多线程,xml,log4j,jdom)