1 /*
2 * $Id: VelocityUtils.java 2993 2011-11-24 19:51:48Z andrewinkler $
3 * ============================================================================
4 * Project gluehloch-homepage-core
5 * Copyright (c) 2004-2007 by Andre Winkler. All rights reserved.
6 * ============================================================================
7 * GNU LESSER GENERAL PUBLIC LICENSE
8 * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 *
24 */
25
26 package de.awtools.homegen.velocity;
27
28 import java.io.StringWriter;
29 import java.io.Writer;
30
31 import org.apache.commons.io.IOUtils;
32 import org.apache.velocity.Template;
33 import org.apache.velocity.VelocityContext;
34 import org.apache.velocity.app.Velocity;
35 import org.apache.velocity.exception.ParseErrorException;
36 import org.apache.velocity.exception.ResourceNotFoundException;
37
38 import de.awtools.homegen.TransformerException;
39
40 /**
41 * Utility Methoden für den Umgang mit Velocity.
42 *
43 * @version $LastChangedRevision: 2993 $ $LastChangedDate: 2011-11-24 20:51:48 +0100 (Thu, 24 Nov 2011) $
44 * @author by Andre Winkler, $LastChangedBy: andrewinkler $
45 *
46 * @since 1.2
47 */
48 public final class VelocityUtils {
49
50 /**
51 * Generiert einen String aus einem Velocity-Kontext und -Template.
52 *
53 * @param velocityContext Der Kontext.
54 * @param templateFile Eine Template Datei. Wird aus dem Klassenpfad
55 * gelesen.
56 * @param encoding Zeichensatzkodierung der VM Datei.
57 * @return Der generierte String.
58 */
59 public static String toString(final VelocityContext velocityContext,
60 final String templateFile, final String encoding) {
61
62 Writer writer = null;
63 try {
64 writer = new StringWriter();
65 Template template = Velocity.getTemplate(templateFile, encoding);
66 template.merge(velocityContext, writer);
67 } catch (ResourceNotFoundException ex) {
68 throw new TransformerException(ex);
69 } catch (ParseErrorException ex) {
70 throw new TransformerException(ex);
71 } catch (Exception ex) {
72 throw new TransformerException(ex);
73 } finally {
74 IOUtils.closeQuietly(writer);
75 }
76 return (writer.toString());
77 }
78 }