1 package com.salto.db.generator.plugin;
2
3 import java.io.BufferedWriter;
4 import java.io.ByteArrayOutputStream;
5 import java.io.File;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.OutputStreamWriter;
9 import java.util.Enumeration;
10 import java.util.Iterator;
11 import java.util.Map;
12 import java.util.Properties;
13 import java.util.PropertyResourceBundle;
14 import java.util.ResourceBundle;
15
16 import org.apache.velocity.Template;
17 import org.apache.velocity.VelocityContext;
18 import org.apache.velocity.app.Velocity;
19
20 public abstract class VelocityAbstractPlugin extends
21 DefaultAbstractGeneratorPlugin {
22
23 protected static void runVelocity(String templatesPath,
24 String templateName, String outputDirectory, String outputFilename,
25 Map context) throws Exception {
26
27 ByteArrayOutputStream out = new ByteArrayOutputStream();
28 FileOutputStream fileOutputStream = null;
29
30 try {
31
32 PropertyResourceBundle bundle = (PropertyResourceBundle) ResourceBundle
33 .getBundle("org.apache.velocity.runtime.defaults.velocity");
34 Properties props = new Properties();
35 Enumeration enumeration = bundle.getKeys();
36 String cle;
37 while (enumeration.hasMoreElements()) {
38 cle = (String) enumeration.nextElement();
39 props.put(cle, bundle.getString(cle));
40 }
41 props.put("resource.loader", "class");
42 props
43 .put("class.resource.loader.class",
44 "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
45 props.put("class.resource.loader.path", templatesPath);
46 props.put("directive.foreach.counter.initial.value", "0");
47 Velocity.init(props);
48 Template t = Velocity.getTemplate(templatesPath + "/"
49 + templateName);
50
51 VelocityContext velocityContext = new VelocityContext();
52 for (Iterator iterator = context.entrySet().iterator(); iterator
53 .hasNext();) {
54 Map.Entry entry = (Map.Entry) iterator.next();
55 velocityContext.put((String) entry.getKey(), entry.getValue());
56 }
57
58 t.initDocument();
59 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
60 out));
61 t.merge(velocityContext, writer);
62 writer.flush();
63 File dir = new File(outputDirectory);
64 dir.mkdirs();
65 fileOutputStream = new FileOutputStream(dir.getPath() + "/"
66 + outputFilename);
67 fileOutputStream.write(out.toByteArray());
68
69 } catch (Exception e) {
70 e.printStackTrace();
71 } finally {
72 try {
73 out.close();
74 } catch (IOException e1) {
75 }
76 try {
77 fileOutputStream.close();
78 } catch (IOException e1) {
79 }
80 }
81
82 }
83
84 }