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 alarmLevelsMap=new HashMap();
	//工单状态数据转换
	private Map sheetStatusTransMap=new HashMap();
	
	
	/////////////////////////////////////////////	单例模式 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 loadAttributeMap(String nodePath){
		Map fromToMap=new HashMap();
		//日志信息
		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 loadTextMap(String nodePath){
		Map fromToMap=new HashMap();
		//日志信息
		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 getAlarmLevelsMap() {
		return alarmLevelsMap;
	}

	public void setAlarmLevelsMap(Map alarmLevelsMap) {
		this.alarmLevelsMap = alarmLevelsMap;
	}

	public Map getSheetStatusTransMap() {
		return sheetStatusTransMap;
	}

	public void setSheetStatusTransMap(Map sheetStatusTransMap) {
		this.sheetStatusTransMap = sheetStatusTransMap;
	}


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

 

 

配置文件:


	
		
		127.0.0.1
		
		51088

		
		
			
			
			
			
		

		
		
			
				草稿1
			
			
				一级处理中2
			
			
				二级处理中3
			
			
				三级处理中4
			
		
		
		
		12
	
 

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