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.StringWriter;
010: import java.util.HashMap;
011: import java.util.Map;
012:
013: import org.apache.velocity.VelocityContext;
014: import org.apache.velocity.app.VelocityEngine;
015: import org.apache.velocity.app.event.EventCartridge;
016: import org.apache.velocity.app.event.EventHandler;
017:
018: /**
019: * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
020: */
021: public class VelocityUtils {
022:
023: private static VelocityEngine ve = new VelocityEngine();
024:
025: static {
026: /* first, we init the runtime engine. Defaults are fine. */
027:
028: try {
029:
030: /*
031: * configure the engine. In this case, we are using
032: * ourselves as a logger (see logging examples..)
033: */
034:
035: // ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
036: /*
037: * initialize the engine
038: */
039:
040: ve.init();
041: } catch (Exception e) {
042: throw new RuntimeException(
043: "Problem initializing Velocity : " + e);
044: }
045: }
046:
047: private VelocityUtils() {
048: }
049:
050: /**
051: * 替� placeholder
052: *
053: * @param template 输入的模版
054: * @param mapContext map context
055: * @return 替�之�的内容
056: */
057: public static String evaluate(String template,
058: Map<String, Object> mapContext) {
059: VelocityContext context = new VelocityContext();
060: for (Map.Entry entry : mapContext.entrySet()) {
061: context.put((String) entry.getKey(), entry.getValue());
062: }
063:
064: return evaluate(template, context);
065: }
066:
067: public static String evaluate(String template,
068: VelocityContext context) {
069:
070: try {
071: StringWriter sw = new StringWriter();
072: ve.evaluate(context, sw, VelocityUtils.class
073: .getSimpleName(), template);
074: return sw.toString();
075: } catch (Exception pee) {
076: pee.printStackTrace();
077: return template;
078: }
079: }
080:
081: public static String evaluate(String template,
082: Map<String, Object> mapContext,
083: EventHandler... eventHandlers) {
084: VelocityContext context = new VelocityContext();
085: for (Map.Entry entry : mapContext.entrySet()) {
086: context.put((String) entry.getKey(), entry.getValue());
087: }
088: EventCartridge ec = new EventCartridge();
089:
090: for (EventHandler eventHandler : eventHandlers) {
091: ec.addEventHandler(eventHandler);
092: }
093: ec.attachToContext(context);
094: return evaluate(template, context);
095: }
096:
097: public static void main(String[] args) {
098: Map<String, Object> map = new HashMap<String, Object>();
099: map.put("time", System.currentTimeMillis());
100: String out = VelocityUtils.evaluate(
101: "Hello, World! time is: $time", map);
102: System.out.println(out);
103: }
104: }
|