KickJava   Java API By Example, From Geeks To Geeks.

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


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.codegen.wizard.CodeGenWizard;
29 import org.enhydra.tool.codegen.wizard.CodeGenPage;
30 import org.enhydra.tool.codegen.internal.Enhydra3AppGenerator;
31 //Zeljko Kovacevic comment this 30.10 2003
32
//import org.enhydra.tool.codegen.internal.ServiceGenerator;
33
import org.enhydra.tool.codegen.internal.WebAppGenerator;
34 import org.enhydra.tool.common.ToolException;
35 import org.enhydra.tool.common.SwingUtil;
36 import org.enhydra.tool.common.ResUtil;
37
38 // Standard imports
39
import java.io.File JavaDoc;
40 import java.io.FileInputStream JavaDoc;
41 import java.io.FileOutputStream JavaDoc;
42 import java.util.Properties JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.beans.Beans JavaDoc;
45 import java.awt.Component JavaDoc;
46 import java.awt.Dialog JavaDoc;
47 import java.awt.Frame JavaDoc;
48 import javax.swing.JOptionPane JavaDoc;
49 import java.util.ResourceBundle JavaDoc;
50
51 /**
52  * Main class for CodeGen wizard and command line interface.
53  */

54 public class CodeGen implements Constants {
55
56     /**
57      * When the debug flag is true, stack traces are printed
58      * for all exceptions.
59      */

60     static ResourceBundle JavaDoc res =
61         ResourceBundle.getBundle("org.enhydra.tool.codegen.Res");
62     public static boolean debug = false;
63
64     /**
65      * When the verbose flag is true, file names stream out
66      * during file operations.
67      */

68     public static boolean verbose = false;
69
70     //
71
private static final String JavaDoc GENERATOR = "external.generator"; // nores
72
private static final String JavaDoc CLASS_WEB_GEN =
73         "org.enhydra.tool.codegen.internal.WebAppGenerator"; // nores
74
private static final String JavaDoc CLASS_EN3_GEN =
75         "org.enhydra.tool.codegen.internal.Enhydra3AppGenerator"; // nores
76
//Zeljko Kovacevic comment this 30.10 2003
77
/* private static final String CLASS_SERVICE_GEN =
78         "org.enhydra.tool.codegen.internal.ServiceGenerator"; // nores
79 */

80     //
81
private Generator[] generators = new Generator[0];
82     private Generator selection = null;
83     private Properties JavaDoc properties = new Properties JavaDoc();
84     private int option = JOptionPane.CANCEL_OPTION;
85     private boolean swing = false;
86
87     //
88
// PUBLIC CONSTRUCTORS
89
//
90

91     /**
92      * Create an Code Generator in command line mode so that no
93      * swing components are instantiated.
94      *
95      * @throws GeneratorException
96      * Thrown if no generators could be instantiated. Warnings
97      * print out for each generators that could not be instantiated.
98      */

99     public CodeGen() throws GeneratorException {
100         this(false);
101     }
102
103     /**
104      * Create an Code Generator and read in the
105      * codegen.properties file. Use Beans instantiate to
106      * create instances of each generator listed in
107      * codegen.properties. Also pass the properties object
108      * into each generator.
109      *
110      * @throws GeneratorException
111      * Thrown if no generators could be instantiated. Warnings
112      * print out for each generators that could not be instantiated.
113      *
114      * @param swing
115      * If true, swing components will be used for user interaction.
116      */

117     public CodeGen(boolean useSwing) throws GeneratorException {
118         setSwing(useSwing);
119         readProperties();
120         initGenerators();
121         if (generators.length == 0) {
122             throw new GeneratorException(res.getString("No_generators"));
123         }
124     }
125
126     /**
127      * Create a Code Generator using a specified implementation
128      * of the Generator class. This constructor is used by Kelp
129      * to create seperate wizards for each generator.
130      *
131      * @throws GeneratorException
132      * Thrown if properties fail to initialize.
133      *
134      * @param selection
135      * The generator implementation to use for all
136      * generation operations.
137      */

138     public CodeGen(Generator sel) throws GeneratorException {
139         selection = sel;
140         setSwing(true);
141         readProperties();
142         generators = new Generator[1];
143         generators[0] = selection;
144         selection.setProperties(properties);
145     }
146
147     //
148
// PUBLIC METHODS
149
//
150
public boolean isSwing() {
151         return swing;
152     }
153
154     public void setSwing(boolean b) {
155         swing = b;
156     }
157
158     /**
159      * Get an integer representing the button selected
160      * by the use to close the wizard dialog.
161      *
162      * @return
163      * CodeGenDialog.CHOICE_FINISH or CodeGenDialog.CHOICE_CANCEL.
164      * The CHOICE_FINISH value indicates that code generation was
165      * attempted.
166      */

167     public int getOption() {
168         return option;
169     }
170
171     /**
172      * Get generator implementation to use for all generation
173      * operations.
174      *
175      * @return
176      * A specific implementation of the generator interface.
177      */

178     public Generator getSelection() {
179         return selection;
180     }
181
182     public void setSelection(Generator sel) {
183       selection = sel;
184     }
185
186     /**
187      * Open the wizard dialog where a user can select what generator
188      * to use, specify generation options and generate the project.
189      *
190      * @param host
191      * A component that can act as the owner of the modal dialog. May be
192      * null, Frame or Dialog.
193      *
194      * @return
195      * Returns an array of generated file references.
196      */

197     public File JavaDoc[] invokeWizard(Component JavaDoc host) {
198         CodeGenWizard wizard = null;
199         File JavaDoc[] files = new File JavaDoc[0];
200
201         wizard = new CodeGenWizard(this);
202         if (selection != null) {
203             try {
204                 wizard.setSelection(selection);
205             } catch (GeneratorException e) {
206                 JOptionPane.showMessageDialog(host, e.getMessage(),
207                                               res.getString("Unable_to_set"),
208                                               JOptionPane.ERROR_MESSAGE);
209                 if (CodeGen.debug) {
210                     e.printStackTrace();
211                 }
212             }
213         }
214         option = wizard.showDialog(host);
215         files = wizard.getGeneratedFiles();
216         if (option == JOptionPane.CANCEL_OPTION) {
217
218             // done
219
} else {
220             if (files == null || files.length == 0) {
221                 JOptionPane.showMessageDialog(host,
222                                               res.getString("No_files_generated_"),
223                                               res.getString("AppWizard_Complete"),
224                                               JOptionPane.WARNING_MESSAGE);
225             } else {
226                 String JavaDoc parentPath = files[0].getParent();
227
228                 for (int i = 0; i < files.length; i++) {
229                     if (files[i].getParent().length() < parentPath.length()) {
230                         parentPath = files[i].getParent();
231                     }
232                 }
233                 String JavaDoc mess =
234                     ResUtil.format(res.getString("Generated_0_files_in"),
235                                    (new String JavaDoc()) + files.length, parentPath);
236
237                 JOptionPane.showMessageDialog(host, mess,
238                                               res.getString("AppWizard_Complete"),
239                                               JOptionPane.INFORMATION_MESSAGE);
240             }
241         }
242         return files;
243     }
244
245     // /
246
// / PRIVATE STATIC
247
// /
248

249     /**
250      * Method declaration
251      *
252      * @exception GeneratorException
253      */

254     private void createProperties() throws GeneratorException {
255
256         // create default property set
257
Properties JavaDoc prop = new Properties JavaDoc();
258         File JavaDoc file = null;
259
260         try {
261             file = ToolBoxInfo.storeProperties(prop);
262             System.out.println(ResUtil.format(res.getString("Configuration"),
263                                               file));
264         } catch (Exception JavaDoc e) {
265             throw new GeneratorException(e,
266                                          ResUtil.format(res.getString("Unable_to_write_file"),
267                                                         ToolBoxInfo.getPropertyFilename()));
268         }
269     }
270
271     // /
272
// / PRIVATE
273
// /
274
public void setGenerators(Generator[] g) {
275         generators = g;
276     }
277
278     public Generator[] getGenerators() {
279         return generators;
280     }
281
282     /**
283      * Method declaration
284      *
285      */

286     public void initGenerators() throws GeneratorException {
287         String JavaDoc className;
288         Object JavaDoc newObject;
289         ArrayList JavaDoc gList = new ArrayList JavaDoc();
290         int validCount = 0;
291
292         // read exteneral generators
293
for (int i = 0; i < 100; i++) {
294             className = properties.getProperty(GENERATOR + '.' + i);
295             newObject = null;
296             if (className != null && className.trim().length() > 0) {
297                 try {
298                     newObject = Beans.instantiate(getClass().getClassLoader(),
299                                                   className);
300                 } catch (Exception JavaDoc e) {
301                     newObject = null;
302                     System.out.println(ResUtil.format(res.getString("AppWizard_Warning"),
303                                                       className));
304                     if (CodeGen.debug) {
305                         System.out.println(TAB4 + e.toString());
306                     }
307                 }
308                 if (newObject != null) {
309                     if (newObject instanceof Generator) {
310                         gList.add((Generator) newObject);
311                     } else {
312                         System.out.println(ResUtil.format(res.getString("AppWizard_Warning_Not"),
313                                                           className));
314                     }
315                 }
316             }
317         }
318         
319         
320         // Slobodan Vujasinovic 28.04.2005.
321
// Enhydra Application generator moved at first place
322
gList.add(new Enhydra3AppGenerator());
323
324         // add internal generators
325
gList.add(new WebAppGenerator());
326 //Zeljko Kovacevic comment this 30.10 2003
327
/* if (!ToolBoxInfo.isEnhydra3()) {
328             gList.add(new ServiceGenerator());
329         }
330 */

331         //gList.add(new Enhydra3AppGenerator());
332
// Slobodan Vujasinovic 28.04.2005.
333

334         for (int i = 0; i < gList.size(); i++) {
335             Generator current = null;
336
337             current = (Generator) gList.get(i);
338             try {
339                 current.setProperties(properties);
340                 current.setSwing(isSwing());
341                 validCount++;
342             } catch (GeneratorException e) {
343                 System.out.println(ResUtil.format(res.getString("Invalid_generator_0_"),
344                                                   current.getCommandName()));
345                 System.out.println(e.getMessage());
346                 gList.set(i, new Object JavaDoc());
347             }
348         }
349         if (validCount == 0) {
350             throw new GeneratorException(res.getString("No_generators1"));
351         } else {
352             generators = new Generator[validCount];
353         }
354         validCount = 0;
355         for (int i = 0; i < gList.size(); i++) {
356             if (gList.get(i) instanceof Generator) {
357                 generators[validCount] = (Generator) gList.get(i);
358                 validCount++;
359             }
360         }
361         gList.clear();
362     }
363
364     /**
365      * Method declaration
366      *
367      */

368     protected void list() {
369         int count = generators.length;
370
371         System.out.println(new String JavaDoc());
372         if (count < 1) {
373             System.out.println(res.getString("No_generators_to_list"));
374         } else {
375             System.out.println(res.getString("Available_generators_"));
376             for (int i = 0; i < count; i++) {
377                 System.out.println(TAB4 + generators[i].getCommandName());
378             }
379             System.out.println(new String JavaDoc());
380             System.out.println(res.getString("Generator"));
381             for (int i = 0; i < count; i++) {
382                 StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
383
384                 buf.append(generators[i].getCommandName());
385                 buf.append(TAB4);
386                 buf.append(generators[i].getDisplayName());
387                 buf.append('\n');
388                 buf.append(generators[i].getDescription());
389                 buf.append('\n');
390                 System.out.println(buf.toString());
391             }
392         }
393         System.out.println(new String JavaDoc());
394     }
395
396     /**
397      * Method declaration
398      *
399      *
400      * @param args
401      */

402     protected void invokeGenerator(String JavaDoc[] args) throws GeneratorException {
403         File JavaDoc[] files = new File JavaDoc[0];
404
405         initSelection(args[0]);
406         if (selection == null) {}
407
408         // do nothing
409
else {
410             processGeneratorOptions(args);
411             System.out.println(ResUtil.format(res.getString("Generator_0_"),
412                                               selection.getCommandName()));
413             GeneratorOption[] options = selection.getOptionSet().toArray();
414
415             for (int i = 0; i < options.length; i++) {
416                 if (options[i].isRequired() || CodeGen.verbose) {
417                     System.out.println(options[i].getDisplayName() + ':'
418                                        + ' ' + options[i].getValue());
419                 }
420             }
421             files = selection.generate();
422             System.out.println(ResUtil.format(res.getString("File_count_0_"),
423                                               files.length));
424         }
425     }
426
427     /**
428      * Method declaration
429      *
430      * @param args
431      * @exception GeneratorException
432      */

433     private void processGeneratorOptions(String JavaDoc[] args)
434             throws GeneratorException {
435
436         // Do basic validation and update option set
437
// with argument values.
438
GeneratorOption[] options = selection.getOptionSet().toArray();
439
440         // Clear out values for required items.
441
for (int i = 0; i < options.length; i++) {
442             if (options[i].isRequired()) {
443                 options[i].clearValue();
444             }
445         }
446
447         // Report any arguments we don't recognize and will ignore.
448
for (int i = 1; i < args.length; i++) {
449             if ((args[i].length() > 0) && (args[i].charAt(0) == '-')) {
450                 boolean found = false;
451
452                 // it is a name.
453
for (int j = 0; j < options.length; j++) {
454                     String JavaDoc paramName = '-' + options[j].getName();
455
456                     if (paramName.equalsIgnoreCase(args[i])) {
457                         found = true;
458                         if (options[j].isBoolean()) {
459                             options[j].setValue((new Boolean JavaDoc(true)).toString());
460                         } else if (i + 1 < args.length) {
461                             options[j].setValue(args[i + 1]);
462                         }
463                     }
464                 }
465                 if (!found) {
466                     System.out.println(ResUtil.format(res.getString("Ignoring_unrecognized"),
467                                                       args[i]));
468                 }
469             }
470         }
471         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
472         boolean missing = false;
473
474         for (int j = 0; j < options.length; j++) {
475             if (options[j].isRequired()) {
476                 if (options[j].isEmpty()) {
477                     if (!missing) {
478                         missing = true;
479                         buf.append(res.getString("Required_value"));
480                         buf.append('\n');
481                     }
482                     buf.append(TAB4);
483                     buf.append('-');
484                     buf.append(options[j].getName());
485                     buf.append('\n');
486                 }
487             }
488         }
489         if (buf.length() > 0) {
490             buf.append('\n');
491             buf.append(res.getString("For_more_information"));
492             buf.append(' ');
493             buf.append(selection.getCommandName());
494             throw new GeneratorException(buf.toString());
495         }
496
497         // do something wonderful
498
}
499
500     /**
501      * Method declaration
502      *
503      * @param commandName
504      */

505     private void initSelection(String JavaDoc commandName) throws GeneratorException {
506         selection = null;
507         for (int i = 0; i < generators.length; i++) {
508             if (generators[i].getCommandName().equalsIgnoreCase(commandName)) {
509                 selection = generators[i];
510                 break;
511             }
512         }
513         if (selection == null) {
514             System.out.println(ResUtil.format(res.getString("_0_is_not_a_valid"),
515                                               commandName));
516         }
517     }
518
519     /**
520      * Method declaration
521      *
522      *
523      * @exception GeneratorException
524      */

525     private void readProperties() throws GeneratorException {
526         String JavaDoc fn = ToolBoxInfo.getPropertyFilename();
527         File JavaDoc file = new File JavaDoc(fn);
528
529         if (!file.exists()) {
530             createProperties();
531         }
532         try {
533             properties = ToolBoxInfo.loadProperties();
534         } catch (ToolException e) {
535             throw new GeneratorException(e, res.getString("Unable_to_read"));
536         }
537     }
538
539     /**
540      * Method declaration
541      *
542      * @param commandName
543      */

544     protected void showGeneratorOptionHelp(String JavaDoc commandName) {
545         try {
546             initSelection(commandName);
547         } catch (GeneratorException e) {
548             e.printStackTrace();
549         }
550         if (selection == null) {
551             System.out.println(ResUtil.format(res.getString("Unable_to_show"),
552                                               commandName));
553         } else {
554             GeneratorOption[] options = selection.getOptionSet().toArray();
555
556             if (options.length == 0) {
557                 System.out.println(ResUtil.format(res.getString("No_options_available"),
558                                                   commandName));
559             } else {
560                 for (int i = 0; i < options.length; i++) {
561                     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
562
563                     buf.append(' ');
564                     buf.append('-');
565                     buf.append(options[i].getName());
566                     if (options[i].isBoolean()) {
567
568                         // skip placeholder
569
} else {
570                         buf.append(' ');
571                         buf.append(options[i].getDisplayName());
572                     }
573                     buf.append(TAB4);
574                     buf.append(options[i].getDescription());
575                     System.out.println(buf.toString());
576                 }
577             }
578         }
579     }
580
581 }
582
Popular Tags