com.app.common.config.PropertiesHelper Maven / Gradle / Ivy
The newest version!
package com.app.common.config;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gw.common.utils.HostTools;
import com.gw.common.utils.HostTools.InvalidHostException;
/**
* PropertiesHelper对Properties类的简单扩张
* 支持扩展标签@include
* eg.
* #@include*命令用于引入新的配置文件
* #@include=./control/***1.ini
* #@include0=./control/***2.ini
* #@include1=./control/***3.ini
* #@include45=./control/***4.ini
* #Note: 只处理了load(InputStream inStream)和loadFromXML(InputStream
* inStream)方法,其它保留不变
*
* @author Guohai.Shan
*/
public class PropertiesHelper extends Properties {
private static Logger logger = LoggerFactory.getLogger(PropertiesHelper.class);
public static void main(String[] args) throws IOException {
System.out.println(PropertiesHelper.getFullPath("", "./control/DDD.ini"));
PropertiesHelper properties = new PropertiesHelper();
try {
properties.load("./control/DBPoolConfig.ini");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try
// {
// FileOutputStream xmlout = new FileOutputStream("./control/KeyFull.ini");
//
//
// properties.store(xmlout, "测试用例");
// }
// catch (FileNotFoundException e)
// {
// e.printStackTrace();
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
{
System.out.println("------------------------------------------");
DBParam dbParam = properties.findDBParam("JDBC.ATSDB1");
System.out.println(printParmas(dbParam));
}
{
System.out.println("------------------------------------------");
DBParam dbParam = properties.findDBParam("SERVICENAME.PBOX");
System.out.println(printParmas(dbParam));
}
{
System.out.println("------------------------------------------");
System.out.println(printParmas(properties.findServerParam("SERVER.AMQIIIServerAdapter")));
System.out.println(printParmas(properties.findClientParam("CLIENT.xxx")));
System.out.println(printParmas(properties.findClientParam("REGISTER.xxx1")));
System.out.println(printParmas(properties.findRegisterParams()));
}
}
public static String printParmas(DBParam params) {
StringBuffer buff = new StringBuffer("DBParam={");
if (params.Driver.length() <= 0) {
buff.append("SERVICENAME:").append(params.Driver).append(",");
} else {
buff.append("JDBC:").append(params.Driver).append(",");
}
buff.append("Url:").append(params.Url).append(",");
buff.append("UserName:").append(params.UserName).append(",");
buff.append("Passwd:").append(params.Passwd).append("}");
return buff.toString();
}
public static String printParmas(RegisterParams params) {
return printParmas((ServerParams) params);
}
public static String printParmas(List params) {
StringBuffer buff = new StringBuffer("RegisterList={");
for (RegisterParams reg : params) {
buff.append(printParmas((ServerParams) reg));
}
buff.append("}");
return buff.toString();
}
public static String printParmas(ClientParams params) {
return printParmas((ServerParams) params);
}
public static String printParmas(ServerParams params) {
StringBuffer buff = new StringBuffer("ServerParams={");
buff.append(params.Name).append("=");
buff.append(params.Host).append(":");
buff.append(params.Port).append(",");
buff.append(params.RegType).append(",");
buff.append(params.LBFactor).append(",");
buff.append(params.RegisterEnable).append(",");
buff.append(params.RegisterServerList).append("");
if (params.RegisterEnable) {
buff.append("[");
for (RegisterParams tmpReg : params.RegisterConfigs) {
buff.append(tmpReg.Name).append("=");
buff.append(tmpReg.Host).append(":");
buff.append(tmpReg.Port).append(";");
}
buff.append("]");
}
buff.append("}");
return buff.toString();
}
public static String getATS_ROOT() {
String value = null;
try {
value = System.getenv("BACKEND_ROOT");
logger.info("BACKEND_ROOT:{}",value);
} catch (Exception e) {
e.printStackTrace();
}
return (value == null) ? "" : value;
}
/**
* serialVersionUID
*/
private static final long serialVersionUID = 6951608021703880014L;
public void load(String path) throws IOException {
this.load(new FileInputStream(path));
}
public void load(InputStream inStream) throws IOException {
Properties temp = new Properties();
temp.load(inStream);
for (Object key : temp.keySet()) {
if (key.toString().toLowerCase().startsWith("@include")) {
String value = temp.get(key).toString();
if (value != null && value.trim().compareTo("") != 0) {
value = getFullPath(PropertiesHelper.getATS_ROOT(), value);
super.load(new FileInputStream(value));
}
} else {
this.put(key, temp.get(key));
}
}
}
public static String getRealPath(String text) {
StringBuffer buf = new StringBuffer(text);
for (int startIndex = buf.indexOf("${"); startIndex != -1;) {
int endIndex = buf.indexOf("}", startIndex + "${".length());
if (endIndex != -1) {
String placeholder = buf.substring(startIndex + "${".length(), endIndex);
int nextIndex = endIndex + "}".length();
try {
String propVal = System.getProperty(placeholder);
if (propVal == null)
propVal = System.getenv(placeholder);
if (propVal != null) {
buf.replace(startIndex, endIndex + "}".length(), propVal);
nextIndex = startIndex + propVal.length();
} else {
System.err.println("Could not resolve placeholder '" + placeholder + "' in [" + text
+ "] as system property: neither system property nor environment variable found");
}
} catch (Throwable ex) {
System.err.println("Could not resolve placeholder '" + placeholder + "' in [" + text
+ "] as system property: " + ex);
}
startIndex = buf.indexOf("${", nextIndex);
} else {
startIndex = -1;
}
}
return buf.toString();
}
public static String getFullPath(String root, String config) {
if (root.length() > 0) {
if (root.endsWith("/")) {
root = root.substring(0, root.length() - 1);
}
if (config.startsWith(".")) {
config = config.substring(1);
}
return root + config;
}
if (config.startsWith("./")) {
return config;
} else if (config.startsWith("/")) {
return "." + config;
} else {
return "./" + config;
}
}
public static String getEnvPath(String root) {
String value = null;
try {
value = System.getenv(root);
} catch (Exception e) {
e.printStackTrace();
}
return (value == null) ? "" : value;
}
public static String getFullPath(String config) {
String retval = config;
if (config.startsWith("$")) {
String root = config.substring(1, config.indexOf("/"));
String temp = config.substring(config.indexOf("/"));
retval = getFullPath(getEnvPath(root), temp);
}
return retval;
}
public void loadFromXML(InputStream inStream) throws IOException {
Properties temp = new Properties();
temp.loadFromXML(inStream);
for (Object key : temp.keySet()) {
if (key.toString().toLowerCase().startsWith("@include")) {
String value = temp.get(key).toString();
if (value != null && value.trim().compareTo("") != 0) {
value = getFullPath(PropertiesHelper.getATS_ROOT(), value);
super.loadFromXML(new FileInputStream(value.toString()));
}
} else {
this.put(key, temp.get(key));
}
}
}
/**
* 获取参数
*
* @param name 必须是以包含'.'分隔符
* @return
* @throws IOException
*/
public DBParam findDBParam(String name) throws IOException {
DBParam dbParam = new DBParam();
String nameSplit[] = (name + "").split("\\.");
if (nameSplit.length >= 1) {
if (nameSplit[0].equalsIgnoreCase((DBParam.TYPE.JDBC).toString())) {
dbParam.Driver = this.getProperty((name + ".Driver").trim());
dbParam.Url = this.getProperty((name + ".Url").trim());
dbParam.UserName = this.getProperty((name + ".UserName").trim());
dbParam.Passwd = this.getProperty((name + ".Passwd").trim());
return dbParam;
} else if (nameSplit[0].equalsIgnoreCase((DBParam.TYPE.ServiceName).toString())) {
dbParam.Url = this.getProperty((name + ".Url").trim());
dbParam.UserName = this.getProperty((name + ".UserName").trim());
dbParam.Passwd = this.getProperty((name + ".Passwd").trim());
return dbParam;
}
}
return null;
}
public List findRegisterParams() throws IOException {
String temp = this.getProperty(("REGISTER.ServerList").trim()) + "";
String[] array = temp.split(",");
List registerConfigs = new ArrayList();
for (String str : array) {
if (str != null && str.length() > 0) {
RegisterParams tmpParams = findRegisterParam(str);
if (tmpParams != null) {
registerConfigs.add(tmpParams);
}
}
}
return registerConfigs;
}
public RegisterParams findRegisterParam(String name) throws IOException {
ServerParams params = findServerParam(name);
return params;
}
public ClientParams findClientParam(String name) throws IOException {
ServerParams params = findServerParam(name);
return params;
}
private boolean isYes(String str) {
if (str == null) {
return false;
}
str = str.trim();
if ("1".equals(str) || "y".equalsIgnoreCase(str) || "yes".equalsIgnoreCase(str)
|| "true".equalsIgnoreCase(str)) {
return true;
}
return false;
}
public ServerParams findServerParam(String name) throws IOException {
ServerParams dbParam = new ServerParams();
String nameSplit[] = (name + "").split("\\.");
if (nameSplit[0].equalsIgnoreCase((TYPE.Regiser).toString())) {
setHostInfo(name, dbParam);
}
if (nameSplit[0].equalsIgnoreCase((TYPE.Server).toString())
|| nameSplit[0].equalsIgnoreCase((TYPE.Client).toString())) {
setHostInfo(name, dbParam);
dbParam.ServiceName = this.getProperty((name + ".ServiceName").trim());
String temp = this.getProperty((name + ".RegisterEnable").trim()) + "";
dbParam.RegisterEnable = isYes(temp);
dbParam.RegisterServerList = this.getProperty((name + ".RegisterServerList"));
setInfoAboutRegistry(name, dbParam, nameSplit[0].equalsIgnoreCase((TYPE.Server).toString()));
}
return dbParam;
}
private void setInfoAboutRegistry(String name, ServerParams dbParam, boolean isSvr) throws IOException {
if (dbParam.RegisterEnable == false) {
return;
}
if (dbParam.ServiceName == null || dbParam.ServiceName.length() == 0) {
throw new IOException("RegisterEnable is set. But no ServiceName - " + name);
}
if (dbParam.RegisterServerList == null || dbParam.RegisterServerList.length() == 0) {
throw new IOException("RegisterEnable is set. But no RegisterServerList - " + name);
}
String[] array = dbParam.RegisterServerList.split(",");
for (String str : array) {
if (str != null && str.length() > 0) {
RegisterParams tmpParams = findRegisterParam(str);
if (tmpParams != null) {
dbParam.RegisterConfigs.add(tmpParams);
}
}
}
if (isSvr) {
try {
String temp = this.getProperty((name + ".RegType").trim()) + "";
dbParam.RegType = Integer.valueOf(temp);
temp = this.getProperty((name + ".LBFactor").trim()) + "";
dbParam.LBFactor = Integer.valueOf(temp);
} catch (NumberFormatException e) {
throw new IOException("RegType or LBFactor is invalid when RegisterEnable is set. - " + name, e);
}
}
}
private void setHostInfo(String name, ServerParams params) throws IOException {
params.Name = this.getProperty((name + ".Name").trim());
String hostStr = this.getProperty((name + ".Host").trim());
String hostMode = this.getProperty((name + ".HostMode").trim());
if (hostStr == null) {
// 由于原来只有这个异常,所以 借用io exception,不很恰当
throw new IOException(name + ".Host is empty, MUST set it.");
}
try {
if (hostMode == null || (hostMode = hostMode.trim()).length() == 0) {
noHostMode(hostStr, params);
} else {
hostMode(hostMode, hostStr, params);
}
} catch (NumberFormatException e) {
// 不很恰当
throw new IOException(
name + ".Host format is invalid, pls check the port. - Host=" + hostStr + ",HostMode=" + hostMode);
} catch (InvalidHostException e) {
throw new IOException(e);
}
}
private void noHostMode(String hostStr, ServerParams params) {
if (hostStr.indexOf(':') > 0) {
String[] tempArray = hostStr.split(":");
params.Host = tempArray[0];
params.Port = Integer.valueOf(tempArray[1]);
} else {
params.Host = hostStr;
params.Port = 80;
}
}
private void hostMode(String hostMode, String hostStr, ServerParams params) throws InvalidHostException {
// 可以忽略host,只配置一个参数,该参数为端口
if (hostStr.indexOf(':') > 0) {
params.Port = Integer.valueOf(hostStr.split(":")[1]);
} else {
params.Port = Integer.valueOf(hostStr);
;
}
String m[] = hostMode.split(":"); // 第一个为模式,后面是模式的参数
String mode = m[0];
// 设置主机地址,在模式匹配情况下,无论设置什么名称都会被替换掉
if ("host".equalsIgnoreCase(mode)) {
params.Host = HostTools.getHostName();
} else if ("ip".equalsIgnoreCase(mode)) {
setIp(m, params);
} else if ("hostmap".equalsIgnoreCase(mode)) {
setHostMap(m, params);
} else {
throw new InvalidHostException("Unknown host mode : " + mode);
}
}
private void setIp(String[] modes, ServerParams params) throws InvalidHostException {
// split保证至少有一个
if (modes.length == 1) {
String[] ips = HostTools.getAllIP();
if (ips.length == 0) {
throw new InvalidHostException("Can't get ip. Maybe no ip is set.");
}
if (ips.length != 1) {
moreThanOneException(ips, params.Name);
}
params.Host = ips[0];
} else {
String filter = modes[1];
params.Host = HostTools.getIP(filter);
}
}
private void setHostMap(String[] modes, ServerParams params) throws InvalidHostException {
String name = null;
String filter = null;
if (modes.length == 1) {
// hostmap
name = HostTools.getHostName();
}
if (modes.length >= 2) {
// hostmap:XX
name = modes[1].trim();
if (name.charAt(0) == '$') {
name = HostTools.getHostName();
}
}
if (modes.length >= 3) { // 大于3
// hostmap:XX:192.168,正式因为如此,所以如果使用本主机名称时必须指定filter,此时本名称使用$表示
filter = modes[2].trim();
}
// 返回一定有,否则触发异常
String adds[] = HostTools.getAddress(name);
if (filter == null) {
// 如果有多个则报错,不能随意指定
if (adds.length != 1) {
moreThanOneException(adds, name);
} else {
params.Host = adds[0];
}
} else {
List list = new ArrayList();
for (String ip : adds) {
if (ip.startsWith(filter)) {
list.add(ip);
}
}
// 如果有filter,且无匹配或匹配到多个则异常
if (list.size() == 1) {
params.Host = list.get(0);
} else if (list.size() == 0) {
throw new InvalidHostException("Can't get the address for name=" + name + ",filter=" + filter);
} else {
moreThanOneException(list.toArray(new String[list.size()]), name);
}
}
}
private void moreThanOneException(Object adds[], String name) throws InvalidHostException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < adds.length; i++) {
sb.append(adds[i]).append(",");
}
throw new InvalidHostException("More than one address in hosts about '" + name + "' : " + sb);
}
public enum TYPE {
UnKnown, Server {
public String toString() {
return "SERVER";
}
},
Client {
public String toString() {
return "CLIENT";
}
},
Regiser {
public String toString() {
return "REGISTER";
}
}
}
}