1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.exolab.castor.builder.printing;
17
18 import java.io.File;
19 import java.io.FileWriter;
20
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23 import org.apache.velocity.Template;
24 import org.apache.velocity.VelocityContext;
25 import org.apache.velocity.app.Velocity;
26 import org.exolab.castor.util.Version;
27 import org.exolab.javasource.JClass;
28
29
30
31
32
33
34 public class TemplateJClassPrinter implements JClassPrinter {
35
36
37
38
39 public static final String TEMPLATE_PACKAGE = "/org/exolab/castor/builder/printing/templates/";
40
41 private static final Log _log = LogFactory.getLog(TemplateJClassPrinter.class);
42
43
44
45
46 private boolean _initialized = false;
47
48
49
50
51 private void initializeVelocity() {
52
53 Velocity.setProperty("velocimacro.permissions.allowInline", "true");
54 Velocity.setProperty("velocimacro.library",
55 "/org/exolab/castor/builder/printing/templates/library.vm");
56 Velocity.setProperty("resource.loader", "classPathResource");
57 Velocity
58 .setProperty("classPathResource.resource.loader.class",
59 "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
60 try {
61 Velocity.init();
62 } catch (Exception e) {
63 System.out.println("init fails!");
64 e.printStackTrace();
65 }
66 }
67
68
69
70
71
72
73
74
75 public void printClass(final JClass jClass, final String outputDir,
76 final String lineSeparator, final String header) {
77
78 if (!_initialized) {
79 initializeVelocity();
80 _initialized = true;
81 }
82
83 _log.info("Printing JClass " + jClass.getName() + " using Velocity templates.");
84
85 try {
86
87
88 VelocityContext context = new VelocityContext();
89 context.put("jClass", jClass);
90 context.put("helper", new TemplateHelper());
91 context.put("version", Version.VERSION);
92
93
94 Template template =
95 Velocity.getTemplate(TEMPLATE_PACKAGE + "main.vm");
96 FileWriter fileWriter =
97 new FileWriter(new File(jClass.getFilename(outputDir)));
98 template.merge(context, fileWriter);
99 fileWriter.flush();
100 fileWriter.close();
101
102 } catch (Exception e) {
103 e.printStackTrace();
104 }
105
106 }
107
108 }