码迷,mamicode.com
首页 > 其他好文 > 详细

服务启动初始化相关配置 如XML、properties、log等文件

时间:2016-03-31 11:05:38      阅读:493      评论:0      收藏:0      [点我收藏+]

标签:

服务启动初始化相关配置 如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;

/**
 * XMLFactory.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company: companyName</p>
 *  @author    
 *  @version   1.0
 */
public class XMLFactory {

    private static Logger log = Logger.getLogger(XMLFactory.class);
    private final static CompositeConfig config = new CompositeConfig();
    private static boolean initFlag = false;
    
    private XMLFactory() {

    }

    /**
     * 增加新的配置文件信息
     * @param path 配置文件地址
     */
    public synchronized static void addConfiguration(String path) {
        initFlag = true;
        try {
            XMLConfiguration configuration= new XMLConfiguration(path);
            configuration.setEncoding("UTF-8");
            config.addConfiguration(configuration);
        } catch (ConfigurationException e) {
            log.error("加载配置文件 " + path + " 发生错误,请查看文件是否存在,或格式是否错误");
        }
    }

    /**
     * 获取长整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static long getValueLong(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getLong(key);
    }

    /**
     *
     * 获取迭代器
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static Iterator getKeys() {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getKeys();
    }
    
    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static int getValueInt(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getInt(key);
    }

    /**
     *
     * 获取数组类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String[] getValueArray(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getStringArray(key);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String getValueString(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getString(key);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param params 替换的参数,例如{"1","22","33"}
     * @return key的值
     */
    public static String getValueString(String key, String[] params) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return StringUtil.substituteParams(config.getString(key), params);
    }
    
    /**
     *
     * 获取双精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static double getValueDouble(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getDouble(key);
    }

    /**
     * 获取高精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static BigDecimal getValueBigDecimal(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBigDecimal(key);
    }

    /**
     * 获取浮点数字类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static float getValueFloat(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getFloat(key);
    }

    /**
     * 获取布尔类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static boolean getValueBoolean(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBoolean(key);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static BigInteger getValueBigInteger(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBigInteger(key);
    }

    /**
     * 获取List类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static List getValueList(String key) {
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getList(key);
    }

    /**
     * 清除配置文件中所有的key和其值
     */
    public static void clear() {
        if (config != null) {
            config.clear();
            initFlag = false;
        }
    }
    
    /**
     * 保存相应的值,该值存在进行修改,不存在不处理
     * @param key 需要保存的KEY
     * @param value 需要保存的值
     */
    public static void setProperty(String key,String value){
        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        config.setPropertyXML(key, value);
    }
}


package com.companyName.dhm.common.config.base;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import org.apache.commons.configuration.*;
import org.apache.log4j.Logger;

/**
 * CompositeConfig.java
 * <p>Copyright: Copyright (c) 2009<p>
 * <p>Company: companyName</p>
 * @author
 * @version 1.0
 */
public class CompositeConfig extends AbstractConfiguration implements Cloneable {
    
    private static Logger logger = Logger.getLogger(CompositeConfig.class);
    /** 配置列表 */
    private List configList = new LinkedList();

    /**
     * 保存配置的对象. 第一次调用新增方法时override父类的新增
     */
    private Configuration inMemoryConfiguration;

    /**
     * 构造函数
     */
    public CompositeConfig() {

        clear();
    }

    /**
     * 新增配置项资源文件
     *
     * @param config
     *        the configuration to add
     */
    public void addConfiguration(Configuration config) {

        if (!configList.contains(config)) {
            // As the inMemoryConfiguration contains all manually added keys,
            // we must make sure that it is always last. "Normal", non composed
            // configuration add their keys at the end of the configuration and
            // we want to mimic this behaviour.
            configList.add(configList.indexOf(inMemoryConfiguration), config);

            if (config instanceof AbstractConfiguration) {
                ((AbstractConfiguration) config)
                        .setThrowExceptionOnMissing(isThrowExceptionOnMissing());
            }
        }
    }

    /**
     * 删除配置项
     * @param config
     */
    public void removeConfiguration(Configuration config) {

        // Make sure that you can‘t remove the inMemoryConfiguration from
        // the CompositeConfiguration object
        if (!config.equals(inMemoryConfiguration)) {
            configList.remove(config);
        }
    }

    /**
     * 获取当前加载的配置数量
     *
     * @return the number of configuration
     */
    public int getNumberOfConfigurations() {

        return configList.size();
    }

    /**
     * 清空所有已加载到内存中的配置信息
     */
    public void clear() {

        configList.clear();
        // recreate the in memory configuration
        inMemoryConfiguration = new BaseConfiguration();
        ((BaseConfiguration) inMemoryConfiguration)
                .setThrowExceptionOnMissing(isThrowExceptionOnMissing());
        ((BaseConfiguration) inMemoryConfiguration).setListDelimiter(getListDelimiter());
        ((BaseConfiguration) inMemoryConfiguration)
                .setDelimiterParsingDisabled(isDelimiterParsingDisabled());
        configList.add(inMemoryConfiguration);
    }

    /**
     * 增加新的配置项
     *
     * @param key
     * @param token
     */
    protected void addPropertyDirect(String key, Object token) {

        inMemoryConfiguration.addProperty(key, token);
    }

    /**
     * 增加新的配置项,仅支持XML格式
     *
     * @param key
     * @param token
     */
    public void setPropertyXML(String key, Object obj) {

        for (Iterator i = configList.iterator(); i.hasNext();) {
            Configuration config = (Configuration) i.next();
            if (config.containsKey(key)) {
                ((XMLConfiguration) config).setProperty(key, obj);
                try {
                    ((XMLConfiguration) config).save();
                } catch (ConfigurationException e) {
                    logger.error("更新配置项 key:" + key + ";value:" + obj + " 失败");
                }
            }
        }
    }

    /**
     * 增加新的配置项,仅支持Properties格式
     *
     * @param key
     * @param token
     */
    public void setPropertyProperties(String key, Object obj) {

        for (Iterator i = configList.iterator(); i.hasNext();) {
            Configuration config = (Configuration) i.next();
            if (config.containsKey(key)) {
                ((PropertiesConfiguration) config).setProperty(key, obj);
                try {
                    ((PropertiesConfiguration) config).save();
                } catch (ConfigurationException e) {
                    logger.error("更新配置项 key:" + key + ";value:" + obj + " 失败");
                }
            }
        }
    }

    /**
     * 获取key对应的value
     *
     * @param key
     * @return value
     */
    public Object getProperty(String key) {

        Configuration firstMatchingConfiguration = null;
        for (Iterator i = configList.iterator(); i.hasNext();) {
            Configuration config = (Configuration) i.next();
            if (config.containsKey(key)) {
                firstMatchingConfiguration = config;
                break;
            }
        }

        if (firstMatchingConfiguration != null) {
            return firstMatchingConfiguration.getProperty(key);
        } else {
            return null;
        }
    }

    /**
     * 获取key对应的迭代器
     * @return Iterator
     */
    public Iterator getKeys() {

        List keys = new ArrayList();
        for (Iterator i = configList.iterator(); i.hasNext();) {
            Configuration config = (Configuration) i.next();

            Iterator j = config.getKeys();
            while (j.hasNext()) {
                String key = (String) j.next();
                if (!keys.contains(key)) {
                    keys.add(key);
                }
            }
        }

        return keys.iterator();
    }

    /**
     * 获取key对应的迭代器
     * @param key
     * @return Iterator
     */
    public Iterator getKeys(String key) {

        List keys = new ArrayList();
        for (Iterator i = configList.iterator(); i.hasNext();) {
            Configuration config = (Configuration) i.next();

            Iterator j = config.getKeys(key);
            while (j.hasNext()) {
                String newKey = (String) j.next();
                if (!keys.contains(newKey)) {
                    keys.add(newKey);
                }
            }
        }

        return keys.iterator();
    }

    /**
     * 校验列表是否为空
     * @param key
     * @return boolean
     */
    public boolean isEmpty() {

        boolean isEmpty = true;
        for (Iterator i = configList.iterator(); i.hasNext();) {
            Configuration config = (Configuration) i.next();
            if (!config.isEmpty()) {
                return false;
            }
        }

        return isEmpty;
    }

    protected void clearPropertyDirect(String key) {

        for (Iterator i = configList.iterator(); i.hasNext();) {
            Configuration config = (Configuration) i.next();
            config.clearProperty(key);
        }
    }

    public boolean containsKey(String key) {

        for (Iterator i = configList.iterator(); i.hasNext();) {
            Configuration config = (Configuration) i.next();
            if (config.containsKey(key)) {
                return true;
            }
        }
        return false;
    }

    public List getList(String key, List defaultValue) {

        List list = new ArrayList();

        // add all elements from the first configuration containing the requested key
        Iterator it = configList.iterator();
        while (it.hasNext() && list.isEmpty()) {
            Configuration config = (Configuration) it.next();
            if (config != inMemoryConfiguration && config.containsKey(key)) {
                appendListProperty(list, config, key);
            }
        }

        // add all elements from the in memory configuration
        appendListProperty(list, inMemoryConfiguration, key);

        if (list.isEmpty()) {
            return defaultValue;
        }

        ListIterator lit = list.listIterator();
        while (lit.hasNext()) {
            lit.set(interpolate(lit.next()));
        }

        return list;
    }

    public String[] getStringArray(String key) {

        List list = getList(key);

        // transform property values into strings
        String[] tokens = new String[list.size()];

        for (int i = 0; i < tokens.length; i++) {
            tokens[i] = String.valueOf(list.get(i));
        }

        return tokens;
    }

    /**
     * Return the configuration at the specified index.
     *
     * @param index
     *        The index of the configuration to retrieve
     * @return the configuration at this index
     */
    public Configuration getConfiguration(int index) {

        return (Configuration) configList.get(index);
    }

    /**
     * Returns the &quot;in memory configuration&quot;. In this configuration changes are
     * stored.
     *
     * @return the in memory configuration
     */
    public Configuration getInMemoryConfiguration() {

        return inMemoryConfiguration;
    }

    /**
     * Returns a copy of this object. This implementation will create a deep clone, i.e.
     * all configurations contained in this composite will also be cloned. This only works
     * if all contained configurations support cloning; otherwise a runtime exception will
     * be thrown. Registered event handlers won‘t get cloned.
     *
     * @return the copy
     * @since 1.3
     */
    public Object clone() {

        try {
            CompositeConfig copy = (CompositeConfig) super.clone();
            copy.clearConfigurationListeners();
            copy.configList = new LinkedList();
            copy.inMemoryConfiguration = ConfigurationUtils
                    .cloneConfiguration(getInMemoryConfiguration());
            copy.configList.add(copy.inMemoryConfiguration);

            for (int i = 0; i < getNumberOfConfigurations(); i++) {
                Configuration config = getConfiguration(i);
                if (config != getInMemoryConfiguration()) {
                    copy.addConfiguration(ConfigurationUtils.cloneConfiguration(config));
                }
            }

            return copy;
        } catch (CloneNotSupportedException cnex) {
            // cannot happen
            throw new ConfigurationRuntimeException(cnex);
        }
    }

    /**
     * Sets a flag whether added values for string properties should be checked for the
     * list delimiter. This implementation ensures that the in memory configuration is
     * correctly initialized.
     *
     * @param delimiterParsingDisabled
     *        the new value of the flag
     * @since 1.4
     */
    public void setDelimiterParsingDisabled(boolean delimiterParsingDisabled) {

        ((BaseConfiguration) getInMemoryConfiguration())
                .setDelimiterParsingDisabled(delimiterParsingDisabled);
        super.setDelimiterParsingDisabled(delimiterParsingDisabled);
    }

    /**
     * Sets the character that is used as list delimiter. This implementation ensures that
     * the in memory configuration is correctly initialized.
     *
     * @param listDelimiter
     *        the new list delimiter character
     * @since 1.4
     */
    public void setListDelimiter(char listDelimiter) {

        ((BaseConfiguration) getInMemoryConfiguration()).setListDelimiter(listDelimiter);
        super.setListDelimiter(listDelimiter);
    }

    /**
     * Returns the configuration source, in which the specified key is defined. This
     * method will iterate over all existing child configurations and check whether they
     * contain the specified key. The following constellations are possible:
     * <ul>
     * <li>If exactly one child configuration contains the key, this configuration is
     * returned as the source configuration. This may be the
     * <em>in memory configuration</em> (this has to be explicitly checked by the
     * calling application).</li>
     * <li>If none of the child configurations contain the key, <b>null</b> is returned.</li>
     * <li>If the key is contained in multiple child configurations or if the key is
     * <b>null</b>, a <code>IllegalArgumentException</code> is thrown. In this case the
     * source configuration cannot be determined.</li>
     * </ul>
     *
     * @param key
     *        the key to be checked
     * @return the source configuration of this key
     * @throws IllegalArgumentException
     *         if the source configuration cannot be determined
     * @since 1.5
     */
    public Configuration getSource(String key) {

        if (key == null) {
            throw new IllegalArgumentException("Key must not be null!");
        }

        Configuration source = null;
        for (Iterator it = configList.iterator(); it.hasNext();) {
            Configuration conf = (Configuration) it.next();
            if (conf.containsKey(key)) {
                if (source != null) {
                    throw new IllegalArgumentException("The key " + key
                            + " is defined by multiple sources!");
                }
                source = conf;
            }
        }

        return source;
    }

    /**
     * Adds the value of a property to the given list. This method is used by
     * <code>getList()</code> for gathering property values from the child
     * configurations.
     *
     * @param dest
     *        the list for collecting the data
     * @param config
     *        the configuration to query
     * @param key
     *        the key of the property
     */
    private static void appendListProperty(List dest, Configuration config, String key) {

        Object value = config.getProperty(key);
        if (value != null) {
            if (value instanceof Collection) {
                dest.addAll((Collection) value);
            } else {
                dest.add(value);
            }
        }
    }
}


package com.companyName.dhm.common.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;

import com.google.gson.Gson;

public class StringUtil {

    public static String substituteParams(String msgtext, Object params[]) {
        if (params == null || msgtext == null) {
            return msgtext;
        }
        MessageFormat mf = new MessageFormat(msgtext);
        return mf.format(params);
    }

    
    //private static final String S_FORMAT_DATETIME = "%1$tF %1$tT";
    private static final String S_FORMAT_DATE = "%1$tF";
    private static final String SDF_FORMAT_DATE = "yyyy-MM-dd";
    private static final String SDF_FORMAT_MONTH = "yyyy-MM";
    
    /**
     * 上周的年份
     * @return
     */
    public static int year()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -7);
        return calendar.get(java.util.Calendar.YEAR);
    }
    
    /**
     * 上周
     * @return
     */
    public static int week()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -7);
        return calendar.get(java.util.Calendar.WEEK_OF_YEAR);
    }
    
    /**
     * 前天
     * @return
     */
    public static String startDate()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -2);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 昨天
     * @return
     */
    public static String endDate()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取昨天
     * @return
     */
    public static String beforeDay()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取上周一
     * @return
     */
    public static String beforeWeek()
    {
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        dayOfWeek = 1 - dayOfWeek; // 从周一开始
        calendar.add(Calendar.DATE, dayOfWeek - 7);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取前月
     * @return
     */
    public static String beforeMonth()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_MONTH);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 上上周一
     * @return
     */
    public static String startWeek()
    {
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        dayOfWeek = 1 - dayOfWeek; // 从周一开始
        calendar.add(Calendar.DATE, dayOfWeek - 14);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 上周日
     * @return
     */
    public static String endWeek()
    {
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        dayOfWeek = 1 - dayOfWeek; // 从周一开始
        calendar.add(Calendar.DATE, dayOfWeek - 1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 前月
     * @return
     */
    public static String startMonth()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -2);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_MONTH);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 上月
     * @return
     */
    public static String endMonth()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_MONTH);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 周的树形数据
     * @return
     */
    public static String weekTree()
    {
        List<HashMap<String,String>> weeks = new ArrayList<HashMap<String,String>>();
        String rootCode = "";
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("areaName", "全选/反选");
        map.put("areaCode", rootCode);
        weeks.add(map);
        for (int i = 1; i <= 53; i++)
        {
            map = new HashMap<String,String>();
            map.put("areaName", "第" + i + "周");
            map.put("areaCode", String.valueOf(i));
            map.put("serviceAreaCode", rootCode);
            weeks.add(map);
        }
        Gson gson = new Gson();
        //System.out.println("weekTree: " + gson.toJson(weeks));
        return gson.toJson(weeks);
    }
    
    /**
     * 初始化25周数据
     * @return
     */
    public static String weeks()
    {
        List<HashMap<String,String>> weeks = new ArrayList<HashMap<String,String>>();
        HashMap<String,String> map = new HashMap<String,String>();
        
        Calendar calendar = new GregorianCalendar();  
        calendar.setFirstDayOfWeek(Calendar.MONDAY);  
        calendar.setTime(new Date());  
        calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); // Monday
        for (int w = 0; w < 26; w++)
        {
            calendar.add(Calendar.DATE, -1);
            String weDate = String.format(S_FORMAT_DATE, calendar.getTime());
            calendar.add(Calendar.DATE, -6);
            String wsDate = String.format(S_FORMAT_DATE, calendar.getTime());
            
            map = new HashMap<String,String>();
            map.put("value", wsDate);
            map.put("text", "第" + calendar.get(Calendar.WEEK_OF_YEAR) + "周(" + wsDate + "至" + weDate + ")");
            weeks.add(map);
        }
        
        return JSONArray.fromObject(weeks).toString();
    }
    
    /**
     * 保留浮点数小数位数
     * @param d 数值
     * @param len 小数位数
     * @return
     */
    public static String doubleFormat(double d, int len)
    {
        BigDecimal b = new BigDecimal(Double.toString(d));
        return decFormat(b, len);
    }
    
    public static String decFormat(BigDecimal d, int len)
    {
        DecimalFormat df = new DecimalFormat("0.0000000000000");
        String result = df.format(d);
        int index = result.indexOf(".") + 1; // 索引从1开始
        result = result.substring(0, index + len); // 保留3位小数点
        return result;
    }
}


package com.companyName.dhm.common.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;

import com.google.gson.Gson;

public class StringUtil {

    public static String substituteParams(String msgtext, Object params[]) {
        if (params == null || msgtext == null) {
            return msgtext;
        }
        MessageFormat mf = new MessageFormat(msgtext);
        return mf.format(params);
    }

    
    //private static final String S_FORMAT_DATETIME = "%1$tF %1$tT";
    private static final String S_FORMAT_DATE = "%1$tF";
    private static final String SDF_FORMAT_DATE = "yyyy-MM-dd";
    private static final String SDF_FORMAT_MONTH = "yyyy-MM";
    
    /**
     * 上周的年份
     * @return
     */
    public static int year()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -7);
        return calendar.get(java.util.Calendar.YEAR);
    }
    
    /**
     * 上周
     * @return
     */
    public static int week()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -7);
        return calendar.get(java.util.Calendar.WEEK_OF_YEAR);
    }
    
    /**
     * 前天
     * @return
     */
    public static String startDate()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -2);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 昨天
     * @return
     */
    public static String endDate()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取昨天
     * @return
     */
    public static String beforeDay()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取上周一
     * @return
     */
    public static String beforeWeek()
    {
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        dayOfWeek = 1 - dayOfWeek; // 从周一开始
        calendar.add(Calendar.DATE, dayOfWeek - 7);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 获取前月
     * @return
     */
    public static String beforeMonth()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_MONTH);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 上上周一
     * @return
     */
    public static String startWeek()
    {
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        dayOfWeek = 1 - dayOfWeek; // 从周一开始
        calendar.add(Calendar.DATE, dayOfWeek - 14);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 上周日
     * @return
     */
    public static String endWeek()
    {
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        dayOfWeek = 1 - dayOfWeek; // 从周一开始
        calendar.add(Calendar.DATE, dayOfWeek - 1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_DATE);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 前月
     * @return
     */
    public static String startMonth()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -2);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_MONTH);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 上月
     * @return
     */
    public static String endMonth()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        SimpleDateFormat sdf = new SimpleDateFormat(SDF_FORMAT_MONTH);
        return sdf.format(calendar.getTime());
    }
    
    /**
     * 周的树形数据
     * @return
     */
    public static String weekTree()
    {
        List<HashMap<String,String>> weeks = new ArrayList<HashMap<String,String>>();
        String rootCode = "";
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("areaName", "全选/反选");
        map.put("areaCode", rootCode);
        weeks.add(map);
        for (int i = 1; i <= 53; i++)
        {
            map = new HashMap<String,String>();
            map.put("areaName", "第" + i + "周");
            map.put("areaCode", String.valueOf(i));
            map.put("serviceAreaCode", rootCode);
            weeks.add(map);
        }
        Gson gson = new Gson();
        //System.out.println("weekTree: " + gson.toJson(weeks));
        return gson.toJson(weeks);
    }
    
    /**
     * 初始化25周数据
     * @return
     */
    public static String weeks()
    {
        List<HashMap<String,String>> weeks = new ArrayList<HashMap<String,String>>();
        HashMap<String,String> map = new HashMap<String,String>();
        
        Calendar calendar = new GregorianCalendar();  
        calendar.setFirstDayOfWeek(Calendar.MONDAY);  
        calendar.setTime(new Date());  
        calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); // Monday
        for (int w = 0; w < 26; w++)
        {
            calendar.add(Calendar.DATE, -1);
            String weDate = String.format(S_FORMAT_DATE, calendar.getTime());
            calendar.add(Calendar.DATE, -6);
            String wsDate = String.format(S_FORMAT_DATE, calendar.getTime());
            
            map = new HashMap<String,String>();
            map.put("value", wsDate);
            map.put("text", "第" + calendar.get(Calendar.WEEK_OF_YEAR) + "周(" + wsDate + "至" + weDate + ")");
            weeks.add(map);
        }
        
        return JSONArray.fromObject(weeks).toString();
    }
    
    /**
     * 保留浮点数小数位数
     * @param d 数值
     * @param len 小数位数
     * @return
     */
    public static String doubleFormat(double d, int len)
    {
        BigDecimal b = new BigDecimal(Double.toString(d));
        return decFormat(b, len);
    }
    
    public static String decFormat(BigDecimal d, int len)
    {
        DecimalFormat df = new DecimalFormat("0.0000000000000");
        String result = df.format(d);
        int index = result.indexOf(".") + 1; // 索引从1开始
        result = result.substring(0, index + len); // 保留3位小数点
        return result;
    }
}

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.PropertiesConfiguration;
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;

/**
 * PropertiesFactory.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company: companyName</p>
 *  @author    903677
 *  @version   1.0
 */
public class PropertiesFactory {

    private static Logger log = Logger.getLogger(PropertiesFactory.class);
    private final static CompositeConfig config = new CompositeConfig();
    private static boolean initFlag = false;

    private PropertiesFactory() {

    }

    /**
     * 增加新的配置文件信息
     * @param path 配置文件地址
     */
    public synchronized static void addConfiguration(String path) {

        initFlag = true;
        try {
            PropertiesConfiguration configuration= new PropertiesConfiguration(path);
            configuration.setEncoding("UTF-8");
            config.addConfiguration(configuration);
        } catch (ConfigurationException e) {
            log.error("加载配置文件 " + path + " 发生错误,请查看文件是否存在,或格式是否错误");
        }
    }

    /**
     * 获取长整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static long getValueLong(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getLong(key);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static int getValueInt(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getInt(key);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String getValueString(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getString(key);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param params 替换的参数,例如{"1","22","33"}
     * @return key的值
     */
    public static String getValueString(String key, String[] params) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return StringUtil.substituteParams(config.getString(key), params);
    }

    /**
     *
     * 获取双精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static double getValueDouble(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getDouble(key);
    }
    
    /**
     *
     * 获取迭代器
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static Iterator getKeys() {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getKeys();
    }
    
    
    /**
     *
     * 获取数组类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String[] getValueArray(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getStringArray(key);
    }

    /**
     * 获取高精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static BigDecimal getValueBigDecimal(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBigDecimal(key);
    }

    /**
     * 获取浮点数字类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static float getValueFloat(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getFloat(key);
    }

    /**
     * 获取布尔类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static boolean getValueBoolean(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBoolean(key);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static BigInteger getValueBigInteger(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBigInteger(key);
    }

    /**
     * 获取List类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static List getValueList(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getList(key);
    }

    /**
     * 清除配置文件中所有的key和其值
     */
    public static void clear() {

        if (config != null) {
            config.clear();
            initFlag = false;
        }
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在不处理
     * @param key 需要保存的KEY
     * @param value 需要保存的值
     */
    public static void setProperty(String key, String value) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        config.setPropertyProperties(key, value);
    }

}

package com.companyName.dhm.common.config.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.configuration.PropertyConverter;
import org.apache.log4j.Logger;

import com.companyName.dhm.common.config.base.DataBaseConfig;
import com.companyName.dhm.common.util.StringUtil;

/**
 * DataFactory.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company: companyName</p>
 *  @author    903677
 *  @version   1.0
 */
public class DataFactory {

    private static Logger log = Logger.getLogger(DataFactory.class);
    
    private final static DataBaseConfig config = new DataBaseConfig();
    private static boolean initFlag = false;

    private DataFactory() {

    }

    /**
     * 设置数据库相应参数
     * @param sDriver_Name 数据库驱名
     * @param jdbc_url 数据库URL
     * @param userName 数据库登录用户名
     * @param passwd 数据库登录密码
     * @param table 配置表表名
     * @param typeColumn 配置表类型字段
     * @param keyColumn 配置表KEY字段
     * @param valueColumn 配置表VALUE字段
     */
    public static void setParameters(String sDriver_Name, String jdbc_url,
            String userName, String passwd, String table, String typeColumn,
            String keyColumn, String valueColumn) {

        initFlag = true;
        config.setParameters(sDriver_Name, jdbc_url, userName, passwd, table, typeColumn,
                keyColumn, valueColumn);
    }

    /**
     * 获取长整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static long getValueLong(String key) {

        return getValueLong(key, null);
    }

    /**
     * 获取长整型类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static long getValueLong(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Long.parseLong(config.getProperty(key, type));
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static int getValueInt(String key) {

        return getValueInt(key, null);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static int getValueInt(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Integer.parseInt(config.getProperty(key, type));
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String getValueString(String key) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getProperty(key, null);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static String getValueString(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getProperty(key, type);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @param params 替换的参数,例如{"1","22","33"}
     * @return key的值
     */
    public static String getValueString(String key, String type, String[] params) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return StringUtil.substituteParams(config.getProperty(key, type), params);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param params 替换的参数,例如{"1","22","33"}
     * @return key的值
     */
    public static String getValueString(String key, String[] params) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return StringUtil.substituteParams(config.getProperty(key), params);
    }

    /**
     * 获取双精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static double getValueDouble(String key) {

        return getValueDouble(key, null);
    }

    /**
     *
     * 获取双精度数字类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static double getValueDouble(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Double.parseDouble(config.getProperty(key, type));
    }

    /**
     * 获取高精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static BigDecimal getValueBigDecimal(String key) {

        return getValueBigDecimal(key, null);
    }

    /**
     * 获取高精度数字类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static BigDecimal getValueBigDecimal(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return PropertyConverter.toBigDecimal(config.getProperty(key, type));
    }

    /**
     * 获取浮点数字类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static float getValueFloat(String key) {

        return getValueFloat(key, null);
    }

    /**
     * 获取浮点数字类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key对应的Value
     */
    public static float getValueFloat(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Float.parseFloat(config.getProperty(key, type));
    }

    /**
     * 获取布尔类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static boolean getValueBoolean(String key) {

        return getValueBoolean(key, null);
    }

    /**
     * 获取布尔类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key对应的Value
     */
    public static boolean getValueBoolean(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Boolean.parseBoolean(config.getProperty(key, type));
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static BigInteger getValueBigInteger(String key) {

        return getValueBigInteger(key, null);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key对应的Value
     */
    public static BigInteger getValueBigInteger(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return PropertyConverter.toBigInteger(config.getProperty(key, type));
    }

    /**
     * 获取List类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static List getValueList(String key) {

        return getValueList(key, null);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key对应的Value
     */
    public static List getValueList(String key, String type) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        List list = new ArrayList();
        list.add(config.getProperty(key, type));
        return list;
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在,进行新增
     *
     * @param key 需要保存的KEY
     * @param value 需要保存的值
     */
    public static void setProperty(String key, String value) {

        setProperty(key, null, value);
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在,进行新增
     *
     * @param key 需要保存的KEY
     * @param type 所取值的类型
     * @param value 需要保存的值
     */
    public static void setProperty(String key, String type, String value) {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
            return;
        }
        config.addProperty(key, type, value);
    }

    /**
     * 刷新该资源配置
     */
    public static void reSet() {

        if (!initFlag) {
            log.error("资源配置尚未初始化,或者资源文件不存在");
            return;
        }
        config.reSet();
    }
}

package com.companyName.dhm.common.config.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Iterator;

import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.log4j.Logger;

/**
 * DataBaseConfig.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company: companyName</p>
 *  @author    903677
 *  @version   1.0
 */
public class DataBaseConfig extends AbstractConfiguration {
    
    private static Logger logger = Logger.getLogger(DataBaseConfig.class);
    /**
     * 用户存放数据库相关信息
     */
    private String DB_PARAM[] = { "driverName", "jdbcUrl", "userName", "passWd" };
    /**
     * 配置表表名
     */
    private String table;
    /**
     * 配置表类型字段
     */
    private String typeColumn;
    /**
     * 配置表KEY字段
     */
    private String keyColumn;
    /**
     * 配置表VALUE字段
     */
    private String valueColumn;

    /**
     * 用于存放配置项的集合
     */
    private Hashtable<String, String> tab = null;

    /**
     * @param sDriver_Name 数据库驱名
     * @param jdbc_url 数据库URL
     * @param userName 数据库登录用户名
     * @param passwd 数据库登录密码
     * @param table 配置表表名
     * @param typeColumn 配置表类型字段
     * @param keyColumn 配置表KEY字段
     * @param valueColumn 配置表VALUE字段
     */
    public void setParameters(String sDriver_Name, String jdbc_url, String userName,
            String passwd, String table, String typeColumn, String keyColumn,
            String valueColumn) {

        this.DB_PARAM[0] = sDriver_Name;
        this.DB_PARAM[1] = jdbc_url;
        this.DB_PARAM[2] = userName;
        this.DB_PARAM[3] = passwd;
        this.table = table;
        this.typeColumn = typeColumn;
        this.keyColumn = keyColumn;
        this.valueColumn = valueColumn;
        readConfig();
    }

    /**
     * 根据key获取相应的value
     * @param key
     * @return key对应的value
     */
    public String getProperty(String key) {

        return this.getProperty(key, null);
    }

    /**
     * 根据key,type获取相应的value
     * @param key
     * @param type
     * @return 相应的key与type对应的value
     */
    public String getProperty(String key, String type) {

        if (tab == null) {

            logger.error("数据库资源信息尚未初始化");
            return null;
        }
        if (this.typeColumn == null) {
            return tab.get(key);
        } else {
            return tab.get(type + "|" + key);
        }
    }

    /**
     * @return
     */
    public boolean isEmpty() {

        return tab == null;
    }

    /**
     * @param key
     * @return 该key在配置中是否存在,存在返回true,不存在返回false
     */
    public boolean containsKey(String key) {

        return this.containsKey(key, null);
    }

    /**
     * @param key
     * @param type
     * @return 该key在配置中对应的type类型中是否存在,存在返回true,不存在返回false
     */
    public boolean containsKey(String key, String type) {

        if (tab == null) {
            return false;
        }
        if (this.typeColumn == null) {
            return tab.containsKey(key);
        } else {
            return tab.containsKey(type + "|" + key);
        }
    }

    /**
     * 清除缓存中的数据
     */
    public void reSet() {

        clear();
        readConfig();
    }

    /**
     * 清除缓存中的数据
     */
    public void clear() {

        if (tab != null) {
            tab.clear();
            tab = null;
        }
    }

    /**
     * @return
     */
    public Iterator getKeys() {

        return null;
    }

    @Override
    protected void addPropertyDirect(String arg0, Object arg1) {

    }

    /**
     * 保存相应的值,该值存在进行修改,不存在,进行新增
     *
     * @param key 需要保存的KEY
     * @param value 需要保存的值
     */
    public void addProperty(String key, String value) {

        addProperty(key, null, value);
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在,进行新增
     *
     * @param key 需要保存的KEY
     * @param type 需要保存的KEY对应的类型
     * @param value 需要保存的值
     */
    public synchronized void addProperty(String key, String type, String value) {

        if (tab == null) {

            logger.error("修改配置失败:资源配置尚未初始化!");
            return;
        }
        // 重新获取配置,已防缓存中的配置陈旧
        reSet();
        if (this.typeColumn == null) {
            if (tab.containsKey(key)) {
                updateProperty(key, null, value);
            } else {
                insertProperty(key, null, value);
            }
        } else {
            if (type == null) {

                logger.error("修改配置失败:在key与type为联合主键的模式下type不能为空");
                return;
            }
            if (tab.containsKey(type + "|" + key)) {
                updateProperty(key, type, value);
            } else {
                insertProperty(key, type, value);
            }
        }
    }

    /**
     * 将新增配置项添加到数据库中
     * @param key 需要保存的KEY
     * @param type 需要保存的KEY对应的类型
     * @param value 需要保存的值
     */
    private void insertProperty(String key, String type, String value) {

        StringBuffer query = new StringBuffer("INSERT INTO " + this.table);
        if (this.typeColumn != null) {
            query.append(" (" + this.typeColumn + ", " + this.keyColumn + ", "
                    + this.valueColumn + ") VALUES (?, ?, ?)");
        } else {
            query.append(" (" + this.keyColumn + ", " + this.valueColumn
                    + ") VALUES (?, ?)");
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = getConnection();

            logger.debug(" insertProperty query :" + query.toString());
            pstmt = conn.prepareStatement(query.toString());
            int index = 1;
            if (this.typeColumn != null) {
                pstmt.setString(index++, type);
            }
            pstmt.setString(index++, key);
            pstmt.setString(index++, value);
            // 将新增项加入到数据库中
            pstmt.executeUpdate();

            // 将新增项加入到缓存中
            if (this.typeColumn == null) {
                tab.put(key, value);
            } else {
                tab.put(type + "|" + key, value);
            }
        } catch (SQLException e) {

            logger.error("新增配置失败:key:" + key + ";type:" + type + ";value:" + value);
        } finally {
            close(conn, pstmt, null);
        }
    }

    /**
     * 修改已有配置项的value
     *
     * @param key 需要保存的KEY
     * @param type 需要保存的KEY对应的类型
     * @param value 需要保存的值
     */
    private void updateProperty(String key, String type, String value) {

        StringBuffer query = new StringBuffer("UPDATE " + this.table + " SET ");
        if (this.typeColumn == null) {
            query.append(this.valueColumn + " = ? WHERE " + this.keyColumn + " = ? ");
        } else {
            query.append(this.valueColumn + " = ? WHERE " + this.keyColumn + " = ? AND "
                    + this.typeColumn + " = ? ");
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = getConnection();

            logger.debug(" updateProperty query :" + query.toString());
            pstmt = conn.prepareStatement(query.toString());
            int index = 1;
            pstmt.setString(index++, value);
            pstmt.setString(index++, key);
            if (this.typeColumn != null) {
                pstmt.setString(index++, type);
            }
            // 将修改项更新到数据库中
            pstmt.executeUpdate();

            // 将修改项更新到缓存中
            if (this.typeColumn == null) {
                tab.put(key, value);
            } else {
                tab.put(type + "|" + key, value);
            }
        } catch (SQLException e) {

            logger.error("修改配置失败:key:" + key + ";type:" + type + ";value:" + value);
        } finally {
            close(conn, pstmt, null);
        }
    }

    /**
     * 读取配置表,加载到本地缓存
     */
    private void readConfig() {

        if (this.tab == null) {
            this.tab = new Hashtable<String, String>();
        }

        // 生成查询语句
        StringBuffer query = null;
        if (this.typeColumn == null) {
            // 以keyColumn为主键时
            query = new StringBuffer("SELECT " + this.keyColumn + "," + this.valueColumn
                    + " FROM " + this.table);
        } else {
            // 以keyColumn与typeColumn为共同主键时
            query = new StringBuffer("SELECT " + this.typeColumn + "," + this.keyColumn
                    + "," + this.valueColumn + " FROM " + this.table);
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            
            logger.debug(" readConfig sql :" + query.toString());
            pstmt = conn.prepareStatement(query.toString());
            rs = pstmt.executeQuery();
            while (rs.next()) {
                if (this.typeColumn == null) {
                    // 以keyColumn为主键时
                    this.tab.put(rs.getString(1), rs.getString(2));
                } else {
                    // 以keyColumn与typeColumn为共同主键时
                    this.tab
                            .put(rs.getString(1) + "|" + rs.getString(2), rs.getString(3));
                }
            }
        } catch (SQLException e) {

            logger.error("加载配置信息失败");
        } finally {
            close(conn, pstmt, rs);
        }
    }

    /**
     * 获取数据库连接
     * @return 数据库连接
     */
    private synchronized Connection getConnection() {

        Connection con = null;
        try {
            Class.forName(this.DB_PARAM[0]);
        } catch (Exception e) {

            logger.error("加载数据库驱动信息异常 ");
        }
        try {
            con = DriverManager.getConnection(this.DB_PARAM[1], this.DB_PARAM[2],
                    this.DB_PARAM[3]);
        } catch (SQLException e) {

            logger.error("始初化数据库连接信息异常 ");
        }
        return con;
    }

    /**
     * 关闭相关数据库连接资源
     * @param conn
     * @param stmt
     */
    private void close(Connection conn, Statement stmt, ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
        }

        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
        }

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
        }
    }

}

服务启动初始化相关配置 如XML、properties、log等文件

标签:

原文地址:http://blog.csdn.net/chenkeqin_2012/article/details/51020314

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!