View Javadoc
1   /**
2    * Copyright By Grandsoft Company Limited.  
3    * 2012-3-6 上午10:52:06
4    */
5   package gboat2.base.core.util;
6   
7   import gboat2.base.core.web.BundleVelocityResourceLoader;
8   
9   import java.io.BufferedReader;
10  import java.io.InputStreamReader;
11  import java.io.StringReader;
12  import java.io.StringWriter;
13  import java.net.URL;
14  import java.util.Iterator;
15  import java.util.Map;
16  import java.util.Properties;
17  
18  import net.sf.json.JSONObject;
19  
20  import org.apache.commons.lang3.StringUtils;
21  import org.apache.velocity.VelocityContext;
22  import org.apache.velocity.app.Velocity;
23  import org.apache.velocity.runtime.RuntimeConstants;
24  import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
25  import org.apache.velocity.tools.generic.DateTool;
26  import org.apache.velocity.tools.generic.EscapeTool;
27  import org.apache.velocity.tools.generic.NumberTool;
28  
29  /**
30   * 
31   * Velocity工具,填充json字符串中的变量
32   * @author zhaic
33   * @since jdk1.6
34   * @date 2012-3-6
35   *  
36   */
37  
38  public abstract class JsonVelocityUtil {
39  	
40  	private static final String DEFAULTCHARSET = "utf-8";
41  	
42  	private static Properties velocityProperties;
43  	
44  	public static String fillJsonByVelocityfromMdStr(String metadataContent, Map<String, Object> params) {
45  		if (!StringUtils.isEmpty(metadataContent)) {
46  			
47  			metadataContent = metadataContent.replaceAll("\\/\\/.*(\\r\\n|\\n)", "").replaceAll("\\s| +", " ");//去掉注释
48  			StringReader reader = new StringReader(metadataContent);
49  			
50  			String contentStr = null;
51  			StringWriter writer = new StringWriter();
52  			VelocityContext context = new VelocityContext(params);
53  			context.put("date", new DateTool());
54  			context.put("number", new NumberTool());
55  			context.put("escape", new EscapeTool());
56  			
57  			try {
58  				ClassLoader loader = JsonVelocityUtil.class.getClassLoader();
59  				//解决和web容器lib下的velocity包冲突
60  				ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
61  				Thread.currentThread().setContextClassLoader(loader);
62  				if (velocityProperties == null) {
63  					velocityProperties = new Properties();
64  					velocityProperties.setProperty(RuntimeConstants.RESOURCE_LOADER, "class,osgi");
65  					velocityProperties.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
66  					velocityProperties.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
67  					velocityProperties.setProperty("osgi.resource.loader.description", "OSGI bundle loader");
68  					velocityProperties.setProperty("osgi.resource.loader.class", BundleVelocityResourceLoader.class.getName());
69  					velocityProperties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.Log4JLogChute");
70  					//过滤值中的javascript特殊字符
71  					velocityProperties.setProperty("eventhandler.referenceinsertion.class",EscapeJavaScriptReference.class.getName() );
72  					velocityProperties.setProperty("eventhandler.escape.javascript.match", "/^(?!\\$\\!.*?Json).*/");
73  					//velocityProperties.setProperty("eventhandler.escape.javascript.match", "/^(?!\\$\\!?attachsJson).*/");
74  					
75  					Velocity.init(velocityProperties);
76  				}
77  				writer.toString();
78  				Velocity.evaluate(context, writer, "gboat", reader);
79  				contentStr = writer.toString();
80  				
81  				Thread.currentThread().setContextClassLoader(oldLoader);
82  				return contentStr;
83  			} catch (Exception e) {
84  				e.printStackTrace();
85  			}
86  		}
87  		return null;
88  	}
89  	
90  	private JsonVelocityUtil() {
91  		super();
92  	}
93  	
94  	/**
95  	 * 读取md文件内容
96  	 * @param url 元文件url
97  	 * @return 返回页面流
98  	 */
99  	
100 	public static String getMetadataFile(URL url) {
101 		if (null != url) {
102 			StringBuffer buf = null;
103 			BufferedReader breader = null;
104 			try {
105 				breader = new BufferedReader(new InputStreamReader(url.openStream(), DEFAULTCHARSET));
106 				buf = new StringBuffer();
107 				while (breader.ready()) {
108 					buf.append((char) breader.read());
109 				}
110 				breader.close();
111 			} catch (Exception e) {
112 				e.printStackTrace();
113 			}
114 			return buf.toString();
115 		}
116 		return null;
117 	}
118 	
119 	/**
120 	 * 元数据文件继承,简单覆盖继承
121 	 * @param 父json对象,子json对象,叶子节点md文件params
122 	 * @return 继承了父json对象的子json对象
123 	 */
124 	public static JSONObject merge(JSONObject fatherObj, JSONObject sonObj) {
125 		
126 		fatherObj.remove("extends");
127 		Iterator<?> iter = sonObj.keys();
128 		while (iter.hasNext()) {
129 			String key = (String) iter.next();
130 			fatherObj.put(key, sonObj.get(key));
131 		}
132 		return fatherObj;
133 	}
134 	
135 }