001: /*
002: * Copyright 2002-2007 the original author or authors.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package org.springframework.web.servlet.view.velocity;
018:
019: import java.util.Enumeration;
020: import java.util.HashMap;
021: import java.util.Iterator;
022: import java.util.Locale;
023: import java.util.Map;
024: import java.util.Properties;
025:
026: import javax.servlet.http.HttpServletRequest;
027: import javax.servlet.http.HttpServletResponse;
028:
029: import org.apache.velocity.Template;
030: import org.apache.velocity.VelocityContext;
031: import org.apache.velocity.app.VelocityEngine;
032: import org.apache.velocity.app.tools.VelocityFormatter;
033: import org.apache.velocity.context.Context;
034: import org.apache.velocity.exception.MethodInvocationException;
035: import org.apache.velocity.exception.ResourceNotFoundException;
036: import org.apache.velocity.tools.generic.DateTool;
037: import org.apache.velocity.tools.generic.NumberTool;
038:
039: import org.springframework.beans.BeansException;
040: import org.springframework.beans.factory.BeanFactoryUtils;
041: import org.springframework.beans.factory.NoSuchBeanDefinitionException;
042: import org.springframework.context.ApplicationContextException;
043: import org.springframework.util.ClassUtils;
044: import org.springframework.web.servlet.support.RequestContextUtils;
045: import org.springframework.web.servlet.view.AbstractTemplateView;
046: import org.springframework.web.util.NestedServletException;
047:
048: /**
049: * View using the Velocity template engine.
050: *
051: * <p>Exposes the following JavaBean properties:
052: * <ul>
053: * <li><b>url</b>: the location of the Velocity template to be wrapped,
054: * relative to the Velocity resource loader path (see VelocityConfigurer).
055: * <li><b>encoding</b> (optional, default is determined by Velocity configuration):
056: * the encoding of the Velocity template file
057: * <li><b>velocityFormatterAttribute</b> (optional, default=null): the name of
058: * the VelocityFormatter helper object to expose in the Velocity context of this
059: * view, or <code>null</code> if not needed. VelocityFormatter is part of standard Velocity.
060: * <li><b>dateToolAttribute</b> (optional, default=null): the name of the
061: * DateTool helper object to expose in the Velocity context of this view,
062: * or <code>null</code> if not needed. DateTool is part of Velocity Tools 1.0.
063: * <li><b>numberToolAttribute</b> (optional, default=null): the name of the
064: * NumberTool helper object to expose in the Velocity context of this view,
065: * or <code>null</code> if not needed. NumberTool is part of Velocity Tools 1.1.
066: * <li><b>cacheTemplate</b> (optional, default=false): whether or not the Velocity
067: * template should be cached. It should normally be true in production, but setting
068: * this to false enables us to modify Velocity templates without restarting the
069: * application (similar to JSPs). Note that this is a minor optimization only,
070: * as Velocity itself caches templates in a modification-aware fashion.
071: * </ul>
072: *
073: * <p>Depends on a VelocityConfig object such as VelocityConfigurer being
074: * accessible in the current web application context, with any bean name.
075: * Alternatively, you can set the VelocityEngine object as bean property.
076: *
077: * <p>Note: Spring's VelocityView requires Velocity 1.3 or higher, and optionally
078: * Velocity Tools 1.0 or higher (depending on the use of DateTool and/or NumberTool).
079: *
080: * @author Rod Johnson
081: * @author Juergen Hoeller
082: * @see VelocityConfig
083: * @see VelocityConfigurer
084: * @see #setUrl
085: * @see #setExposeSpringMacroHelpers
086: * @see #setEncoding
087: * @see #setVelocityEngine
088: * @see VelocityConfig
089: * @see VelocityConfigurer
090: */
091: public class VelocityView extends AbstractTemplateView {
092:
093: private Map toolAttributes;
094:
095: private String velocityFormatterAttribute;
096:
097: private String dateToolAttribute;
098:
099: private String numberToolAttribute;
100:
101: private String encoding;
102:
103: private boolean cacheTemplate = false;
104:
105: private VelocityEngine velocityEngine;
106:
107: private Template template;
108:
109: /**
110: * Set tool attributes to expose to the view, as attribute name / class name pairs.
111: * An instance of the given class will be added to the Velocity context for each
112: * rendering operation, under the given attribute name.
113: * <p>For example, an instance of MathTool, which is part of the generic package
114: * of Velocity Tools, can be bound under the attribute name "math", specifying the
115: * fully qualified class name "org.apache.velocity.tools.generic.MathTool" as value.
116: * <p>Note that VelocityView can only create simple generic tools or values, that is,
117: * classes with a public default constructor and no further initialization needs.
118: * This class does not do any further checks, to not introduce a required dependency
119: * on a specific tools package.
120: * <p>For tools that are part of the view package of Velocity Tools, a special
121: * Velocity context and a special init callback are needed. Use VelocityToolboxView
122: * in such a case, or override <code>createVelocityContext</code> and
123: * <code>initTool</code> accordingly.
124: * <p>For a simple VelocityFormatter instance or special locale-aware instances
125: * of DateTool/NumberTool, which are part of the generic package of Velocity Tools,
126: * specify the "velocityFormatterAttribute", "dateToolAttribute" or
127: * "numberToolAttribute" properties, respectively.
128: * @param toolAttributes attribute names as keys, and tool class names as values
129: * @see org.apache.velocity.tools.generic.MathTool
130: * @see VelocityToolboxView
131: * @see #createVelocityContext
132: * @see #initTool
133: * @see #setVelocityFormatterAttribute
134: * @see #setDateToolAttribute
135: * @see #setNumberToolAttribute
136: */
137: public void setToolAttributes(Properties toolAttributes) {
138: this .toolAttributes = new HashMap(toolAttributes.size());
139: for (Enumeration attributeNames = toolAttributes
140: .propertyNames(); attributeNames.hasMoreElements();) {
141: String attributeName = (String) attributeNames
142: .nextElement();
143: String className = toolAttributes
144: .getProperty(attributeName);
145: Class toolClass = null;
146: try {
147: toolClass = ClassUtils.forName(className);
148: } catch (ClassNotFoundException ex) {
149: throw new IllegalArgumentException(
150: "Invalid definition for tool '" + attributeName
151: + "' - tool class not found: "
152: + ex.getMessage());
153: }
154: this .toolAttributes.put(attributeName, toolClass);
155: }
156: }
157:
158: /**
159: * Set the name of the VelocityFormatter helper object to expose in the
160: * Velocity context of this view, or <code>null</code> if not needed.
161: * <p>VelocityFormatter is part of the standard Velocity distribution.
162: * @see org.apache.velocity.app.tools.VelocityFormatter
163: */
164: public void setVelocityFormatterAttribute(
165: String velocityFormatterAttribute) {
166: this .velocityFormatterAttribute = velocityFormatterAttribute;
167: }
168:
169: /**
170: * Set the name of the DateTool helper object to expose in the Velocity context
171: * of this view, or <code>null</code> if not needed. The exposed DateTool will be aware of
172: * the current locale, as determined by Spring's LocaleResolver.
173: * <p>DateTool is part of the generic package of Velocity Tools 1.0.
174: * Spring uses a special locale-aware subclass of DateTool.
175: * @see org.apache.velocity.tools.generic.DateTool
176: * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
177: * @see org.springframework.web.servlet.LocaleResolver
178: */
179: public void setDateToolAttribute(String dateToolAttribute) {
180: this .dateToolAttribute = dateToolAttribute;
181: }
182:
183: /**
184: * Set the name of the NumberTool helper object to expose in the Velocity context
185: * of this view, or <code>null</code> if not needed. The exposed NumberTool will be aware of
186: * the current locale, as determined by Spring's LocaleResolver.
187: * <p>NumberTool is part of the generic package of Velocity Tools 1.1.
188: * Spring uses a special locale-aware subclass of NumberTool.
189: * @see org.apache.velocity.tools.generic.NumberTool
190: * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
191: * @see org.springframework.web.servlet.LocaleResolver
192: */
193: public void setNumberToolAttribute(String numberToolAttribute) {
194: this .numberToolAttribute = numberToolAttribute;
195: }
196:
197: /**
198: * Set the encoding of the Velocity template file. Default is determined
199: * by the VelocityEngine: "ISO-8859-1" if not specified otherwise.
200: * <p>Specify the encoding in the VelocityEngine rather than per template
201: * if all your templates share a common encoding.
202: */
203: public void setEncoding(String encoding) {
204: this .encoding = encoding;
205: }
206:
207: /**
208: * Return the encoding for the Velocity template.
209: */
210: protected String getEncoding() {
211: return this .encoding;
212: }
213:
214: /**
215: * Set whether the Velocity template should be cached. Default is "false".
216: * It should normally be true in production, but setting this to false enables us to
217: * modify Velocity templates without restarting the application (similar to JSPs).
218: * <p>Note that this is a minor optimization only, as Velocity itself caches
219: * templates in a modification-aware fashion.
220: */
221: public void setCacheTemplate(boolean cacheTemplate) {
222: this .cacheTemplate = cacheTemplate;
223: }
224:
225: /**
226: * Return whether the Velocity template should be cached.
227: */
228: protected boolean isCacheTemplate() {
229: return this .cacheTemplate;
230: }
231:
232: /**
233: * Set the VelocityEngine to be used by this view.
234: * If this is not set, the default lookup will occur: A single VelocityConfig
235: * is expected in the current web application context, with any bean name.
236: * @see VelocityConfig
237: */
238: public void setVelocityEngine(VelocityEngine velocityEngine) {
239: this .velocityEngine = velocityEngine;
240: }
241:
242: /**
243: * Return the VelocityEngine used by this view.
244: */
245: protected VelocityEngine getVelocityEngine() {
246: return this .velocityEngine;
247: }
248:
249: /**
250: * Invoked on startup. Looks for a single VelocityConfig bean to
251: * find the relevant VelocityEngine for this factory.
252: */
253: protected void initApplicationContext() throws BeansException {
254: super .initApplicationContext();
255:
256: if (getVelocityEngine() == null) {
257: // No explicit VelocityEngine: try to autodetect one.
258: setVelocityEngine(autodetectVelocityEngine());
259: }
260:
261: checkTemplate();
262: }
263:
264: /**
265: * Autodetect a VelocityEngine via the ApplicationContext.
266: * Called if no explicit VelocityEngine has been specified.
267: * @return the VelocityEngine to use for VelocityViews
268: * @throws BeansException if no VelocityEngine could be found
269: * @see #getApplicationContext
270: * @see #setVelocityEngine
271: */
272: protected VelocityEngine autodetectVelocityEngine()
273: throws BeansException {
274: try {
275: VelocityConfig velocityConfig = (VelocityConfig) BeanFactoryUtils
276: .beanOfTypeIncludingAncestors(
277: getApplicationContext(),
278: VelocityConfig.class, true, false);
279: return velocityConfig.getVelocityEngine();
280: } catch (NoSuchBeanDefinitionException ex) {
281: throw new ApplicationContextException(
282: "Must define a single VelocityConfig bean in this web application context "
283: + "(may be inherited): VelocityConfigurer is the usual implementation. "
284: + "This bean may be given any name.", ex);
285: }
286: }
287:
288: /**
289: * Check that the Velocity template used for this view exists and is valid.
290: * <p>Can be overridden to customize the behavior, for example in case of
291: * multiple templates to be rendered into a single view.
292: * @throws ApplicationContextException if the template cannot be found or is invalid
293: */
294: protected void checkTemplate() throws ApplicationContextException {
295: try {
296: // Check that we can get the template, even if we might subsequently get it again.
297: this .template = getTemplate();
298: } catch (ResourceNotFoundException ex) {
299: throw new ApplicationContextException(
300: "Cannot find Velocity template for URL ["
301: + getUrl()
302: + "]: Did you specify the correct resource loader path?",
303: ex);
304: } catch (Exception ex) {
305: throw new ApplicationContextException(
306: "Could not load Velocity template for URL ["
307: + getUrl() + "]", ex);
308: }
309: }
310:
311: /**
312: * Process the model map by merging it with the Velocity template.
313: * Output is directed to the servlet response.
314: * <p>This method can be overridden if custom behavior is needed.
315: */
316: protected void renderMergedTemplateModel(Map model,
317: HttpServletRequest request, HttpServletResponse response)
318: throws Exception {
319:
320: exposeHelpers(model, request);
321:
322: Context velocityContext = createVelocityContext(model, request,
323: response);
324: exposeHelpers(velocityContext, request, response);
325: exposeToolAttributes(velocityContext, request);
326:
327: doRender(velocityContext, response);
328: }
329:
330: /**
331: * Expose helpers unique to each rendering operation. This is necessary so that
332: * different rendering operations can't overwrite each other's formats etc.
333: * <p>Called by <code>renderMergedTemplateModel</code>. The default implementation
334: * is empty. This method can be overridden to add custom helpers to the model.
335: * @param model the model that will be passed to the template for merging
336: * @param request current HTTP request
337: * @throws Exception if there's a fatal error while we're adding model attributes
338: * @see #renderMergedTemplateModel
339: */
340: protected void exposeHelpers(Map model, HttpServletRequest request)
341: throws Exception {
342: }
343:
344: /**
345: * Create a Velocity Context instance for the given model,
346: * to be passed to the template for merging.
347: * <p>The default implementation delegates to {@link #createVelocityContext(Map)}.
348: * Can be overridden for a special context class, for example ChainedContext which
349: * is part of the view package of Velocity Tools. ChainedContext is needed for
350: * initialization of ViewTool instances.
351: * <p>Have a look at {@link VelocityToolboxView}, which pre-implements
352: * ChainedContext support. This is not part of the standard VelocityView class
353: * in order to avoid a required dependency on the view package of Velocity Tools.
354: * @param model the model Map, containing the model attributes to be exposed to the view
355: * @param request current HTTP request
356: * @param response current HTTP response
357: * @return the Velocity Context
358: * @throws Exception if there's a fatal error while creating the context
359: * @see #createVelocityContext(Map)
360: * @see #initTool
361: * @see org.apache.velocity.tools.view.context.ChainedContext
362: * @see VelocityToolboxView
363: */
364: protected Context createVelocityContext(Map model,
365: HttpServletRequest request, HttpServletResponse response)
366: throws Exception {
367:
368: return createVelocityContext(model);
369: }
370:
371: /**
372: * Create a Velocity Context instance for the given model,
373: * to be passed to the template for merging.
374: * <p>Default implementation creates an instance of Velocity's
375: * VelocityContext implementation class.
376: * @param model the model Map, containing the model attributes
377: * to be exposed to the view
378: * @return the Velocity Context
379: * @throws Exception if there's a fatal error while creating the context
380: * @see org.apache.velocity.VelocityContext
381: */
382: protected Context createVelocityContext(Map model) throws Exception {
383: return new VelocityContext(model);
384: }
385:
386: /**
387: * Expose helpers unique to each rendering operation. This is necessary so that
388: * different rendering operations can't overwrite each other's formats etc.
389: * <p>Called by <code>renderMergedTemplateModel</code>. Default implementation
390: * delegates to <code>exposeHelpers(velocityContext, request)</code>. This method
391: * can be overridden to add special tools to the context, needing the servlet response
392: * to initialize (see Velocity Tools, for example LinkTool and ViewTool/ChainedContext).
393: * @param velocityContext Velocity context that will be passed to the template
394: * @param request current HTTP request
395: * @param response current HTTP response
396: * @throws Exception if there's a fatal error while we're adding model attributes
397: * @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest)
398: */
399: protected void exposeHelpers(Context velocityContext,
400: HttpServletRequest request, HttpServletResponse response)
401: throws Exception {
402:
403: exposeHelpers(velocityContext, request);
404: }
405:
406: /**
407: * Expose helpers unique to each rendering operation. This is necessary so that
408: * different rendering operations can't overwrite each other's formats etc.
409: * <p>Default implementation is empty. This method can be overridden to add
410: * custom helpers to the Velocity context.
411: * @param velocityContext Velocity context that will be passed to the template
412: * @param request current HTTP request
413: * @throws Exception if there's a fatal error while we're adding model attributes
414: * @see #exposeHelpers(Map, HttpServletRequest)
415: */
416: protected void exposeHelpers(Context velocityContext,
417: HttpServletRequest request) throws Exception {
418: }
419:
420: /**
421: * Expose the tool attributes, according to corresponding bean property settings.
422: * <p>Do not override this method unless for further tools driven by bean properties.
423: * Override one of the <code>exposeHelpers</code> methods to add custom helpers.
424: * @param velocityContext Velocity context that will be passed to the template
425: * @param request current HTTP request
426: * @throws Exception if there's a fatal error while we're adding model attributes
427: * @see #setVelocityFormatterAttribute
428: * @see #setDateToolAttribute
429: * @see #setNumberToolAttribute
430: * @see #exposeHelpers(Map, HttpServletRequest)
431: * @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, HttpServletResponse)
432: */
433: protected void exposeToolAttributes(Context velocityContext,
434: HttpServletRequest request) throws Exception {
435: // Expose generic attributes.
436: if (this .toolAttributes != null) {
437: for (Iterator it = this .toolAttributes.entrySet()
438: .iterator(); it.hasNext();) {
439: Map.Entry entry = (Map.Entry) it.next();
440: String attributeName = (String) entry.getKey();
441: Class toolClass = (Class) entry.getValue();
442: try {
443: Object tool = toolClass.newInstance();
444: initTool(tool, velocityContext);
445: velocityContext.put(attributeName, tool);
446: } catch (Exception ex) {
447: throw new NestedServletException(
448: "Could not instantiate Velocity tool '"
449: + attributeName + "'", ex);
450: }
451: }
452: }
453:
454: // Expose VelocityFormatter attribute.
455: if (this .velocityFormatterAttribute != null) {
456: velocityContext.put(this .velocityFormatterAttribute,
457: new VelocityFormatter(velocityContext));
458: }
459:
460: // Expose locale-aware DateTool/NumberTool attributes.
461: if (this .dateToolAttribute != null
462: || this .numberToolAttribute != null) {
463: Locale locale = RequestContextUtils.getLocale(request);
464: if (this .dateToolAttribute != null) {
465: velocityContext.put(this .dateToolAttribute,
466: new LocaleAwareDateTool(locale));
467: }
468: if (this .numberToolAttribute != null) {
469: velocityContext.put(this .numberToolAttribute,
470: new LocaleAwareNumberTool(locale));
471: }
472: }
473: }
474:
475: /**
476: * Initialize the given tool instance. The default implementation is empty.
477: * <p>Can be overridden to check for special callback interfaces, for example
478: * the ViewContext interface which is part of the view package of Velocity Tools.
479: * In the particular case of ViewContext, you'll usually also need a special
480: * Velocity context, like ChainedContext which is part of Velocity Tools too.
481: * <p>Have a look at {@link VelocityToolboxView}, which pre-implements such a
482: * ViewTool check. This is not part of the standard VelocityView class in order
483: * to avoid a required dependency on the view package of Velocity Tools.
484: * @param tool the tool instance to initialize
485: * @param velocityContext the Velocity context
486: * @throws Exception if initializion of the tool failed
487: * @see #createVelocityContext
488: * @see org.apache.velocity.tools.view.context.ViewContext
489: * @see org.apache.velocity.tools.view.context.ChainedContext
490: * @see VelocityToolboxView
491: */
492: protected void initTool(Object tool, Context velocityContext)
493: throws Exception {
494: }
495:
496: /**
497: * Render the Velocity view to the given response, using the given Velocity
498: * context which contains the complete template model to use.
499: * <p>The default implementation renders the template specified by the "url"
500: * bean property, retrieved via <code>getTemplate</code>. It delegates to the
501: * <code>mergeTemplate</code> method to merge the template instance with the
502: * given Velocity context.
503: * <p>Can be overridden to customize the behavior, for example to render
504: * multiple templates into a single view.
505: * @param context the Velocity context to use for rendering
506: * @param response servlet response (use this to get the OutputStream or Writer)
507: * @throws Exception if thrown by Velocity
508: * @see #setUrl
509: * @see #getTemplate()
510: * @see #mergeTemplate
511: */
512: protected void doRender(Context context,
513: HttpServletResponse response) throws Exception {
514: if (logger.isDebugEnabled()) {
515: logger.debug("Rendering Velocity template [" + getUrl()
516: + "] in VelocityView '" + getBeanName() + "'");
517: }
518: mergeTemplate(getTemplate(), context, response);
519: }
520:
521: /**
522: * Retrieve the Velocity template to be rendered by this view.
523: * <p>By default, the template specified by the "url" bean property will be
524: * retrieved: either returning a cached template instance or loading a fresh
525: * instance (according to the "cacheTemplate" bean property)
526: * @return the Velocity template to render
527: * @throws Exception if thrown by Velocity
528: * @see #setUrl
529: * @see #setCacheTemplate
530: * @see #getTemplate(String)
531: */
532: protected Template getTemplate() throws Exception {
533: // We already hold a reference to the template, but we might want to load it
534: // if not caching. Velocity itself caches templates, so our ability to
535: // cache templates in this class is a minor optimization only.
536: if (isCacheTemplate() && this .template != null) {
537: return this .template;
538: } else {
539: return getTemplate(getUrl());
540: }
541: }
542:
543: /**
544: * Retrieve the Velocity template specified by the given name,
545: * using the encoding specified by the "encoding" bean property.
546: * <p>Can be called by subclasses to retrieve a specific template,
547: * for example to render multiple templates into a single view.
548: * @param name the file name of the desired template
549: * @return the Velocity template
550: * @throws Exception if thrown by Velocity
551: * @see org.apache.velocity.app.VelocityEngine#getTemplate
552: */
553: protected Template getTemplate(String name) throws Exception {
554: return (getEncoding() != null ? getVelocityEngine()
555: .getTemplate(name, getEncoding()) : getVelocityEngine()
556: .getTemplate(name));
557: }
558:
559: /**
560: * Merge the template with the context.
561: * Can be overridden to customize the behavior.
562: * @param template the template to merge
563: * @param context the Velocity context to use for rendering
564: * @param response servlet response (use this to get the OutputStream or Writer)
565: * @throws Exception if thrown by Velocity
566: * @see org.apache.velocity.Template#merge
567: */
568: protected void mergeTemplate(Template template, Context context,
569: HttpServletResponse response) throws Exception {
570:
571: try {
572: template.merge(context, response.getWriter());
573: } catch (MethodInvocationException ex) {
574: throw new NestedServletException(
575: "Method invocation failed during rendering of Velocity view with name '"
576: + getBeanName() + "': " + ex.getMessage()
577: + "; reference [" + ex.getReferenceName()
578: + "], method '" + ex.getMethodName() + "'",
579: ex.getWrappedThrowable());
580: }
581: }
582:
583: /**
584: * Subclass of DateTool from Velocity Tools, using a passed-in Locale
585: * (usually the RequestContext Locale) instead of the default Locale.N
586: * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
587: */
588: private static class LocaleAwareDateTool extends DateTool {
589:
590: private final Locale locale;
591:
592: private LocaleAwareDateTool(Locale locale) {
593: this .locale = locale;
594: }
595:
596: public Locale getLocale() {
597: return this .locale;
598: }
599: }
600:
601: /**
602: * Subclass of NumberTool from Velocity Tools, using a passed-in Locale
603: * (usually the RequestContext Locale) instead of the default Locale.
604: * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
605: */
606: private static class LocaleAwareNumberTool extends NumberTool {
607:
608: private final Locale locale;
609:
610: private LocaleAwareNumberTool(Locale locale) {
611: this .locale = locale;
612: }
613:
614: public Locale getLocale() {
615: return this.locale;
616: }
617: }
618:
619: }
|