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