1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.javagen.agile.core.emitter.template;
17
18 import java.io.File;
19 import java.io.Writer;
20 import java.util.Iterator;
21 import java.util.Map;
22 import java.util.Properties;
23
24 import org.apache.velocity.Template;
25 import org.apache.velocity.VelocityContext;
26 import org.apache.velocity.app.VelocityEngine;
27 import org.javagen.agile.core.emitter.DefaultWriterFactory;
28 import org.javagen.agile.core.emitter.WriterFactory;
29 import org.javagen.agile.core.util.ResourceLoader;
30
31 /***
32 * Velocity template implementation.
33 *
34 * @author Richard Easterling
35 */
36 public class VelocityCodeGenerator implements TemplateGenerator {
37
38 public static final String DEFAULT_TEMPLATE_LOCATION_PATH = "/";
39 public static final String TEMPLATE_FILE_EXTENSION = ".vm";
40 public static final String VELOCITY_PROPERTIES_FILE = "classpath:"+DEFAULT_TEMPLATE_LOCATION_PATH+"velocity.properties";
41
42 protected String templateBasePath = DEFAULT_TEMPLATE_LOCATION_PATH;
43
44 VelocityEngine vengine = null;
45
46 protected WriterFactory writerFactory;
47
48 public VelocityCodeGenerator() {
49 try {
50 Properties velocityInitProps = ResourceLoader.properties(VELOCITY_PROPERTIES_FILE);
51 vengine = new VelocityEngine();
52 vengine.init(velocityInitProps);
53 } catch (Exception e) {
54 throw new IllegalStateException("Error reading: "+VELOCITY_PROPERTIES_FILE, e);
55 }
56 }
57
58
59 String tempTemplate = "templates/atc/common/ValidationTypesGen.xml.vm";
60
61
62
63
64
65
66
67
68
69 /*** Process templates. */
70 public void gen(String templatePath, File outFile, Map<String, Object> context)
71 {
72 try {
73
74 VelocityContext velocityContext = populateContext(context);
75 Template template = vengine.getTemplate(templatePath);
76 Writer writer = getWriterFactory().createWriter(outFile);
77 template.merge(velocityContext, writer);
78 writer.flush();
79 writer.close();
80 } catch (Exception e) {
81 throw new RuntimeException("running Velocity template: "+templatePath, e);
82 }
83 }
84
85 /***
86 * Copy over localized properties to velocity context.
87 */
88 private VelocityContext populateContext(Map<String, Object> props) {
89 VelocityContext context = new VelocityContext();
90 Iterator<String> iter = props.keySet().iterator();
91 while(iter.hasNext()) {
92 String key = iter.next();
93 context.put(key, props.get(key));
94 }
95 return context;
96 }
97
98 public String getTemplateBasePath() {
99 return templateBasePath;
100 }
101
102 public void setTemplateBasePath(String templateBasePath) {
103 this.templateBasePath = templateBasePath;
104 }
105
106 public void setWriterFactory(WriterFactory writerFactory) {
107 this.writerFactory = writerFactory;
108 }
109
110 public WriterFactory getWriterFactory() {
111 if (writerFactory == null) {
112 writerFactory = new DefaultWriterFactory();
113 }
114 return writerFactory;
115 }
116
117 }