01: package net.sourceforge.jaxor.parser;
02:
03: import net.sourceforge.jaxor.util.SystemException;
04: import org.apache.velocity.VelocityContext;
05: import org.apache.velocity.runtime.log.LogSystem;
06:
07: import java.io.File;
08: import java.io.FileOutputStream;
09: import java.io.IOException;
10: import java.io.PrintStream;
11: import java.util.ArrayList;
12: import java.util.Iterator;
13: import java.util.List;
14:
15: /*
16: * User: Mike
17: * Date: Nov 10, 2002
18: * Time: 9:55:34 PM
19: */
20:
21: public class SourceGenerator {
22: private final File _destdir;
23: private final long _timestamp;
24: private final List _configs = new ArrayList();
25: private final VelocityContext _context = new VelocityContext();
26: private final CodeTemplate _code;
27:
28: public SourceGenerator(Jaxor jaxor, File destdir, long timestamp,
29: LogSystem log) {
30: _destdir = destdir;
31: _timestamp = timestamp;
32: _context.put("jaxor", jaxor);
33: _code = new CodeTemplate(log, _context);
34: }
35:
36: public void addToContext(String name, Object obj) {
37: _context.put(name, obj);
38: }
39:
40: public void add(String template, String fileName) {
41: _configs.add(new Config(template, fileName));
42: }
43:
44: public void generate() {
45: for (Iterator iter = _configs.iterator(); iter.hasNext();) {
46: Config element = (Config) iter.next();
47: generate(element);
48: }
49: }
50:
51: private boolean generate(Config config) {
52: PrintStream out = null;
53: try {
54: File file = new File(_destdir, config.file + ".java");
55: if (file.exists() && file.lastModified() > _timestamp) {
56: return false;
57: }
58: System.out.println("Generating " + file.getPath());
59: _destdir.mkdirs();
60: out = new PrintStream(new FileOutputStream(file));
61: print(out, config.template);
62: return true;
63: } catch (IOException exc) {
64: throw new SystemException(exc);
65: } finally {
66: if (out != null) {
67: out.flush();
68: out.close();
69: }
70: }
71: }
72:
73: public void print(PrintStream out, String template) {
74: _code.write(template, out);
75: }
76:
77: private static class Config {
78: public final String template;
79: public final String file;
80:
81: public Config(String template, String file) {
82: this.template = template;
83: this.file = file;
84: }
85: }
86: }
|