View Javadoc

1   package net.sf.jlayercheck.out.html;
2   
3   import java.io.Writer;
4   import java.text.SimpleDateFormat;
5   import java.util.Date;
6   import java.util.Map;
7   
8   import org.apache.velocity.VelocityContext;
9   import org.apache.velocity.app.Velocity;
10  import org.apache.velocity.exception.MethodInvocationException;
11  import org.apache.velocity.exception.ParseErrorException;
12  import org.apache.velocity.exception.ResourceNotFoundException;
13  
14  /**
15   * Prepares velocity and an initial context for a template.
16   * 
17   * @author timo
18   * @author $Author: stuelten $
19   * @version $Id: VelocityGenerator.java 18 2007-05-08 21:49:53Z stuelten $
20   */
21  public class VelocityGenerator {
22  
23  	/** Use UTF-8 as default encoding for templates. */
24  	public static final String DEFAULT_ENCODING = "UTF-8";
25  
26  	static {
27  		// Initialize velocity at least once
28  		try {
29  			Velocity.init();
30  		} catch (Exception e) {
31  			throw new InternalError("Cannot initialize velocity: " + e);
32  		}
33  	}
34  
35  	// fields
36  
37  	/** The name of the template */
38  	protected String template;
39  
40  	/** The {@link VelocityContext} for the template. */
41  	protected VelocityContext context;
42  
43  	// construction
44  
45  	/**
46  	 * Create a new generator.
47  	 */
48  	public VelocityGenerator() {
49  		super();
50  	}
51  
52  	/**
53  	 * Create a new generator for the given template
54  	 * 
55  	 * @param template
56  	 *            The name of the template to use.
57  	 * @param context
58  	 *            A Map with
59  	 */
60  	public VelocityGenerator(String template, Map<String, Object> addCtx) {
61  		this();
62  		setTemplate(template);
63  		addToContext(addCtx);
64  	}
65  
66  	// getter and setter
67  
68  	public String getTemplate() {
69  		return template;
70  	}
71  
72  	public void setTemplate(String template) {
73  		this.template = template;
74  		// simply put template name into context too
75  		getContext().put("templateName", template);
76  
77  	}
78  
79  	// context
80  
81  	/**
82  	 * Get the current {@link #context} or create a new empty one.
83  	 */
84  	public VelocityContext getContext() {
85  		if (context == null) {
86  			// create inital empty context
87  			context = new VelocityContext();
88  
89  			// default entries
90  			Date now = new Date();
91  			context.put("now", now);
92  			context.put("nowIso", new SimpleDateFormat("yyyy-MM-dd_HH:mm:ssZ")
93  					.format(now));
94  			context
95  					.put("today", SimpleDateFormat.getDateInstance()
96  							.format(now));
97  			context.put("todayIso", new SimpleDateFormat("yyyy-MM-dd")
98  					.format(now));
99  
100 			// self-reference the context
101 			context.put("context", context);
102 
103 			// add this
104 			context.put("generator", this);
105 
106 		}
107 		return context;
108 	}
109 
110 	/**
111 	 * Set the {@link #context}.
112 	 * 
113 	 * @param context
114 	 *            the new context
115 	 */
116 	public void setContext(VelocityContext context) {
117 		this.context = context;
118 	}
119 
120 	/**
121 	 * Add all entries to the {@link #context}.
122 	 * 
123 	 * @param addCtx
124 	 *            The map containing the entries
125 	 */
126 	public void addToContext(Map<String, Object> addCtx) {
127 		if (context == null) {
128 			// initialize context
129 			getContext();
130 		}
131 		for (Map.Entry<String, Object> entry : addCtx.entrySet()) {
132 			context.put(entry.getKey(), entry.getValue());
133 		}
134 	}
135 
136 	/**
137 	 * Start generation and write output.
138 	 * 
139 	 * @param writer
140 	 *            write output into this writer
141 	 */
142 	public void generate(Writer writer) {
143 		if (writer == null)
144 			throw new NullPointerException("writer must not be null!");
145 
146 		String templateName = getTemplate();
147 		if (templateName == null)
148 			throw new NullPointerException("template must not be null!");
149 
150 		try {
151 			// let the party start
152 			Velocity.mergeTemplate(templateName, DEFAULT_ENCODING, //
153 					getContext(), writer);
154 		} catch (ResourceNotFoundException e) {
155 			// wrong template name?
156 			throw new RuntimeException(e);
157 		} catch (ParseErrorException e) {
158 			// syntax error: problem parsing the template
159 			throw new RuntimeException(e);
160 		} catch (MethodInvocationException e) {
161 			// something threw an exception in the template
162 			throw new RuntimeException(e);
163 		} catch (Exception e) {
164 			// Something weird happend
165 			throw new RuntimeException(e);
166 		}
167 
168 	}
169 
170 }