001: package com.avaje.util.codegen;
002:
003: import java.io.Writer;
004: import java.util.Map;
005: import java.util.Properties;
006: import java.util.logging.Logger;
007:
008: import org.apache.velocity.Template;
009: import org.apache.velocity.VelocityContext;
010: import org.apache.velocity.runtime.RuntimeSingleton;
011:
012: import com.avaje.lib.SystemProperties;
013: import com.avaje.lib.log.LogFactory;
014: import com.avaje.lib.util.NotFoundException;
015:
016: /**
017: * Singleton wrapper around Velocity functionality.
018: * <p>
019: * Provides a single point for using Velocity.
020: * </p>
021: */
022: public class TemplateManager {
023:
024: private static final Logger logger = LogFactory
025: .get(TemplateManager.class);
026:
027: /**
028: * The default encoding to use if none is specified.
029: */
030: private String defaultEncoding;
031:
032: /**
033: * Initialise Velocity
034: */
035: public TemplateManager() {
036: try {
037: logger.info("VelocityManager initialising");
038:
039: defaultEncoding = SystemProperties.getProperty(
040: "velocity.encoding", "UTF-8");
041:
042: Map sysprops = SystemProperties.getMap();
043: Properties p = new Properties();
044:
045: // default to using the PreparseLoader
046: p.put(RuntimeSingleton.RESOURCE_LOADER, "file");
047: //p.put("file.resource.loader.class",PreparseLoader.class.getName());
048:
049: // default the encoding
050: p.put(RuntimeSingleton.ENCODING_DEFAULT, defaultEncoding);
051:
052: // override any properties from system.properties
053: p.putAll(sysprops);
054:
055: //p.put("file.resource.loader.cache","false");
056:
057: // initialise velocity
058: RuntimeSingleton.init(p);
059:
060: } catch (Exception ex) {
061: throw new RuntimeException(ex);
062: }
063: }
064:
065: public String getDefaultEncoding() {
066: return defaultEncoding;
067: }
068:
069: /**
070: * Merge the velocity template using the default encoding.
071: */
072: public void merge(String templateName, VelocityContext context,
073: Writer writer) {
074:
075: mergeTemplate(templateName, defaultEncoding, context, writer);
076: }
077:
078: private void mergeTemplate(String templateName, String encoding,
079: VelocityContext context, Writer writer) {
080:
081: try {
082:
083: Template template = getTemplate(templateName, encoding);
084: template.merge(context, writer);
085:
086: } catch (Exception ex) {
087: throw new RuntimeException(ex);
088: }
089: }
090:
091: private Template getTemplate(String templateName, String encoding)
092: throws NotFoundException {
093: try {
094: return RuntimeSingleton.getTemplate(templateName, encoding);
095:
096: } catch (NotFoundException e) {
097: throw e;
098: } catch (Exception e) {
099: throw new RuntimeException(e);
100: }
101: }
102:
103: }
|