1 package com.aurea.maven.plugins.util;
2
3 import java.io.BufferedWriter;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileWriter;
7 import java.io.IOException;
8 import java.util.Properties;
9
10 import org.apache.maven.project.MavenProject;
11 import org.apache.velocity.Template;
12 import org.apache.velocity.VelocityContext;
13 import org.apache.velocity.app.Velocity;
14
15 public class VelocityRunner {
16
17 private static VelocityRunner instance = null;
18 private VelocityContext context = null;
19 private MavenProject project = null;
20 private File outputDirectory = null;
21
22 private VelocityRunner(MavenProject project) {
23 try {
24 Velocity.init();
25 context = new VelocityContext();
26 this.project = project;
27 Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, project.getBasedir());
28 } catch (Exception e) {
29
30 }
31 }
32
33 public static VelocityRunner getInstance(MavenProject project) {
34 if (instance == null) {
35 instance = new VelocityRunner(project);
36 }
37 return instance;
38 }
39
40 public static VelocityRunner getInstance() throws Exception {
41 if (instance == null)
42 throw new Exception("VelocityRunner not initialized.");
43
44 return instance;
45 }
46
47 public void setOutputDirectory(String outputDirName) {
48 outputDirectory = new File(project.getBuild().getDirectory(), outputDirName);
49 }
50
51 public void addProperties(String prefix, String propFileName) {
52
53 Properties props = new Properties();
54
55 if (propFileName != null) {
56 File propFile = new File(project.getBasedir() + "/" + propFileName);
57 if (propFile.exists() && propFile.canRead()) {
58 try {
59 props.load(new FileInputStream(propFile));
60 } catch (Exception e) {
61
62 }
63 }
64 }
65 addProperty(prefix, props);
66 }
67
68 public void addProperty(String key, Object value) {
69 context.put(key, value);
70 }
71
72 public void run(String tplFile, String outFileName) throws Exception {
73 if (!outputDirectory.exists()) {
74 outputDirectory.mkdirs();
75 }
76
77 BufferedWriter out = null;
78 try {
79 Template template = Velocity.getTemplate(tplFile);
80 File outFile = new File(outputDirectory.getAbsoluteFile(), outFileName);
81 outFile.getParentFile().mkdirs();
82 out = new BufferedWriter(new FileWriter(outFile));
83 template.merge(context, out);
84 } catch (Exception e) {
85 throw new Exception("Template generation failed ...");
86 } finally {
87 try {
88 if (out != null) {
89 out.flush();
90 out.close();
91 }
92 } catch (IOException ioe) {
93
94 }
95 }
96 }
97 }