001: /*
002: * JFox - The most lightweight Java EE Application Server!
003: * more details please visit http://www.huihoo.org/jfox or http://www.jfox.org.cn.
004: *
005: * JFox is licenced and re-distributable under GNU LGPL.
006: */
007: package org.jfox.util;
008:
009: import java.io.FileNotFoundException;
010: import java.io.IOException;
011: import java.io.InputStream;
012: import java.net.URL;
013: import java.util.ArrayList;
014: import java.util.List;
015: import java.util.Map;
016: import java.util.Properties;
017:
018: import org.apache.log4j.Logger;
019:
020: /**
021: * å? ä½?符替æ?¢å·¥å…·ç±»
022: *
023: * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
024: */
025: public class PlaceholderUtils {
026:
027: private static final Logger logger = Logger
028: .getLogger(PlaceholderUtils.class);
029:
030: /**
031: * 全局属性
032: */
033: private Properties globalProperties = new Properties();
034:
035: private static List<String> loadedProperties = new ArrayList<String>();
036:
037: private static final PlaceholderUtils instance = new PlaceholderUtils();
038:
039: private PlaceholderUtils() {
040: }
041:
042: private void loadProperties(Properties prop) {
043: globalProperties.putAll(prop);
044: }
045:
046: public static PlaceholderUtils getInstance() {
047: return instance;
048: }
049:
050: /**
051: * 装载一个全局�置文件
052: *
053: * @param filename properties file name
054: * @return PlaceHolderUtil
055: * @throws IOException if failed to load property file
056: */
057: public static PlaceholderUtils loadGlobalProperty(String filename)
058: throws IOException {
059: if (!loadedProperties.contains(filename)) {
060: InputStream in = PlaceholderUtils.class.getClassLoader()
061: .getResourceAsStream(filename);
062: if (in != null) {
063: Properties prop = new Properties();
064: prop.load(in);
065: in.close();
066: instance.loadProperties(prop);
067: loadedProperties.add(filename);
068: } else {
069: throw new FileNotFoundException(filename);
070: }
071: }
072: return instance;
073: }
074:
075: /**
076: * 替� placeholder
077: *
078: * @param template 输入的模版
079: * @return 替�之�的内容
080: */
081: public String evaluate(String template) {
082: return VelocityUtils.evaluate(template, (Map) globalProperties);
083: }
084:
085: /**
086: * 从一个文件ä¸æ›¿æ?¢ï¼Œè¿”回替æ?¢å?Žçš„文本
087: *
088: * @param url file url
089: * @return 替��的文本
090: * @throws IOException if failed to load file
091: */
092: public String evaluate(URL url) throws IOException {
093: InputStream in = url.openStream();
094: if (in != null) {
095: String content = IOUtils.toString(in);
096: in.close();
097: return evaluate(content);
098: } else {
099: return "";
100: }
101: }
102:
103: public static void main(String[] args) throws Exception {
104: PlaceholderUtils pu = loadGlobalProperty("global.properties");
105: System.out.println(pu
106: .evaluate("I use database type is ${db_type}!"));
107:
108: }
109: }
|