KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > tool > codegen > TemplateDrivenGenerator


1
2 /*
3  * Enhydra Java Application Server Project
4  *
5  * The contents of this file are subject to the Enhydra Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License on
8  * the Enhydra web site ( http://www.enhydra.org/ ).
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific terms governing rights and limitations
13  * under the License.
14  *
15  * The Initial Developer of the Enhydra Application Server is Lutris
16  * Technologies, Inc. The Enhydra Application Server and portions created
17  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
18  * All Rights Reserved.
19  *
20  * Contributor(s):
21  * Paul Mahar
22  *
23  */

24 package org.enhydra.tool.codegen;
25
26 // ToolBox imports
27
import org.enhydra.tool.ToolBoxInfo;
28 import org.enhydra.tool.common.FileUtil;
29 import org.enhydra.tool.common.PathHandle;
30 import org.enhydra.tool.common.Replacement;
31 import org.enhydra.tool.common.ReplacementSet;
32 import org.enhydra.tool.common.ResUtil;
33 import org.enhydra.tool.common.ToolException;
34 import org.enhydra.tool.common.Template;
35 import org.enhydra.tool.common.TemplateTool;
36 import org.enhydra.tool.common.TemplateFilter;
37 import org.enhydra.tool.common.event.TemplateListener;
38 import org.enhydra.tool.configure.ConfigTool;
39
40 // Standard imports
41
import java.io.File JavaDoc;
42 import java.util.Properties JavaDoc;
43 import java.util.ResourceBundle JavaDoc;
44 import java.util.Vector JavaDoc;
45 import javax.swing.JFrame JavaDoc;
46 import java.net.URL JavaDoc;
47
48 /**
49  * A partial implementation of the Generator interface that works with
50  * template files. The predefined generators are based on this class.
51  *
52  */

53 abstract public class TemplateDrivenGenerator implements Generator,
54         TemplateListener, Constants {
55     public static ResourceBundle JavaDoc res =
56         ResourceBundle.getBundle("org.enhydra.tool.codegen.Res"); // nores
57

58     //
59
private Properties JavaDoc properties = new Properties JavaDoc();
60     private File JavaDoc rootDir = null;
61     private Vector JavaDoc fileVector = new Vector JavaDoc();
62     private ReplacementSet replacementSet = null;
63     private OptionSet optionSet = null;
64     private boolean overwrite = false;
65     private boolean echo = true;
66     private boolean swing = true;
67
68     //
69
abstract public TemplateFilter createTemplateFilter(TemplateTool tool)
70             throws GeneratorException;
71     abstract public TemplateFilter createCopyFilter(TemplateTool tool)
72             throws GeneratorException;
73     abstract public String JavaDoc getDestination() throws GeneratorException;
74     abstract public void initReplacementSet() throws GeneratorException;
75     abstract public Replacement[] createReplacementsForDirectory(PathHandle path)
76             throws GeneratorException;
77
78     /**
79      * Use the display name for the string representation of this class
80      * so that a list model can map directly into generators.
81      *
82      * @return
83      * The display name.
84      */

85     public String JavaDoc toString() {
86         return getDisplayName();
87     }
88
89     /**
90      * Get properties used to customize CodeGen. This may contain
91      * information on the template directory location and
92      * persisted generation options.
93      *
94      * @return
95      * Properties passed from the CodeGen class.
96      */

97     public Properties JavaDoc getProperties() {
98         return properties;
99     }
100
101     /**
102      * Set CodeGen customization properties. The CodeGen
103      * class calls this method after it instantiates a
104      * generator class.
105      *
106      * @param properties
107      * Properties passed from the CodeGen class.
108      */

109     public void setProperties(Properties JavaDoc p) throws GeneratorException {
110         Template root = null;
111
112         properties = p;
113         root = getTemplateRoot();
114         if (root == null) {
115             throw new GeneratorException(res.getString("Root_path_is_not"));
116         } else if (!root.isDirectory()) {
117             throw new GeneratorException(ResUtil.format(res.getString("Invalid_template_0"),
118                                                         root.toString()));
119         }
120
121         // read in persisteted option values
122
GeneratorOption[] options = getOptionSet().toArray();
123
124         for (int i = 0; i < options.length; i++) {
125             String JavaDoc name = options[i].getName();
126             String JavaDoc value = options[i].getValue();
127
128             value = properties.getProperty(getCommandName() + '.' + name,
129                                            value);
130             if (value != null) {
131                 if (options[i].isRequired()) {
132                     if (value.trim().length() > 0) {
133                         getOptionSet().lookup(name).setValue(value);
134                     }
135                 } else {
136                     getOptionSet().lookup(name).setValue(value);
137                 }
138             }
139         }
140     }
141
142     /**
143      * Get the location of the template files.
144      *
145      * @returns
146      * The directory containing template files.
147      */

148     public Template getTemplateRoot() {
149         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
150         String JavaDoc path = new String JavaDoc();
151         URL JavaDoc url = null;
152         Template root = null;
153
154         buf.append(DIR_TEMPLATE);
155         buf.append('/');
156         buf.append(getCommandName());
157         buf.append('/');
158         url = this.getClass().getClassLoader().getResource(buf.toString());//dacha&strale
159
// url = ClassLoader.getSystemResource(buf.toString());
160
if (url == null) {
161             System.err.println("");
162             System.err.println("Failed to load resource: " + buf.toString());
163             root = null;
164         } else {
165             root = new Template(url, buf.toString());
166         }
167         return root;
168     }
169
170     public boolean isOverwrite() {
171         return overwrite;
172     }
173
174     public void setOverwrite(boolean b) {
175         overwrite = b;
176     }
177
178     public boolean isEcho() {
179         return echo;
180     }
181
182     public void setEcho(boolean b) {
183         echo = b;
184     }
185
186     public boolean isSwing() {
187         return swing;
188     }
189
190     public void setSwing(boolean b) {
191         swing = b;
192     }
193
194     /**
195      * Get the replacement operations to run against the templates. If this is
196      * null or has a zero length, no replacements are performed during generate().
197      *
198      * @returns
199      * Array of placeholders to search for and the
200      * strings use for replacement.
201      */

202     public ReplacementSet getReplacementSet() {
203         return replacementSet;
204     }
205
206     /**
207      * Set the replacement operations to run against the templates. If this is
208      * not called, called prior to generate(), no replacements are performed.
209      *
210      * @param replacements
211      * Array of placeholders to search for and the
212      * strings use for replacement.
213      */

214     public void setReplacementSet(ReplacementSet replacementSet) {
215         this.replacementSet = replacementSet;
216     }
217
218     /**
219      * Get generator option set
220      *
221      * @return
222      * An option set that you can use to read and write generator
223      * options.
224      */

225     public OptionSet getOptionSet() {
226         return optionSet;
227     }
228
229     public void setOptionSet(OptionSet set) {
230         optionSet = set;
231     }
232
233     /**
234      * Generate application files from a set of templates. This implementation of
235      * the generate method uses the replacements array to perform a search and
236      * replace on generated file names as well as there contents.
237      *
238      * @return
239      * An array of the files that were generated.
240      *
241      * @throws GenerationException
242      * Thrown if unable to generate all the files. Note that generation will fail
243      * if the template directory has not been set.
244      */

245     public File JavaDoc[] generate() throws GeneratorException {
246         initReplacementSet();
247         File JavaDoc[] files = new File JavaDoc[0];
248
249         rootDir = new File JavaDoc(getDestination());
250         fileVector = new Vector JavaDoc();
251         if (getTemplateRoot() == null) {
252             throw new GeneratorException(res.getString("Template_null"));
253         }
254         try {
255             recurseFolders(getTemplateRoot(), rootDir);
256         } catch (ToolException e) {
257             String JavaDoc mess = new String JavaDoc();
258
259             mess = ResUtil.format(res.getString("Failed_to_copy"),
260                                   getTemplateRoot().toString(), rootDir);
261             throw new GeneratorException(e, mess);
262         }
263         storeProperties();
264         files = (File JavaDoc[]) fileVector.toArray(files);
265         fileVector.removeAllElements();
266         return files;
267     }
268
269     // /
270
// / PRIVATE METHODS
271
// /
272

273     /**
274      * Method declaration
275      *
276      *
277      */

278     public void storeProperties() {
279         try {
280             Properties JavaDoc tbProps = ToolBoxInfo.loadProperties();
281             GeneratorOption[] options = getOptionSet().toArray();
282
283             for (int i = 0; i < options.length; i++) {
284                 if (options[i].isPersistent()) {
285                     tbProps.setProperty(getCommandName() + '.'
286                                         + options[i].getName(), options[i].getValue());
287                 }
288             }
289             ToolBoxInfo.storeProperties(tbProps);
290         } catch (ToolException e) {
291
292             // non fatal, just print the stack trace.
293
e.printStackTrace(System.err);
294         }
295     }
296
297     protected String JavaDoc[] getInputIncludes() {
298         String JavaDoc[] includes = new String JavaDoc[1];
299
300         if (ToolBoxInfo.isEnhydra3()) {
301             includes[0] = "3";
302         } else {
303             includes[0] = "4";
304         }
305         return includes;
306     }
307
308     /**
309      * Method declaration
310      *
311      *
312      * @param sourceDir
313      * @param destDir
314      *
315      * @exception java.io.IOException
316      */

317     private void recurseFolders(Template source, File JavaDoc dest)
318             throws ToolException, GeneratorException {
319         Template[] toolList = new Template[0];
320         Template[] copyList = new Template[0];
321         File JavaDoc[] output = new File JavaDoc[0];
322         ConfigTool tool = null;
323         String JavaDoc destPath = null;
324
325         tool = new ConfigTool();
326         tool.addTemplateListener(this);
327         tool.setReplacements(replacementSet.toArray());
328         tool.setOverwrite(isOverwrite());
329         tool.setEcho(isEcho());
330         if (isSwing()) {
331             tool.setOwner(new JFrame JavaDoc());
332         }
333         toolList = source.listTemplates(createTemplateFilter(tool));
334         copyList = source.listTemplates(createCopyFilter(tool));
335         destPath = dest.getAbsolutePath();
336         destPath = tool.lineSearchAndReplace(destPath);
337         dest = new File JavaDoc(destPath);
338
339         // copy non-templates
340
if (copyList != null) {
341             for (int i = 0; i < copyList.length; i++) {
342                 if (copyList[i].isDirectory()) {
343                     File JavaDoc nextDest = null;
344
345                     nextDest = new File JavaDoc(dest, copyList[i].getName());
346                     recurseFolders(copyList[i], nextDest);
347                 } else {
348                     dest.mkdirs();
349                     File JavaDoc outCopy = null;
350                     outCopy = FileUtil.copy(copyList[i], dest);
351                     if (isEcho()) {
352                         PathHandle path =
353                             PathHandle.createPathHandle(outCopy);
354
355                         System.out.println("Copying file to: "
356                                            + path.getPath());
357                     }
358                     fileVector.addElement(outCopy);
359                 }
360             }
361         }
362
363         // process templates
364
if (toolList != null && toolList.length > 0) {
365             tool.setTemplates(toolList);
366             Replacement[] pathReplacements = new Replacement[0];
367             String JavaDoc outPath = new String JavaDoc();
368
369             if (tool.getTemplates()[0].getOutput().isDirectory()) {
370                 outPath =
371                     tool.getTemplates()[0].getOutput().getAbsolutePath();
372             } else {
373                 outPath = tool.getTemplates()[0].getOutput().getParent();
374             }
375             pathReplacements =
376                 createReplacementsForDirectory(PathHandle.createPathHandle(outPath));
377             tool.setReplacements(pathReplacements);
378             output = tool.createOutput();
379             overwrite = tool.isOverwrite();
380             for (int i = 0; i < output.length; i++) {
381                 fileVector.addElement(output[i]);
382             }
383             for (int i = 0; i < toolList.length; i++) {
384                 if (toolList[i].isDirectory()) {
385                     File JavaDoc nextDest = null;
386
387                     nextDest = new File JavaDoc(dest, toolList[i].getName());
388                     recurseFolders(toolList[i], nextDest);
389                 }
390             }
391         }
392     }
393
394 }
395
Popular Tags