KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > finalist > jag > JApplicationGen


1 /* Copyright (C) 2003 Finalist IT Group
2  *
3  * This file is part of JAG - the Java J2EE Application Generator
4  *
5  * JAG is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * JAG is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  * You should have received a copy of the GNU General Public License
14  * along with JAG; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16  */

17
18 package com.finalist.jag;
19
20 import com.finalist.jag.util.DirectoryIterator;
21 import com.finalist.jag.util.Log;
22 import com.finalist.jag.util.TemplateEngine;
23 import com.finalist.jaggenerator.ConsoleLogger;
24 import com.finalist.jaggenerator.JagGenerator;
25 import com.finalist.jaggenerator.LibCopier;
26 import com.finalist.jaggenerator.modules.Paths;
27 import com.finalist.jaggenerator.modules.Config;
28 import com.finalist.jaggenerator.template.Template;
29
30 import java.io.*;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Collection JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.Iterator JavaDoc;
35
36 import org.apache.commons.logging.LogFactory;
37 import org.apache.log4j.lf5.LogLevel;
38
39
40 /**
41  * This class is responsible for generating the J2EE project from the application file specified in the GUI.
42  * Originally this was a console-based Java app, seperate from the GUI.
43  *
44  */

45 public class JApplicationGen {
46
47    static org.apache.commons.logging.Log log = LogFactory.getLog(JApplicationGen.class);
48
49    private Boolean JavaDoc overwrite = null;
50    private static ConsoleLogger logger;
51    private static final String JavaDoc CVS_DIR = "CVS";
52    public static final String JavaDoc OPTION_YES = "Yes";
53    public static final String JavaDoc OPTION_NO = "No";
54    public static final String JavaDoc OPTION_YES_ALL = "Yes to all";
55    public static final String JavaDoc OPTION_NO_ALL = "No to all";
56    public static final String JavaDoc OPTION_VIEW_DIFF = "View Diff";
57    public static final Object JavaDoc[] DIALOGUE_OPTIONS =
58          {OPTION_YES, OPTION_NO, OPTION_YES_ALL, OPTION_NO_ALL, OPTION_VIEW_DIFF};
59
60    /** Jag command line option */
61    private static final String JavaDoc SVIEW = "-sview";
62
63    private static String JavaDoc outputDir = "";
64    private static String JavaDoc applicationFile = "Skelet.xml";
65    private static boolean displaySkeletView = false;
66    private static boolean exitOnFinish = false;
67
68
69    /**
70     * Constructor JApplicationGen
71     *
72     *
73     * @param property
74     *
75     */

76    public JApplicationGen(String JavaDoc[] property) {
77       if (property.length > 0) {
78          JApplicationGen.outputDir = property[0];
79          log.debug("Output dir is: " + this.outputDir);
80
81       }
82
83       if (property.length > 1) {
84          this.applicationFile = property[1];
85          log.debug("project file: : " + this.applicationFile);
86       }
87
88    }
89
90    /**
91     * Method main
92     *
93     * @param args
94     */

95    public static void main(String JavaDoc args[]) {
96       try {
97          long seconds = System.currentTimeMillis();
98          Log.setLogger(logger);
99          if (args.length < 1) {
100             log("[Error] Invalid command line : JApplicationGen <outputpath> <skeletfile> <overwrite>");
101             return;
102          }
103          Boolean JavaDoc overwrite = null;
104          if (args.length >2 ) {
105             overwrite = new Boolean JavaDoc(args[2]);
106             log("Overwrite mode is: " + args[2]);
107          }
108          if (args.length >3 ) {
109             exitOnFinish = new Boolean JavaDoc(args[3]).booleanValue();
110          }
111          JApplicationGen jag = new JApplicationGen(args);
112          if (JagGenerator.jagGenerator == null) {
113             JagGenerator.jagGenerator = new JagGenerator();
114             if (exitOnFinish) {
115                JagGenerator.jagGenerator.setVisible(false);
116
117                // TextConsole is required for command line generation!
118
JagGenerator.jagGenerator.setLogger(new ConsoleLogger(JagGenerator.jagGenerator.textConsole));
119             }
120             JagGenerator.jagGenerator.loadApplicationFile(new File(args[1]));
121             JagGenerator.jagGenerator.save();
122          }
123
124          Template template = JagGenerator.jagGenerator.root.config.selectedTemplate;
125          log.info("Generate using template: " + template.getTemplateDir());
126          TemplateEngine engine = null;
127          try {
128             engine = (TemplateEngine) Class.forName(
129                   template.getEngineClass()).newInstance();
130          } catch (Exception JavaDoc e) {
131             log("Error! The specified template engine '" +
132                 template.getEngineClass() +
133                 "' can't be loaded (" + e + "). Using the default engine..");
134             try {
135                engine = (TemplateEngine) Class.forName(
136                      Template.DEFAULT_ENGINE_CLASS).newInstance();
137                if (overwrite != null)
138                engine.setOverwrite(overwrite);
139
140             } catch (Exception JavaDoc e1) {
141                log("FATAL! default template engine can't be loaded (" + e1 + "). Aborting.");
142                System.exit(1);
143             }
144          }
145
146          int totalNumberOfNewFiles = engine.process(
147                      jag.getTemplateFiles(template.getTemplateDir().getAbsolutePath()),
148                      outputDir);
149
150
151          seconds = System.currentTimeMillis() - seconds;
152          seconds = seconds / 1000;
153          log("\nTotal number of new files : " + totalNumberOfNewFiles);
154
155          log("\nStart copying required jar files..");
156          try {
157             File outputLibDirectory = new File(args[0]+File.separator+"lib");
158             if (!outputLibDirectory.exists()) {
159                // Create the output lib directory
160
if (!outputLibDirectory.mkdir()) {
161                    log("Failed to create the directory: "+outputLibDirectory);
162                 }
163             }
164
165             HashMap JavaDoc failedCopies = LibCopier.copyJars(args[0]+File.separator+JagGenerator.jagGenerator.root.paths.getConfigOutput()+File.separator+"lib.xml", args[0]+File.separator+"lib");
166             if (failedCopies == null) {
167                log("\nError occured while copying the required jar files.");
168             } else if (failedCopies.size() > 0) {
169                // Not all jars could be copied
170
log("\nSome required jar files couldn't be copied from JAG.\nPlease add the following jars to the JAG lib directory:\n");
171                boolean j2eeJarMissing = false;
172                for (Iterator iterator = failedCopies.keySet().iterator(); iterator.hasNext();) {
173                   String JavaDoc fileName = (String JavaDoc) iterator.next();
174                   String JavaDoc url = (String JavaDoc) failedCopies.get(fileName);
175                   log(" - "+fileName+" : "+url);
176                   if ("j2ee.jar".equalsIgnoreCase(fileName)) {
177                      j2eeJarMissing = true;
178                   }
179                   log("");
180                }
181                if (j2eeJarMissing) {
182                   log("\nThe j2ee.jar is missing because it isn't distributed with JAG because the j2ee.jar is no open source jar file.");
183                   log("Please download the j2ee.jar from the http://java.sun.com site or from for example a JBoss installation.");
184                }
185             } else {
186                log("\nSuccessfully finished copying the required jar files.");
187             }
188
189          } catch (Exception JavaDoc e) {
190             log("\n\nAn error occured while copying the required jar files.\n");
191             e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
192
}
193          log("Process finished in " + seconds + " seconds");
194       } catch (InterruptedException JavaDoc e) {
195          try {
196             log("INTERRUPTED BY USER - ABORTED!");
197             if (exitOnFinish) {
198                System.exit(-1);
199             }
200          } catch (InterruptedException JavaDoc e1) {
201          }
202       } finally {
203          JagGenerator.finishedGeneration();
204          if (exitOnFinish) {
205             System.exit(0);
206          }
207       }
208    }
209
210    /**
211     * Copies all the source files from the specified template directory to the output directory,
212     * not including any CVS directories.
213     *
214     * @param templatePath
215     * @throws InterruptedException
216     */

217    public static void createOutputStructure(String JavaDoc templatePath) throws InterruptedException JavaDoc {
218       try {
219          templatePath = new File(templatePath).getCanonicalPath();
220          templatePath = templatePath.replace('\\', '/');
221          File file = null;
222          Paths paths = (Paths) JagGenerator.getObjectsFromTree(Paths.class).get(0);
223          Config config = (Config) JagGenerator.getObjectsFromTree(Config.class).get(0);
224          DirectoryIterator iterator = new DirectoryIterator(templatePath, true, true);
225          while ((file = iterator.getNext()) != null) {
226             boolean copyFile = false;
227             //don't copy CVS files!
228
String JavaDoc fullFilename = file.getCanonicalPath();
229             int lastDirPos = fullFilename.lastIndexOf(System.getProperty("file.separator"));
230             if (CVS_DIR.equals(file.getCanonicalPath().
231                   substring(fullFilename.length() - CVS_DIR.length(), fullFilename.length())) ||
232                                                                                               CVS_DIR.equals(fullFilename.substring(lastDirPos - CVS_DIR.length(), lastDirPos))) {
233                continue;
234             }
235              if ("readme.txt".equals(file.getName())) {
236                  continue;
237              }
238             String JavaDoc fileOut = outputDir.replace('\\', '/');
239             String JavaDoc path = file.getCanonicalPath().replace('\\', '/');
240
241
242             if (path.indexOf(templatePath) == 0) {
243                path = path.substring(templatePath.length());
244                // Now check if it is one of the sources. THe should be copied to the configured paths.
245

246                //@TODO make this more generic.
247
// Somehow define the different mappings.
248
//
249
// In the template source directory is checked if relevant sources should be copied.
250

251                /////////////////////
252
//// CONFIG SOURCES
253
/////////////////////
254
if (path.startsWith(Paths.CONF_GENERAL_DIR)) {
255                   // Generic configuration files.
256
path = paths.getConfigOutput() + path.substring(Paths.CONF_GENERAL_DIR.length());
257                   copyFile = true;
258                }
259                else if (path.startsWith(Paths.CONF_STRUTS_DIR)) {
260                    // Struts specific configuration files.
261
path = paths.getConfigOutput() + path.substring(Paths.CONF_STRUTS_DIR.length());
262                    copyFile = true;
263                }
264                else if (path.startsWith(Paths.CONF_TAPESTRY4_DIR)) {
265                    // Tapestry specific configuration files.
266
path = paths.getConfigOutput() + path.substring(Paths.CONF_TAPESTRY4_DIR.length());
267                    copyFile = true;
268                }
269                else if (path.startsWith(Paths.CONF_SWING_DIR)) {
270                    // Swing specific configuration files.
271
path = paths.getConfigOutput() + path.substring(Paths.CONF_SWING_DIR.length());
272                    copyFile = true;
273                }
274
275
276
277                /////////////////////////////////////
278
// PRESENTATION TIER SOURCES
279
/////////////////////////////////////
280
else if (path.startsWith(Paths.JAVA_WEB_STRUTS_DIR)) {
281                   path = paths.getJspOutput() + path.substring(Paths.JAVA_WEB_STRUTS_DIR.length());
282                   if (config.matchWebTier("struts").booleanValue()) {
283                      copyFile = true;
284                   }
285                }
286                else if (path.startsWith(Paths.JAVA_WEB_TAPESTRY4_DIR)) {
287                   path = paths.getJspOutput() + path.substring(Paths.JAVA_WEB_TAPESTRY4_DIR.length());
288                   if (config.matchWebTier("tapestry").booleanValue()) {
289                      copyFile = true;
290                   }
291                }
292                else if (path.startsWith(Paths.JAVA_SWING_DIR)) {
293                   path = paths.getSwingOutput() + path.substring(Paths.JAVA_SWING_DIR.length());
294                   if (config.matchWebTier("swing").booleanValue()) {
295                      copyFile = true;
296                   }
297                }
298                else if (path.startsWith(Paths.JAVA_STRUTS_DIR)) {
299                   path = paths.getWebOutput() + path.substring(Paths.JAVA_STRUTS_DIR.length());
300                   if (config.matchWebTier("struts").booleanValue()) {
301                      copyFile = true;
302                   }
303                }
304                else if (path.startsWith(Paths.JAVA_TAPESTRY4_DIR)) {
305                   path = paths.getWebOutput() + path.substring(Paths.JAVA_TAPESTRY4_DIR.length());
306                   if (config.matchWebTier("tapestry").booleanValue()) {
307                      copyFile = true;
308                   }
309                }
310
311
312                //////////////////////////////////
313
// Business tier sources..
314
//////////////////////////////////
315
else if (path.startsWith(Paths.JAVA_EJB2_DIR)) {
316                   path = paths.getEjbOutput() + path.substring(Paths.JAVA_EJB2_DIR.length());
317                   if (config.matchBusinessTier("ejb 2").booleanValue()) {
318                      copyFile = true;
319                   }
320                }
321                else if (path.startsWith(Paths.JAVA_EJB3_DIR)) {
322                   path = paths.getEjbOutput() + path.substring(Paths.JAVA_EJB3_DIR.length());
323                   if (config.matchBusinessTier("ejb 3").booleanValue()) {
324                      copyFile = true;
325                   }
326                }
327                else if (path.startsWith(Paths.JAVA_HIBERNATE2_DIR)) {
328                   path = paths.getHibernateOutput() + path.substring(Paths.JAVA_HIBERNATE2_DIR.length());
329                   if (config.matchBusinessTier("hibernate 2").booleanValue()) {
330                      copyFile = true;
331                   }
332                }
333                else if (path.startsWith(Paths.JAVA_HIBERNATE3_DIR)) {
334                   path = paths.getHibernateOutput() + path.substring(Paths.JAVA_HIBERNATE3_DIR.length());
335                   if (config.matchBusinessTier("hibernate 3").booleanValue()) {
336                      copyFile = true;
337                   }
338                }
339
340
341                ////////////////////////////
342
// MOCK Tier.
343
/////////////////////////////
344
else if (path.startsWith(Paths.JAVA_MOCK_DIR)) {
345                   path = paths.getMockOutput() + path.substring(Paths.JAVA_MOCK_DIR.length());
346                   if (config.useMock().booleanValue()) {
347                      copyFile = true;
348                   }
349                }
350
351
352                ///////////////////////////////
353
// SERVICE TIER
354
///////////////////////////////
355
else if (path.startsWith(Paths.JAVA_SERVICE_DIR)) {
356                   path = paths.getServiceOutput() + path.substring(Paths.JAVA_SERVICE_DIR.length());
357                    // Will always be copied!
358
copyFile = true;
359                }
360
361                else if (path.startsWith(Paths.JAVA_TEST_DIR)) {
362                   path = paths.getTestOutput() + path.substring(Paths.JAVA_TEST_DIR.length());
363                   // Will always be copied.
364
copyFile = true;
365                }
366
367                else if ((path.indexOf("build.bat") != -1) || ((path.indexOf("deploy.bat") != -1))) {
368                   copyFile = true;
369                }
370             }
371
372             // On linux this would otherwise fail in case a path starts with a . !
373
if (!path.startsWith("/")) {
374                 path = "/" + path;
375             }
376
377             // Only copy the file if the relevant business/web tier was selected
378
if (copyFile) {
379                fileOut += path;
380                path = outputDir + path;
381                if (!file.isDirectory()) {
382                   String JavaDoc name = file.getName();
383                   path = path.substring(0, (path.length() - name.length()));
384                }
385
386                new File(path).mkdirs();
387                if (!file.isDirectory()) {
388                   byte array[] = new byte[1024];
389                   int size = 0;
390                   try {
391                      BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
392                      BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileOut));
393
394                      while ((size = in.read(array)) != -1)
395                         out.write(array, 0, size);
396                      in.close();
397                      out.flush();
398                      out.close();
399                   } catch (Exception JavaDoc exc) {
400                      log("[Error] Copy output file failed : " + fileOut);
401                      log(exc.getMessage());
402                   }
403                }
404             }
405          }
406       } catch (Exception JavaDoc exc) {
407          log.error("Error while copying files: ", exc);
408          log(exc.getMessage());
409       }
410    }
411
412    /**
413     * Returns a collection of File for all *.jag files in
414     * the given directory.
415     */

416    private Collection JavaDoc getTemplateFiles(String JavaDoc path) {
417       ArrayList JavaDoc documents = new ArrayList JavaDoc();
418       DirectoryIterator iterator = new DirectoryIterator(path);
419       File skeletFile = null;
420
421       while ((skeletFile = iterator.getNext()) != null) {
422          if (!skeletFile.getName().endsWith(".vsl"))
423             continue;
424          documents.add(skeletFile);
425       }
426
427       return documents;
428    }
429
430    public static void setLogger(ConsoleLogger a_logger) {
431       logger = a_logger;
432    }
433
434    /**
435     * If the logger is set to the ConsoleLogger and this class has been interrupted by the JAG gui user,
436     * the resulting act of updating the JTextField can cause write lock acquisition errors in the Swing classes.
437     * This method first checks the interrupted status before logging, and throws an exception if appropriate.
438     * @param message
439     * @throws InterruptedException
440     */

441    public static void log(String JavaDoc message) throws InterruptedException JavaDoc {
442       if (Thread.interrupted()) {
443          throw new InterruptedException JavaDoc();
444       }
445       Log.log(message);
446    }
447
448    public static void log(String JavaDoc message, LogLevel level) throws InterruptedException JavaDoc {
449       if (Thread.interrupted()) {
450          throw new InterruptedException JavaDoc();
451       }
452       logger.log(message, level);
453    }
454
455    /**
456     * Gets the application file, retrieved from the GUI.
457     *
458     * @return file name.
459     */

460    public static String JavaDoc getApplicationFile() {
461       return applicationFile;
462    }
463
464    /**
465     * If this property is set, a graphical tree representation of the applicaton XML file is shown
466     * to the user. Originally used for debugging, I think.
467     *
468     * @return true if displayed.
469     */

470    public static boolean isDisplaySkeletView() {
471       return displaySkeletView;
472    }
473
474 }
Popular Tags