Skip to content

Instantly share code, notes, and snippets.

@max747
Created May 25, 2011 08:52
Show Gist options
  • Save max747/990611 to your computer and use it in GitHub Desktop.
Save max747/990611 to your computer and use it in GitHub Desktop.
Using Velocity Tools 2.0 in SpringFramework 3.0.x
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="classpath:velocity/templates" />
<property name="velocityPropertiesMap">
<map>
<entry key="input.encoding" value="UTF-8" />
<entry key="output.encoding" value="UTF-8" />
</map>
</property>
</bean>
<bean id="velocityMerger"
class="yourdomain.yourapp.VelocityMerger"
p:engine-ref="velocityEngine"
p:toolBoxConfigLocation="/WEB-INF/config/velocity-tools.xml">
</bean>
</beans>
<tools>
<toolbox scope="application">
<tool key="date" format="yyyy/MM/dd" class="org.apache.velocity.tools.generic.DateTool" />
</toolbox>
</tools>
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package yourdomain.yourapp;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.tools.ToolManager;
/**
* Utility class for working with a VelocityEngine.
* Provides convenience methods to merge a Velocity template with a model.
*
* @author Juergen Hoeller
* @since 22.01.2004
*/
public abstract class VelocityEngineUtils {
private static final Log logger = LogFactory.getLog(VelocityEngineUtils.class);
/**
* Merge the specified Velocity template with the given model and write
* the result to the given Writer.
* @param velocityEngine VelocityEngine to work with
* @param templateLocation the location of template, relative to Velocity's
* resource loader path
* @param model the Map that contains model names as keys and model objects
* as values
* @param writer the Writer to write the result to
* @throws VelocityException if the template wasn't found or rendering failed
*/
public static void mergeTemplate(
VelocityEngine velocityEngine, String templateLocation, Map model, Writer writer, String toolboxConfigurationPath)
throws VelocityException {
try {
VelocityContext velocityContext = new VelocityContext(model, createToolboxContext(toolboxConfigurationPath));
velocityEngine.mergeTemplate(templateLocation, velocityContext, writer);
}
catch (VelocityException ex) {
throw ex;
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
logger.error("Why does VelocityEngine throw a generic checked exception, after all?", ex);
throw new VelocityException(ex.toString());
}
}
/**
* Merge the specified Velocity template with the given model and write
* the result to the given Writer.
* @param velocityEngine VelocityEngine to work with
* @param templateLocation the location of template, relative to Velocity's
* resource loader path
* @param encoding the encoding of the template file
* @param model the Map that contains model names as keys and model objects
* as values
* @param writer the Writer to write the result to
* @throws VelocityException if the template wasn't found or rendering failed
*/
public static void mergeTemplate(
VelocityEngine velocityEngine, String templateLocation, String encoding, Map model, Writer writer, String toolboxConfigurationPath)
throws VelocityException {
try {
VelocityContext velocityContext = new VelocityContext(model, createToolboxContext(toolboxConfigurationPath));
velocityEngine.mergeTemplate(templateLocation, encoding, velocityContext, writer);
}
catch (VelocityException ex) {
throw ex;
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
logger.error("Why does VelocityEngine throw a generic checked exception, after all?", ex);
throw new VelocityException(ex.toString());
}
}
private static Context createToolboxContext(String path) {
ToolManager toolManager = new ToolManager();
toolManager.configure(path);
return toolManager.createContext();
}
/**
* Merge the specified Velocity template with the given model into a String.
* <p>When using this method to prepare a text for a mail to be sent with Spring's
* mail support, consider wrapping VelocityException in MailPreparationException.
* @param velocityEngine VelocityEngine to work with
* @param templateLocation the location of template, relative to Velocity's
* resource loader path
* @param model the Map that contains model names as keys and model objects
* as values
* @return the result as String
* @throws VelocityException if the template wasn't found or rendering failed
* @see org.springframework.mail.MailPreparationException
*/
public static String mergeTemplateIntoString(
VelocityEngine velocityEngine, String templateLocation, Map model, String toolboxConfigurationPath)
throws VelocityException {
StringWriter result = new StringWriter();
mergeTemplate(velocityEngine, templateLocation, model, result, toolboxConfigurationPath);
return result.toString();
}
/**
* Merge the specified Velocity template with the given model into a String.
* <p>When using this method to prepare a text for a mail to be sent with Spring's
* mail support, consider wrapping VelocityException in MailPreparationException.
* @param velocityEngine VelocityEngine to work with
* @param templateLocation the location of template, relative to Velocity's
* resource loader path
* @param encoding the encoding of the template file
* @param model the Map that contains model names as keys and model objects
* as values
* @return the result as String
* @throws VelocityException if the template wasn't found or rendering failed
* @see org.springframework.mail.MailPreparationException
*/
public static String mergeTemplateIntoString(
VelocityEngine velocityEngine, String templateLocation, String encoding, Map model, String toolboxConfigurationPath)
throws VelocityException {
StringWriter result = new StringWriter();
mergeTemplate(velocityEngine, templateLocation, encoding, model, result, toolboxConfigurationPath);
return result.toString();
}
}
--- VelocityEngineUtils.java.orig 2010-08-18 13:41:10.000000000 +0900
+++ VelocityEngineUtils.java 2011-05-25 17:26:08.262838600 +0900
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.springframework.ui.velocity;
+package yourdomain.yourapp;
import java.io.StringWriter;
import java.io.Writer;
@@ -24,7 +24,9 @@
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
+import org.apache.velocity.context.Context;
import org.apache.velocity.exception.VelocityException;
+import org.apache.velocity.tools.ToolManager;
/**
* Utility class for working with a VelocityEngine.
@@ -50,11 +52,11 @@
* @throws VelocityException if the template wasn't found or rendering failed
*/
public static void mergeTemplate(
- VelocityEngine velocityEngine, String templateLocation, Map model, Writer writer)
+ VelocityEngine velocityEngine, String templateLocation, Map model, Writer writer, String toolboxConfigurationPath)
throws VelocityException {
try {
- VelocityContext velocityContext = new VelocityContext(model);
+ VelocityContext velocityContext = new VelocityContext(model, createToolboxContext(toolboxConfigurationPath));
velocityEngine.mergeTemplate(templateLocation, velocityContext, writer);
}
catch (VelocityException ex) {
@@ -82,11 +84,11 @@
* @throws VelocityException if the template wasn't found or rendering failed
*/
public static void mergeTemplate(
- VelocityEngine velocityEngine, String templateLocation, String encoding, Map model, Writer writer)
+ VelocityEngine velocityEngine, String templateLocation, String encoding, Map model, Writer writer, String toolboxConfigurationPath)
throws VelocityException {
try {
- VelocityContext velocityContext = new VelocityContext(model);
+ VelocityContext velocityContext = new VelocityContext(model, createToolboxContext(toolboxConfigurationPath));
velocityEngine.mergeTemplate(templateLocation, encoding, velocityContext, writer);
}
catch (VelocityException ex) {
@@ -101,6 +103,12 @@
}
}
+ private static Context createToolboxContext(String path) {
+ ToolManager toolManager = new ToolManager();
+ toolManager.configure(path);
+ return toolManager.createContext();
+ }
+
/**
* Merge the specified Velocity template with the given model into a String.
* <p>When using this method to prepare a text for a mail to be sent with Spring's
@@ -115,11 +123,11 @@
* @see org.springframework.mail.MailPreparationException
*/
public static String mergeTemplateIntoString(
- VelocityEngine velocityEngine, String templateLocation, Map model)
+ VelocityEngine velocityEngine, String templateLocation, Map model, String toolboxConfigurationPath)
throws VelocityException {
StringWriter result = new StringWriter();
- mergeTemplate(velocityEngine, templateLocation, model, result);
+ mergeTemplate(velocityEngine, templateLocation, model, result, toolboxConfigurationPath);
return result.toString();
}
@@ -138,12 +146,11 @@
* @see org.springframework.mail.MailPreparationException
*/
public static String mergeTemplateIntoString(
- VelocityEngine velocityEngine, String templateLocation, String encoding, Map model)
+ VelocityEngine velocityEngine, String templateLocation, String encoding, Map model, String toolboxConfigurationPath)
throws VelocityException {
StringWriter result = new StringWriter();
- mergeTemplate(velocityEngine, templateLocation, encoding, model, result);
+ mergeTemplate(velocityEngine, templateLocation, encoding, model, result, toolboxConfigurationPath);
return result.toString();
}
-
}
package yourdomain.yourapp;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
/**
* Velocity テンプレートにパラメータをマージするクラスです。
*/
public class VelocityMerger implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(VelocityMerger.class);
private VelocityEngine engine;
private Resource toolBoxConfigLocation;
private String toolBoxConfigurationPath;
public void setToolBoxConfigLocation(Resource toolBoxConfigLocation) {
this.toolBoxConfigLocation = toolBoxConfigLocation;
}
public void setEngine(VelocityEngine engine) {
this.engine = engine;
}
@Override
public void afterPropertiesSet() throws IOException {
toolBoxConfigurationPath = toolBoxConfigLocation.getFile().getAbsolutePath();
if (logger.isInfoEnabled()) {
logger.info("Resource loader path '{}' resolved to file '{}'", toolBoxConfigLocation.getURI(), toolBoxConfigurationPath);
}
}
/**
* Velocity テンプレートにパラメータをマージした結果を得ます。
* テンプレートのエンコーディングは、設定ファイルで定義されたデフォルト値を使用します。
* @param templateName テンプレート名
* @param model パラメータを保持するMap
* @return マージ結果の文字列
*/
public String merge(String templateName, Map<String, Object> model) {
return VelocityEngineUtils.mergeTemplateIntoString(engine, templateName, model, toolBoxConfigurationPath);
}
/**
* Velocity テンプレートにパラメータをマージした結果を得ます。
* テンプレートのエンコーディングをパラメータで指定できます。
* @param templateName テンプレート名
* @param templateEncoding テンプレートのエンコーディング
* @param model パラメータを保持するMap
* @return マージ結果の文字列
*/
public String merge(String templateName, String templateEncoding, Map<String, Object> model) {
return VelocityEngineUtils.mergeTemplateIntoString(engine, templateName, templateEncoding, model,
toolBoxConfigurationPath);
}
/**
* Velocity テンプレートにパラメータをマージし、結果を Writer に書き出します。
* テンプレートのエンコーディングは、設定ファイルで定義されたデフォルト値を使用します。
* @param templateName テンプレート名
* @param model パラメータを保持するMap
* @param writer マージ結果を書き出す Writer
*/
public void mergeToWriter(String templateName, Map<String, Object> model, Writer writer) {
VelocityEngineUtils.mergeTemplate(engine, templateName, model, writer, toolBoxConfigurationPath);
}
/**
* Velocity テンプレートにパラメータをマージし、結果を Writer に書き出します。
* テンプレートのエンコーディングをパラメータで指定できます。
* @param templateName テンプレート名
* @param templateEncoding テンプレートのエンコーディング名
* @param model パラメータを保持するMap
* @param writer マージ結果を書き出す Writer
*/
public void mergeToWriter(String templateName, String templateEncoding, Map<String, Object> model, Writer writer) {
VelocityEngineUtils.mergeTemplate(engine, templateName, templateEncoding, model, writer,
toolBoxConfigurationPath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment