From b12839560b407e92b188b934fbfd9aeb2c876f97 Mon Sep 17 00:00:00 2001 From: mdb Date: Thu, 25 Nov 2004 00:07:16 +0000 Subject: [PATCH] A utility for creating a VelocityEngine that's all set up to be used from within a tool in a sensible manner (loading templates from the classpath, not logging boatloads of informational messages, not complaining about a non-existent "macro library"). git-svn-id: https://samskivert.googlecode.com/svn/trunk@1530 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../com/samskivert/velocity/VelocityUtil.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 projects/samskivert/src/java/com/samskivert/velocity/VelocityUtil.java diff --git a/projects/samskivert/src/java/com/samskivert/velocity/VelocityUtil.java b/projects/samskivert/src/java/com/samskivert/velocity/VelocityUtil.java new file mode 100644 index 00000000..c76bf596 --- /dev/null +++ b/projects/samskivert/src/java/com/samskivert/velocity/VelocityUtil.java @@ -0,0 +1,57 @@ +// +// $Id$ + +package com.samskivert.velocity; + +import java.util.Properties; + +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.runtime.RuntimeServices; +import org.apache.velocity.runtime.log.LogSystem; +import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; + +/** + * Handy Velocity-related routines. + */ +public class VelocityUtil +{ + /** + * Creates a {@link VelocityEngine} that is configured to load + * templates from the classpath and log using the samskivert logging + * classes and not complain about a bunch of pointless stuff that it + * generally complains about. + * + * @throws Exception if a problem occurs initializing Velocity. We'd + * throw something less generic, but that's what + * {@link VelocityEngine#init} throws. + */ + public VelocityEngine createEngine () + throws Exception + { + // initialize velocity which we'll use for templating + Properties props = new Properties(); + props.put(VelocityEngine.VM_LIBRARY, ""); + props.put(VelocityEngine.RESOURCE_LOADER, "classpath"); + props.put("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", + ClasspathResourceLoader.class.getName()); + VelocityEngine velocity = new VelocityEngine(); + velocity.init(props); + velocity.setProperty( + VelocityEngine.RUNTIME_LOG_LOGSYSTEM, _logger); + return velocity; + } + + /** Handles logging for Velocity. */ + protected static LogSystem _logger = new LogSystem() { + public void init (RuntimeServices rs) { + // nothing doing + } + public void logVelocityMessage (int level, String message) { + // skip anything other than warnings or errors + if (level == WARN_ID || level == ERROR_ID) { + System.err.println(message); + } + } + }; +}