服务启动初始化相关配置 如XMLpropertieslog等文件
Posted 绿源2008
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了服务启动初始化相关配置 如XMLpropertieslog等文件相关的知识,希望对你有一定的参考价值。
服务启动初始化相关配置 如XML、properties、log等文件/**
*
*/
package com.companyName.dhm.common.init;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Iterator;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.companyName.dhm.common.config.impl.ConfigFactory;
import com.companyName.dhm.common.log.config.Log4jConfigurer;
import com.companyName.dhm.common.uif.config.EndpointItem;
import com.companyName.dhm.common.uif.config.SystemConfig;
import com.companyName.dhm.report.service.ReportService;
/**
* @author
*
*/
public class InitSystemListener implements ServletContextListener {
ReportService reportService;
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent sce) {
String FS = System.getProperty("file.separator");
ServletContext ctx = sce.getServletContext();
// invoke system initial filter
System.out.println("========================");
System.out.println("BI: Initial system...");
SystemInitiator.initApp(ctx);
// print welcome.txt
System.out.println("BI: welcome info");
printWelcome(ctx.getInitParameter("system.welcome-file-name"));
// print version info
System.out.println("BI: version info");
VersionInfo.init(ctx.getInitParameter("system.version-file-name"));
System.out.println(VersionInfo.getVersionInfo());
// initial log configuration
System.out.println("BI: Initial log...");
String logFile = ctx.getInitParameter("log.config-file");
if (logFile == null || logFile.trim().length() == 0) {
System.out.println("BI: log.config-file is not configed, so not initial!!! ");
} else {
String logConfigFileLocation = SystemInitiator.getSystemInfo()
.getConfPath()
+ FS + logFile;
try {
int refreshInterval = Integer.parseInt(ctx
.getInitParameter("log.config-file-refresh-interval"));
System.out.println("logConfigFileLocation="
+ logConfigFileLocation + ",refreshInterval="
+ refreshInterval);
Log4jConfigurer.initLogging(logConfigFileLocation,
refreshInterval);
} catch (Exception e) {
System.out.println("BI: Initail log4f config error:"
+ e.getMessage());
System.exit(1);
}
}
// Initial License
// System.out.println("BI: Initial license...");
// String licenseFileName = ctx.getInitParameter("license.license-file");
// String publicKeyFileName = ctx
// .getInitParameter("license.public-key-file");
// new com.companyName.dhm.common.license.LicenseInit().init(licenseFileName,
// publicKeyFileName);
// initial log configuration
System.out.println("BI: Initial system configuration...");
String configFile = ctx.getInitParameter("config.system-config-file");
if (configFile == null || configFile.trim().length() == 0) {
System.out.println("BI: config.system-config-file is not configed, so not initial!!! ");
} else {
new ConfigFactory().initConfig(SystemInitiator.getSystemInfo()
.getConfPath(), configFile);
}
ApplicationContext appctx=null;
System.out.println("Update VOD record valid Time");
appctx = new ClassPathXmlApplicationContext(new String[]{"spring/applicationcontext-datasource.xml",
"spring/applicationcontext-report.xml",
"spring/applicationcontext-adminmanage.xml",
"spring/applicationcontext-logmanage.xml",
"spring/applicationcontext-rolemanage.xml"});
reportService = (ReportService) appctx.getBean("ReportService");
String validTimeStr = ctx.getInitParameter("system.configValidTime-file-name");
System.out.println("Read validTimeStr>>>>>"+validTimeStr);
int validTime = Integer.parseInt(getValidTime(validTimeStr));
reportService.updateValidTime(validTime);
System.out.println("Update VOD record valid Time["+validTime+"]");
}
private void printWelcome(String welcomeFileName) {
String FS = System.getProperty("file.separator");
String welcomeFile = SystemInitiator.getSystemInfo().getConfPath() + FS
+ welcomeFileName;
File file = new File(welcomeFile);
try {
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
StringBuffer sb = new StringBuffer(100);
String str;
boolean firstLine = true;
while ((str = br.readLine()) != null) {
if (firstLine) {
sb.append(str);
firstLine = false;
} else {
sb.append("\n").append(str);
}
}
System.out.println(sb.toString());
br.close();
fileReader.close();
} catch (Exception e) {
System.out
.println("BI: Read welcome file error:" + e.getMessage());
}
}
private String getValidTime(String FileName) {
String FS = System.getProperty("file.separator");
String welcomeFile = SystemInitiator.getSystemInfo().getConfPath() + FS
+ FileName;
File file = new File(welcomeFile);
String lineTxt = null;
String defaultValue = "600";
StringBuffer sb = new StringBuffer();
try {
String encoding = "UTF-8";
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
while ((lineTxt = bufferedReader.readLine()) != null) {
sb.append(lineTxt);
}
read.close();
//System.out.println("读取到的数值>>>>" + sb.toString());
return sb.toString();
} else {
System.out.println("BI: Can‘t find configValidTime.txt file");
}
} catch (Exception e) {
System.out.println("BI: Read configValidTime.txt file error:"
+ e.getMessage());
}
return defaultValue;
}
}
/**
*
*/
package com.companyName.dhm.common.init;
import javax.servlet.ServletContext;
/**
* @author
*
*/
public class SystemInitiator {
static private SystemInfo systemInfo = null;
static public SystemInfo getSystemInfo(){
return systemInfo;
}
public static void setSystemInfo(SystemInfo systemInfo) {
SystemInitiator.systemInfo = systemInfo;
}
public static void initApp(ServletContext ctx){
//get file seperator
String FS = System.getProperty("file.separator");
//get system name configed in web.xml
String systemName = ctx.getInitParameter("dhm-system-name");
//get working dir
String work_dir = System.getProperty("user.dir");
//set conf path
String confPath = work_dir + FS + systemName+ FS + ctx.getInitParameter("system.config-path-name");
//set log path
String logPath = work_dir + FS + systemName+ FS + ctx.getInitParameter("system.log-path-name");
systemInfo = new SystemInfo(systemName,confPath,logPath);
System.out.println(systemInfo.toString());
}
}
package com.companyName.dhm.common.init;
/**
* @author
*
*/
public class SystemInfo {
private String systemName = null;
private String confPath = null;
private String logPath = null;
public SystemInfo(String systemName, String confPath, String logPath) {
this.systemName = systemName;
this.confPath = confPath;
this.logPath = logPath;
}
public String getSystemName() {
return systemName;
}
public String getConfPath() {
return confPath;
}
public String getLogPath() {
return logPath;
}
public String toString() {
return this.getClass().getName() + "[systemName="
+ this.getSystemName() + ";confPath=" + this.getConfPath()
+ ";logPath=" + this.getLogPath() + "]";
}
}
/**
*
*/
package com.companyName.dhm.common.init;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
/**
* @author
*
*/
public class VersionInfo {
private static String version_info = null;
/**
*
*/
public static void init(String verFileName) {
String FS = System.getProperty("file.separator");
String welcomeFile = SystemInitiator.getSystemInfo().getConfPath() + FS
+ verFileName;
File file = new File(welcomeFile);
try {
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
StringBuffer sb = new StringBuffer(100);
String str;
boolean firstLine = true;
while ((str = br.readLine()) != null) {
if (firstLine) {
sb.append(str);
firstLine = false;
} else {
sb.append("\n").append(str);
}
}
version_info = sb.toString();
br.close();
fileReader.close();
} catch (Exception e) {
System.out
.println("DHM: Read welcome file error:" + e.getMessage());
}
}
public static String getVersionInfo() {
return version_info;
}
}
/*
* 工 程 名: common
* 包 名: com.companyName.dhm.common.log.config
* 文 件 名: Log4jConfigurer.java
* 版 权: Copyright (c) 2009 companyName All Rights Reserved.
* 描 述: log4j配置文件加载类
* 修 改 人:
* 修改时间:
* 跟踪单号: <跟踪单号>
* 修改单号: <修改单号>
* 修改内容: <修改内容>
*/
package com.companyName.dhm.common.log.config;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
/**
*
* 加载log4j配置文件的接口抽象类
* 支持绝对路径,相对路径,类路径,URL等方式加载,支持log4j日志文件被修改后不用重起服务可生效
*
* @author
* @version
* @see org.apache.log4j.xml.DOMConfigurator
* @see org.apache.log4j.PropertyConfigurator
* @see org.apache.log4j.LogManager
* @since [DHM.Core.IEPGM-V200R001]
*/
public abstract class Log4jConfigurer
{
/**
* 类路径配置的前缀
*/
public static final String CLASSPATH_URL_PREFIX = "classpath:";
/**
* XML日志配置文件的后缀
*/
public static final String XML_FILE_EXTENSION = ".xml";
/**
* 起始前缀
*/
public static final String PLACEHOLDER_PREFIX = "${";
/**
* 结尾后缀
*/
public static final String PLACEHOLDER_SUFFIX = "}";
/**
* URL标识的文件前缀
*/
public static final String URL_PROTOCOL_FILE = "file";
/**
* log4j.xml的路径
*/
private static String log4jPath;
/**
* 系统启动时静态加载 log4j配置文件
* @param location 加载log4j配置文件的路径
* @exception throws [FileNotFoundException ] [文件未被找到]
*/
public static void initLogging(String location)
throws FileNotFoundException
{
// 设置log4j的绝对路径
log4jPath = location;
String resolvedLocation = resolvePlaceholders(location);
URL url = getURL(resolvedLocation);
if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION))
{
DOMConfigurator.configure(url);
}
else
{
PropertyConfigurator.configure(url);
}
}
/**
* 当log4j配置文件发生改变时会重新加载
* @param location 加载log4j配置文件的路径
* @param refreshInterval 间隔刷新时间
* @exception throws [FileNotFoundException ] [文件未被找到]
*/
public static void initLogging(String location, long refreshInterval)
throws FileNotFoundException
{
// 设置log4j的绝对路径
log4jPath = location;
String resolvedLocation = resolvePlaceholders(location);
File file = getFile(resolvedLocation);
if (!file.exists())
{
throw new FileNotFoundException("Log4j config file ["
+ resolvedLocation + "] not found");
}
if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION))
{
DOMConfigurator.configureAndWatch(file.getAbsolutePath(),
refreshInterval);
}
else
{
PropertyConfigurator.configureAndWatch(file.getAbsolutePath(),
refreshInterval);
}
}
/**
* 关闭日志记录器
*/
public static void shutdownLogging()
{
LogManager.shutdown();
}
/**
* 设置系统的工作目录
* @param key
* system property key to use, as expected in Log4j configuration
* (for example: "demo.root", used as
* "${demo.root}/WEB-INF/demo.log")
*/
public static void setWorkingDirSystemProperty(String key)
{
System.setProperty(key, new File("").getAbsolutePath());
}
/**
* 替换${},得到真实的路径参数
* @param text 要替换的文本
* @return String [替换后的文本]
*/
public static String resolvePlaceholders(String text)
{
StringBuffer buf = new StringBuffer(text);
String placeholder = null;
int nextIndex = 0;
String propVal = null;
int startIndex = buf.indexOf(PLACEHOLDER_PREFIX);
while (startIndex != -1)
{
int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex
+ PLACEHOLDER_PREFIX.length());
if (endIndex != -1)
{
placeholder = buf.substring(startIndex
+ PLACEHOLDER_PREFIX.length(), endIndex);
nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();
try
{
propVal = System.getProperty(placeholder);
if (propVal == null)
{
// Fall back to searching the system environment.
propVal = System.getenv(placeholder);
}
if (propVal != null)
{
buf.replace(startIndex, endIndex
+ PLACEHOLDER_SUFFIX.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(PLACEHOLDER_PREFIX, nextIndex);
}
else
{
startIndex = -1;
}
}
return buf.toString();
}
/**
* 根据文件的上下文路径获得URL对象
* 可以通过类路径,URL,绝对路径,相对路径来获得
* @param resourceLocation 文件的上下文路径
* @return URL [URL对象]
* @exception throws [FileNotFoundException] [文件没有被找到异常]
*/
public static URL getURL(String resourceLocation)
throws FileNotFoundException
{
if (null == resourceLocation)
{
throw new IllegalArgumentException(
"Resource location must not be null");
}
// 通过类路径classpath加载log4j得到路径
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX))
{
// 得到类的相对路径
String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
URL url = getDefaultClassLoader().getResource(path);
if (url == null)
{
String description = "class path resource [" + path + "]";
throw new FileNotFoundException(
description
+ " cannot be resolved to URL because it does not exist");
}
return url;
}
try
{
// 直接通过相对加载
return new URL(resourceLocation);
}
catch (MalformedURLException ex)
{
// no URL -> treat as file path
try
{
// 通过文件路径加载
return new File(resourceLocation).toURI().toURL();
}
catch (MalformedURLException ex2)
{
throw new FileNotFoundException("Resource location ["
+ resourceLocation
+ "] is neither a URL not a well-formed file path");
}
}
}
/**
* 根据文件的上下文路径获得文件对象
* 可以通过类路径,URL,绝对路径,相对路径来获得
* @param resourceLocation 文件的上下文路径
* @return File [文件对象]
* @exception throws [FileNotFoundException] [文件没有被找到异常]
*/
public static File getFile(String resourceLocation)
throws FileNotFoundException
{
if (null == resourceLocation)
{
throw new IllegalArgumentException(
"Resource location must not be null");
}
// 通过类路径
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX))
{
String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
String description = "class path resource [" + path + "]";
URL url = getDefaultClassLoader().getResource(path);
if (url == null)
{
throw new FileNotFoundException(description
+ " cannot be resolved to absolute file path "
+ "because it does not reside in the file system");
}
return getFile(url, description);
}
try
{
// try URL
return getFile(new URL(resourceLocation));
}
catch (MalformedURLException ex)
{
// no URL -> treat as file path
return new File(resourceLocation);
}
}
/**
* 根据URL获得具体的文件
* @param resourceUrl 文件的URL路径
* @return File [文件对象]
* @exception throws [FileNotFoundException] [文件没有被找到异常]
*/
public static File getFile(URL resourceUrl) throws FileNotFoundException
{
return getFile(resourceUrl, "URL");
}
/**
* 根据URL获得具体的文件
* @param resourceUrl 文件的URL路径
* @param description 文件描述
* @return File [文件对象]
* @exception throws [FileNotFoundException] [文件没有被找到异常]
*/
public static File getFile(URL resourceUrl, String description)
throws FileNotFoundException
{
// Assert.notNull(resourceUrl, "Resource URL must not be null");
if (null == resourceUrl)
{
throw new IllegalArgumentException("Resource URL must not be null");
}
if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol()))
{
throw new FileNotFoundException(description
+ " cannot be resolved to absolute file path "
+ "because it does not reside in the file system: "
+ resourceUrl);
}
try
{
return new File(toURI(resourceUrl).getSchemeSpecificPart());
}
catch (URISyntaxException ex)
{
// Fallback for URLs that are not valid URIs (should hardly ever
// happen).
return new File(resourceUrl.getFile());
}
}
/**
* 根据URI获得具体的文件
* @param resourceUri 文件的URI路径
* @return File [文件对象]
* @exception throws [FileNotFoundException] [文件没有被找到异常]
*/
public static File getFile(URI resourceUri) throws FileNotFoundException
{
return getFile(resourceUri, "URI");
}
/**
* 根据URI获得具体的文件
* @param resourceUri 文件的URI路径
* @param description 文件描述
* @return File [文件对象]
* @exception throws [FileNotFoundException] [文件没有被找到异常]
*/
public static File getFile(URI resourceUri, String description)
throws FileNotFoundException
{
// Assert.notNull(resourceUri, "Resource URI must not be null");
if (null == resourceUri)
{
throw new IllegalArgumentException("Resource URI must not be null");
}
if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme()))
{
throw new FileNotFoundException(description
+ " cannot be resolved to absolute file path "
+ "because it does not reside in the file system: "
+ resourceUri);
}
return new File(resourceUri.getSchemeSpecificPart());
}
/**
* 将URL转换成URI对象
* @param url url对象
* @return URI [URI对象]
* @exception throws [URISyntaxException ] [URI转换异常]
*/
public static URI toURI(URL url) throws URISyntaxException
{
return toURI(url.toString());
}
/**
* 根据文件路径获得URI对象
* @param location 文件路径
* @return URI [URI路径]
* @exception throws [URISyntaxException] [URI转换异常]
*/
public static URI toURI(String location) throws URISyntaxException
{
// 进行路径中的空格替换
return new URI(replace(location, " ", "%20"));
}
/**
* 获得类装载器
* @return ClassLoader [类装载器]
*/
public static ClassLoader getDefaultClassLoader()
{
ClassLoader cl = null;
try
{
cl = Thread.currentThread().getContextClassLoader();
}
catch (Throwable ex)
{
// Cannot access thread context ClassLoader - falling back to system
// class loader...
}
if (cl == null)
{
// No thread context class loader -> use class loader of this class.
cl = Log4jConfigurer.class.getClassLoader();
}
return cl;
}
/**
* 字符串替换
* @param inString 要替换的字符串
* @param oldPattern 替换前的字符
* @param newPattern 替换后的字符
* @return String [替换后的字符串]
*/
public static String replace(String inString, String oldPattern,
String newPattern)
{
if (!hasLength(inString) || !hasLength(oldPattern)
|| newPattern == null)
{
return inString;
}
StringBuffer sbuf = new StringBuffer();
// output StringBuffer we‘ll build up
int pos = 0; // our position in the old string
int index = inString.indexOf(oldPattern);
// the index of an occurrence we‘ve found, or -1
int patLen = oldPattern.length();
while (index >= 0)
{
sbuf.append(inString.substring(pos, index));
sbuf.append(newPattern);
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
}
sbuf.append(inString.substring(pos));
// remember to append any characters to the right of a match
return sbuf.toString();
}
/**
* 判断字符串是否有长度
* @param str 字符串String
* @return boolean [true-有 false-没有]
*/
public static boolean hasLength(String str)
{
return hasLength((CharSequence) str);
}
/**
* 判断字符串是否有长度
* @param str CharSequence字符序列
* @return boolean [true-有 false-没有]
*/
public static boolean hasLength(CharSequence str)
{
return (str != null && str.length() > 0);
}
/**
* @return 返回 log4jPath
*/
public static String getLog4jPath()
{
return log4jPath;
}
public static void main(String[] args)
{
System.out.println(getRootPath("D:/aaaa////////////tree.txt/aaa", true));
}
public static String getRootPath(String curretpath, boolean isFile)
{
if (null == curretpath || "".equals(curretpath))
{
return curretpath;
}
File f = new File(curretpath);
curretpath = f.getPath();
int tmp = 0;
StringBuffer buf = new StringBuffer();
while ((tmp = curretpath.indexOf(File.separator, tmp)) != -1)
{
tmp++;
if (isFile)
{
isFile = false;
continue;
}
buf.append("..").append("/");
}
return buf.toString();
}
}
package com.companyName.dhm.common.config.impl;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
import com.companyName.dhm.common.config.base.DataBaseConfig;
/**
* ConfigFactory.java
* <p>Copyright: Copyright (c) 2009 <p>
* <p>Company: companyName</p>
* @author
* @version 1.0
*/
public class ConfigFactory {
private static Logger log = Logger.getLogger(ConfigFactory.class);
public ConfigFactory() {
}
/**
* 初始化配置
* @param path:sysConfig.xml的路径
*/
public void initConfig(String confPath, String file) {
String FS = System.getProperty("file.separator");
if (file == null) {
log.error("配置文件SysConfig.xml路径地址尚未初始化,请查看web.xml文件");
return;
}
XMLConfiguration config = null;
try {
config = new XMLConfiguration(confPath + FS + file);
} catch (ConfigurationException e) {
log.error("加载配置文件 SysConfig.xml 发生错误,请查看文件是否存在,或格式是否错误");
return;
}
List<String> proList = config.getList("properties.filepath");
for (String pPath : proList) {
pPath = confPath + FS + pPath;
log.debug("开始加载配置文件 path:" + pPath);
PropertiesFactory.addConfiguration(pPath);
}
List<String> xmlList = config.getList("xml.filepath");
for (String xPath : xmlList) {
xPath = confPath + FS + xPath;
log.debug("开始加载配置文件 path:" + xPath);
XMLFactory.addConfiguration(xPath);
}
if (config.getString("data.dataConn.driverName") != null
&& config.getString("data.dataConn.jdbcUrl") != null
&& config.getString("data.dataConn.userName") != null
&& config.getString("data.dataConn.passWd") != null
&& config.getString("data.table.tableName") != null
&& config.getString("data.table.key") != null
&& config.getString("data.table.value") != null) {
log.debug("开始加载数据库配置信息");
//初始化参数
DataFactory.setParameters(config.getString("data.dataConn.driverName"),
config.getString("data.dataConn.jdbcUrl"), config
.getString("data.dataConn.userName"), config
.getString("data.dataConn.passWd"), config
.getString("data.table.tableName"), config
.getString("data.table.type"), config
.getString("data.table.key"), config
.getString("data.table.value"));
}
}
}
package com.companyName.dhm.common.config.impl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
import com.companyName.dhm.common.config.base.CompositeConfig;
import com.companyName.dhm.common.util.StringUtil;
/
以上是关于服务启动初始化相关配置 如XMLpropertieslog等文件的主要内容,如果未能解决你的问题,请参考以下文章