01: /*
02: * Copyright 2005 Joe Walker
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.directwebremoting.drapgen.generate.freemarker;
17:
18: import java.io.File;
19: import java.io.FileWriter;
20: import java.io.IOException;
21: import java.io.Writer;
22: import java.util.HashMap;
23: import java.util.Map;
24:
25: import org.directwebremoting.drapgen.ast.Project;
26: import org.directwebremoting.drapgen.ast.Type;
27: import org.directwebremoting.drapgen.generate.Generator;
28: import org.directwebremoting.util.LocalUtil;
29:
30: import freemarker.template.Configuration;
31: import freemarker.template.DefaultObjectWrapper;
32: import freemarker.template.Template;
33: import freemarker.template.TemplateException;
34:
35: /**
36: * @author Joe Walker [joe at getahead dot ltd dot uk]
37: */
38: public class FreemarkerGenerator implements Generator {
39: /* (non-Javadoc)
40: * @see org.directwebremoting.drapgen.generate.Generator#setGeneratedBase(java.lang.String)
41: */
42: public void setGeneratedBase(File generatedBase) {
43: this .generatedBase = generatedBase;
44: }
45:
46: /* (non-Javadoc)
47: * @see org.directwebremoting.drapgen.generate.Generator#generate(org.directwebremoting.drapgen.ast.Project)
48: */
49: public void generate(Project project) throws IOException {
50: Configuration cfg = new Configuration();
51: cfg.setObjectWrapper(new DefaultObjectWrapper());
52: cfg.setClassForTemplateLoading(this .getClass(), "");
53:
54: for (Type type : project.getTypes()) {
55: File directory = new File(generatedBase, type
56: .getPackageName().replace('.', '/'));
57: directory.mkdirs();
58:
59: Writer out = null;
60: try {
61: out = new FileWriter(new File(directory, type.getName()
62: + ".java"));
63: Template template = cfg.getTemplate("generate.ftl");
64:
65: Map<String, Object> root = new HashMap<String, Object>();
66: root.put("type", type);
67: root.put("project", project);
68: template.process(root, out);
69: } catch (TemplateException ex) {
70: throw new RuntimeException(ex);
71: } finally {
72: LocalUtil.close(out);
73: }
74: }
75: }
76:
77: private File generatedBase;
78: }
|