INI

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.javaUtil.launch.reflect.ReflectByClassName;


/**
 * function file to read ini config file 
 */
public class INI {

	private static Logger logger = Logger.getLogger(INI.class);
	
	private final ConcurrentHashMap<String, Object> params = new ConcurrentHashMap<String, Object>();
	
	public String FILENAME = "";
	
	public INI() {
		
	}
	
	public INI(String filename, Class<?> cls) {
		FILENAME = filename;
		doInit(filename, cls);
	}
	
	public INI(String commFileName,String relativePath, String fileName, Class<?> objClass) {
		FILENAME = getFullFilename(relativePath, fileName, commFileName);
		doInit(FILENAME, objClass);
	}
	
	private void doInit(String filename,Class<?> cls) {
		if (params != null) {
			params.clear();
		}
		
		try {
			ConcurrentHashMap<String, ConcurrentHashMap<String, String>> concurrentHashMap = IniUtil.getAllProfileStrings(filename);
			Set<String> keys = concurrentHashMap.keySet();
			
			for (String key : keys) {
				Object obj = cls.newInstance();
				ConcurrentHashMap<String, String> valueMap = concurrentHashMap.get(key);
				
				Set<String> innerkeys = valueMap.keySet();
				for (String innerKey : innerkeys){
					ReflectByClassName.setValue(obj, innerKey, valueMap.get(innerKey));
				}

				params.put(key, obj);
			}
			
		} catch (IOException | InstantiationException | IllegalAccessException e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	
	
	public ConcurrentHashMap<String,Object> getParams(){
		return params;
	}
	
	
	public Object getParamObj(String key) {
		if (null == key || key == "") {
			return null;
		}
		
		return params.get(key);
	}
	
	
	public void saveParam(String fileName,String section,String variable, String value) {
		try {
			Object obj = params.get(section);
			
			if (null == obj) {
				logger.warn("[" + section + "] doesn't exists "); 
				return;
			}
			
			ReflectByClassName.setValue(obj, variable, value);
			
			if (null == fileName || fileName == "") {
				if (this.FILENAME != null && !"".equals(this.FILENAME)) {
					IniUtil.setProfileString(this.FILENAME, section, variable, value);
				}
			} else {
				IniUtil.setProfileString(fileName, section, variable, value);
			}
			
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	
	public void saveParam(String filename, String section, Object obj) {
		try {
			if (null == section || "".equals(section) || null == params.get(section)) {
				logger.warn("[" + section + "] doesn't exists "); 
				return;
			}
			
			if (null == filename || filename == "") {
				filename = this.FILENAME;
			}
			
			params.put(section, obj);
			
			Field[] fields = obj.getClass().getDeclaredFields();

			for (Field field : fields){
				IniUtil.setProfileString(filename,section,field.getName(),(String) ReflectByClassName.getValue(obj,field.getName()));
			}
		} catch (SecurityException e) {
			logger.error(e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
		
	}
	
	
	public static String getFullFilename(String relativePath,String fileName,String commFileName) {
		String cFile = IniUtil.getFullFilename(relativePath, commFileName);
		if (new File(cFile).exists()) {
			try {
				ConcurrentHashMap<String, ConcurrentHashMap<String, String>> concurrentHashMap = IniUtil.getAllProfileStrings(cFile);
				if (concurrentHashMap != null && concurrentHashMap.size() > 0 && concurrentHashMap.get(fileName) != null) {
					String path = concurrentHashMap.get(fileName).get("path");
					if (path != null && new File(path).exists()) {
						return path;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return IniUtil.getFullFilename(relativePath, fileName);
	}
	
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;


/**
 * function: ini config file dealer, to read and set ini config file
 */
public final class IniUtil {
	
	private static Logger logger = Logger.getLogger(IniUtil.class);
	
	/**
	 * function:get profile
	 * @param file ini config file path
	 * @param section variable column name
	 * @param var var variable name, matches the ini file key
	 * @param defaultVal variable is null or empty,use defaultValue
	 * @return
	 */
	public static String getProfileString(String file,String section,String varName,String defaultVal) throws IOException{
		//check input param
		if (null == file || "".equals(file.trim())
				|| null == section || "".equals(section.trim())
				|| null == varName || "".equals(varName.trim())) {
			return defaultVal;
		}
		
		String strLine, key = "";
		BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
		boolean isInSection = false;
		
		try {
			while((strLine = bufferedReader.readLine()) != null) {
				strLine = strLine.trim();
				
				//check line data, empty string or start with # is ignore to deal with
				if (!"".equals(strLine) && !strLine.startsWith("#")) {
					strLine = strLine.split("[;]")[0];
					
					Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");
					Matcher m = p.matcher((strLine));
					
					if (m.matches()){
						p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
						m = p.matcher(strLine);
						if (m.matches()){
							isInSection = true;
						} else {
							isInSection = false;
						}
					}
					
					if (isInSection == true){
						strLine = strLine.trim();
						String[] strArray = strLine.split("=");
						if (strArray.length == 1){
							key = strArray[0].trim();
							if (key.equalsIgnoreCase(varName)){
								return "";
							}
						} else if (strArray.length == 2){
							key = strArray[0].trim();
							if (key.equalsIgnoreCase(varName)){
								return strLine.substring(strLine.indexOf("=") + 1).trim();
							}
						} else if (strArray.length > 2){
							key = strArray[0].trim();
							if (key.equalsIgnoreCase(varName)){
								return strLine.substring(strLine.indexOf("=") + 1).trim();
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		} finally {
			bufferedReader.close();
		}
		
		return defaultVal;
	}
	
	/**
	 * function:TODO
	 * @param file
	 * @param section
	 */
	public static ConcurrentHashMap<String, String> getProfileStrings(String file, String section) throws IOException{
		if (null == file || "".equals(file.trim()) || null == section || "".equals(section.trim())) {
			return null;
		}
		
		ConcurrentHashMap<String, String> results = new ConcurrentHashMap<String, String>();
		String strLine = "";
		BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
		boolean isInSection = false;
		boolean isBreak = false;
		
		try{
			while ((strLine = bufferedReader.readLine()) != null){
				strLine = strLine.trim();
				
				if (!"".equals(strLine.trim()) && !strLine.startsWith("#")) {
					strLine = strLine.split("[;]")[0];
					Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");
					Matcher m = p.matcher((strLine));
					
					if (m.matches()){
						if (isBreak){
							break;
						}

						p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
						m = p.matcher(strLine);
						if (m.matches()){
							isInSection = true;
							isBreak = true;
						} else{
							isInSection = false;
							isBreak = false;
						}
					}
					
					if (isInSection == true){
						strLine = strLine.trim();
						String[] strArray = strLine.split("=");
						if (strArray.length == 1){
							results.put(strArray[0].trim(), "");
						} else if (strArray.length == 2){
							results.put(strArray[0].trim(), strLine.substring(strLine.indexOf("=") + 1).trim());
						} else if (strArray.length > 2){
							results.put(strArray[0].trim(), strLine.substring(strLine.indexOf("=") + 1).trim());
						}
					}
				}
			}
		} catch (Exception e){
			logger.error(e);
			e.printStackTrace();
		} finally {
			bufferedReader.close();
		}
		return results;
	}
	
	public static ConcurrentHashMap<String, ConcurrentHashMap<String, String>> getAllProfileStrings(String file) throws IOException{
		if (file == null || "".equals(file)){
			return null;
		}
		
		ConcurrentHashMap<String, ConcurrentHashMap<String, String>> results = new ConcurrentHashMap<String, ConcurrentHashMap<String, String>>();
		String section = "", strLine = "";
		
		InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
		BufferedReader bufferedReader = new BufferedReader(isr);
		
		try{
			while ((strLine = bufferedReader.readLine()) != null){
				strLine = strLine.trim();
				
				if (!"".equals(strLine.trim()) && !strLine.startsWith("#")) {
					strLine = strLine.split("[;]")[0];
					Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");
					Matcher m = p.matcher((strLine));
					
					if (m.matches()){
						section = strLine.substring(1, strLine.length() - 1);
						ConcurrentHashMap<String, String> temp = new ConcurrentHashMap<String, String>();
						results.put(section, temp);
					} else {
						strLine = strLine.trim();
						if (strLine == null || "".equalsIgnoreCase(strLine)){
							continue;
						}
						
						String[] strArray = strLine.split("=");
						if (strArray.length == 1){
							results.get(section).put(strArray[0].trim(), "");
						} else if (strArray.length == 2){
							results.get(section).put(strArray[0].trim(),strLine.substring(strLine.indexOf("=") + 1).trim());
						} else if (strArray.length > 2){
							results.get(section).put(strArray[0].trim(),strLine.substring(strLine.indexOf("=") + 1).trim());
						}
					}
				}
			}
		} catch (Exception e){
			logger.error(e);
			e.printStackTrace();
		} finally{
			bufferedReader.close();
		}
		return results;
	}
	
	public static Set<String> getSections(String file) throws IOException{
		if (file == null || "".equals(file.trim())){
			return null;
		}

		Set<String> results = new CopyOnWriteArraySet<String>();
		String strLine = "";
		BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
		try{
			while ((strLine = bufferedReader.readLine()) != null){
				strLine = strLine.trim();
				strLine = strLine.split("[;]")[0];
				Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");
				Matcher m = p.matcher((strLine));
				
				if (m.matches()){
					results.add(strLine.substring(1, strLine.length() - 1));
				}
			}
		} finally {
			bufferedReader.close();
		}
		return results;
	}
	
	
	public static boolean setProfileString(String file, String section, String variable, String value) throws IOException{
		if (file == null || "".equals(file.trim()) 
				|| section == null || "".equals(section.trim())
				|| variable == null || "".equals(variable.trim())){
			return false;
		}

		String fileContent, allLine, strLine, newLine, remarkStr;
		String getValue;
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));

		boolean isInSection = false;
		fileContent = "";
		try {
			while ((allLine = bufferedReader.readLine()) != null){
				allLine = allLine.trim();
				if (allLine.split("[;]").length > 1)
					remarkStr = ";" + allLine.split(";")[1];
				else
					remarkStr = "";
				strLine = allLine.split(";")[0];
				Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");
				Matcher m = p.matcher((strLine));
				
				if (m.matches()){
					p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
					m = p.matcher(strLine);
					if (m.matches()){
						isInSection = true;
					} else{
						isInSection = false;
					}
				}
				
				if (isInSection == true){
					strLine = strLine.trim();
					String[] strArray = strLine.split("=");
					getValue = strArray[0].trim();
					if (getValue.equalsIgnoreCase(variable)){
						newLine = getValue + "=" + value + remarkStr;
						fileContent += newLine + "\r\n";
						while ((allLine = bufferedReader.readLine()) != null){
							fileContent += allLine + "\r\n";
						}
						bufferedReader.close();

						BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
						bufferedWriter.write(fileContent);
						bufferedWriter.flush();
						bufferedWriter.close();
						return true;
					}
				}
				fileContent += allLine + "\r\n";
			}
		} catch (IOException e){
			logger.error(e);
			e.printStackTrace();
		} finally{
			bufferedReader.close();
		}
		return false;
	}
	
	public static String getFullFilename(String relativePath, String filename){
		String filename1 = null;
		String filename2 = null;
		String filename3 = null;
		String filename5 = null;

		//get the classes path of the java file
		String classesPath = IniUtil.class.getResource("/").toString();

		String webinfoPath = classesPath.substring(0, classesPath.length() - 9);
		String webRoot = classesPath.substring(0, classesPath.length() - 17);
		webinfoPath = webinfoPath.replaceAll("file:/", "");
		webRoot = webRoot.replaceAll("file:/", "");

		String os = System.getProperty("file.separator");
		if (os.equals("/")){
			webinfoPath = "/" + webinfoPath;
			webRoot = "/" + webRoot;
		}

		if (relativePath != null && !"".equals(relativePath)){
			filename1 = webinfoPath + File.separator + relativePath + File.separator + filename;
		} else{
			filename1 = webinfoPath + File.separator + filename;
		}

		if (relativePath != null && !"".equals(relativePath)){
			filename2 = System.getProperty("user.dir") + File.separator + relativePath + File.separator + filename;
		} else{
			filename2 = System.getProperty("user.dir") + File.separator + filename;
		}

		if (relativePath != null && !"".equals(relativePath)){
			filename3 = webRoot + File.separator + relativePath + File.separator + filename;
		} else{
			filename3 = webRoot + File.separator + filename;
		}

		if (relativePath != null && !"".equals(relativePath)){
			filename5 = System.getProperty("user.dir") + File.separator + "WebContent" + File.separator + "WEB-INF"
					+ File.separator + relativePath + File.separator + filename;
		} else{
			filename5 = System.getProperty("user.dir") + File.separator + "WebContent" + File.separator + "WEB-INF"
					+ File.separator + filename;
		}

		String filename4 = classesPath.replaceAll("file:/", "") + File.separator + filename;

		String realFilename = filename;

		logger.info("=====>" + filename);
		logger.info("=====>" + filename1);
		logger.info("=====>" + filename2);
		logger.info("=====>" + filename3);
		logger.info("=====>" + filename4);
		logger.info("=====>" + filename5);
		if (new File(filename3).exists()){
			realFilename = filename3;
		} else if (new File(filename1).exists()){
			realFilename = filename1;
		} else if (new File(filename2).exists()){
			realFilename = filename2;
		} else if (new File(filename4).exists()){
			realFilename = filename4;
		} else if (new File(filename5).exists()){
			realFilename = filename5;
		} else{
			realFilename = filename;
		}

		return realFilename;
	}
	
	
	public static void main(String[] args) {
		System.out.println(getWebRoot());
	}
	
	public static String getWebRoot(){
		String classesPath = IniUtil.class.getResource("/").toString();

		String webRoot = classesPath.substring(0, classesPath.length() - 17);

		webRoot = webRoot.replaceFirst("file:", "");
		if (webRoot.indexOf(":/") != -1){
			webRoot = webRoot.substring(1);
		}

		return webRoot;
	}
	
	
}


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectByClassName {
	
	/**
	 * function: copy attributes to init dest Object
	 * @param destObj
	 * @param srcObj
	 */
	public static void copyProperties(Object destObj,Object srcObj) {
		Class<?> destCls = destObj.getClass();
		Class<?> srcCls = srcObj.getClass();
		
		Field[] fileds = srcCls.getDeclaredFields();
		
		try {
			for (Field f : fileds) {
				String fieldName = f.getName();
				String fGetName = "get" + toFirstLetterUpperCase(fieldName);
				String fSetName = "set" + toFirstLetterUpperCase(fieldName);
				
				Object value = srcCls.getMethod(fGetName).invoke(srcObj) ;
				destCls.getMethod(fSetName,value.getClass()).invoke(destObj, value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * function: uppperCase the first letter of the filed
	 * @param str
	 */
	public static String toFirstLetterUpperCase(String str){
		if (str == null || str.length() < 2){
			return str;
		}
		String firstLetter = str.substring(0, 1).toUpperCase();
		return firstLetter + str.substring(1, str.length());
	}
	
	/**
	 * function: assign value to the filed of the target object
	 * @param obj
	 * @param filed
	 * @param value
	 */
	public static void setValue(Object obj, String filed, String value){
		try {
			Class<?> cls = obj.getClass();
			String setMethodName = "set" + toFirstLetterUpperCase(filed);
			cls.getMethod(setMethodName, value.getClass()).invoke(obj, value);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * function:fetch object value of the field
	 * @param obj
	 * @param filed
	 * @return
	 */
	public static Object getValue(Object obj, String filed){
		try{
			Class<?> cls = obj.getClass();
			String getMethodName = "get" + toFirstLetterUpperCase(filed);
			return cls.getMethod(getMethodName).invoke(obj);
		} catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
}

转载于:https://my.oschina.net/u/2611678/blog/1816783

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值