KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > generation > start > Main


1
2 package org.objectweb.speedo.generation.start;
3
4 import org.apache.tools.ant.BuildException;
5 import org.apache.tools.ant.DirectoryScanner;
6 import org.apache.tools.ant.Project;
7 import org.apache.tools.ant.taskdefs.MatchingTask;
8 import org.apache.tools.ant.types.Path;
9 import org.objectweb.jorm.api.PException;
10 import org.objectweb.speedo.api.SpeedoException;
11 import org.objectweb.speedo.api.SpeedoProperties;
12 import org.objectweb.speedo.generation.SpeedoCompiler;
13 import org.objectweb.speedo.generation.api.SpeedoCompilerParameter;
14 import org.objectweb.util.monolog.Monolog;
15 import org.objectweb.util.monolog.api.BasicLevel;
16 import org.objectweb.util.monolog.api.Logger;
17
18 import java.io.File JavaDoc;
19 import java.io.IOException JavaDoc;
20 import java.io.PrintWriter JavaDoc;
21 import java.util.ArrayList JavaDoc;
22 import java.util.Collection JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25
26
27 /**
28  * Main is the starting point for the persistent filter tool.
29  */

30 public class Main
31     extends Support
32 {
33     // return values of main()
34
static public final int OK = 0;
35     static public final int USAGE_ERROR = -1;
36     static public final int METADATA_ERROR = -2;
37     static public final int INTERNAL_ERROR = -3;
38
39     protected Logger logger = null;
40     private SpeedoCompilerParameter scp = null;
41     private SpeedoCompiler sc = null;
42     private Description jdodesc = new Description();
43     private Description jormdesc = new Description();
44     private Description awareFiles = new Description();
45     private Project project = new Project();
46     /**
47      * The stream to write messages to.
48      */

49     private final PrintWriter JavaDoc out = new PrintWriter JavaDoc(System.out, true);
50
51     /**
52      * The stream to write error messages to.
53      */

54     private final PrintWriter JavaDoc err = new PrintWriter JavaDoc(System.err, true);
55
56     /**
57      * The command line options.
58      */

59     private final CmdLineOptions opts = new CmdLineOptions();
60
61
62     /**
63      * Construct a filter tool instance
64      */

65     public Main()
66     {}
67
68     // ----------------------------------------------------------------------
69

70     /**
71      * This is where it all starts.
72      */

73     public static void main(String JavaDoc[] argv)
74     {
75         int res;
76         final Main main = new Main();
77         
78         main.sc = new SpeedoCompiler();
79         main.scp = main.sc.getSpeedoCompilerParameter();
80
81         // added support for timing statistics
82
try {
83             res = main.process(argv);
84         } catch (RuntimeException JavaDoc ex) {
85             main.out.flush();
86             main.err.println("Internal error while postprocessing: "
87                              + ex.getMessage());
88             ex.printStackTrace(main.err);
89             main.err.flush();
90             res = INTERNAL_ERROR;
91         } finally {
92             // added support for timing statistics
93
main.logger.log(BasicLevel.DEBUG, "Timing infos...");
94             if (main.opts.doTiming) {
95                 Support.timer.print();
96             }
97         }
98         main.logger.log(BasicLevel.DEBUG, "leaving org.objectweb.speedo.start.Main.main(), ret="+res);
99         System.exit(res);
100     }
101
102     /**
103      * Process command line options and perform filtering tasks
104      */

105     public int process(String JavaDoc[] argv)
106     {
107         int res;
108         if ((res = opts.processArgs(argv)) != OK) {
109             printMessage("aborted with errors.");
110             return res;
111         }
112
113         // added support for timing statistics
114
try {
115             if (opts.doTiming) {
116                 timer.push("Main.process(String[])");
117             }
118
119             if ((res = start()) != OK) {
120                 printMessage("aborted with errors.");
121                 return res;
122             }
123
124             printMessage("done.");
125             return 0;
126         } finally {
127             if (opts.doTiming) {
128                 timer.pop();
129             }
130         }
131     }
132
133     // ----------------------------------------------------------------------
134

135     /**
136      * A class for holding the command line options.
137      */

138     private class CmdLineOptions
139     {
140         String JavaDoc speedoproperties = null;
141     final List JavaDoc classNames = new ArrayList JavaDoc();
142         final List JavaDoc classFileNames = new ArrayList JavaDoc();
143         final List JavaDoc zipFileNames = new ArrayList JavaDoc();
144         final List JavaDoc jdoFileNames = new ArrayList JavaDoc();
145         String JavaDoc sourcePath = null;
146         String JavaDoc destinationDirectory = null;
147         String JavaDoc propertiesFileName = null;
148     String JavaDoc logproperties = null;
149     String JavaDoc inputdir = null;
150         boolean doTiming = false;
151         boolean verbose = false;
152         boolean quiet = false;
153         boolean forceWrite = false;
154         boolean noWrite = false;
155         boolean dumpClass = false;
156         boolean noAugment = false;
157         boolean noAnnotate = false;
158
159         /**
160          * Print a usage message to System.err.
161          */

162         public void usage() {
163             err.println("Usage: main <options> <arguments>...");
164             err.println("Options:");
165             err.println(" -h, --help print usage message and exit gently");
166             err.println(" -v, --verbose print verbose messages");
167             err.println(" -q, --quiet supress warnings");
168         err.println(" -i, --input <dir> input dir");
169         err.println(" -d, --destdir <dir> destination directory for output files");
170             err.println(" -s, --sourcepath <path> source path");
171         err.println(" -sp, --speedoproperties <filepath> Absolute path of the Speedo properties file");
172         err.println(" -log <filepath> Absolute path of the log properties file");
173             err.println(" -f, --force overwrite output files");
174             err.println(" -n, --nowrite never write output files");
175             err.println(" -t, --timing do timing messures");
176             err.println();
177             err.println("Debugging Options:");
178             err.println(" --properties <file> use property file for meta data");
179             err.println(" --dumpclass print out disassembled code of classes");
180             err.println(" --noaugment do not enhance for persistence-capability");
181             err.println(" --noannotate do not enhance for persistence-awareness");
182             err.println();
183             err.println("Arguments:");
184             //err.println(" <class> the fully qualified name of a Java class");
185
err.println(" <jdofile> the name of a .jdo file");
186             err.println(" <classfile> the name of a .class file");
187             //err.println(" <zipfile> the name of a .zip or .jar file");
188
err.println();
189             err.println("Returns a non-zero value in case of errors.");
190         }
191
192         /**
193          * Process command line options.
194          */

195         protected int processArgs(String JavaDoc[] argv)
196         {
197             final Collection JavaDoc inputNames = new ArrayList JavaDoc();
198             for (int i = 0; i < argv.length; i++) {
199                 final String JavaDoc arg = argv[i];
200                 if (arg.equals("-h")
201                     || arg.equals("--help")) {
202                     usage();
203                     return OK;
204                 }
205                 if (arg.equals("-v")
206                     || arg.equals("--verbose")) {
207                     verbose = true;
208                     quiet = false;
209                     continue;
210                 }
211                 if (arg.equals("-sp")
212                     || arg.equals("--speedoproperties")) {
213                         if (argv.length - i < 2) {
214                             printError("Missing argument to the -sp/--speedoproperties option", null);
215                             usage();
216                             return USAGE_ERROR;
217                         }
218                         speedoproperties = argv[++i];
219                         continue;
220                 }
221                 if (arg.equals("-log")) {
222                         if (argv.length - i < 2) {
223                             printError("Missing argument to the -log option", null);
224                             usage();
225                             return USAGE_ERROR;
226                         }
227                         logproperties = argv[++i];
228                         continue;
229                 }
230                 if (arg.equals("-i")
231                      || arg.equals("--input")) {
232                         if (argv.length - i < 2) {
233                             printError("Missing argument to the -i option", null);
234                             usage();
235                             return USAGE_ERROR;
236                         }
237                         inputdir = argv[++i];
238                         continue;
239                  }
240                 if (arg.equals("-q")
241                     || arg.equals("--quiet")) {
242                     quiet = true;
243                     verbose = false;
244                     continue;
245                 }
246                 if (arg.equals("-t") ||
247                     arg.equals("--timing")) {
248                     doTiming = true;
249                     continue;
250                 }
251                 if (arg.equals("-f")
252                     || arg.equals("--force")) {
253                     forceWrite = true;
254                     noWrite = false;
255                     continue;
256                 }
257                 if (arg.equals("-n")
258                     || arg.equals("--nowrite")) {
259                     noWrite = true;
260                     forceWrite = false;
261                     continue;
262                 }
263                 if (arg.equals("--dumpclass")) {
264                     dumpClass = true;
265                     continue;
266                 }
267                 if (arg.equals("--noaugment")) {
268                     noAugment = true;
269                     continue;
270                 }
271                 if (arg.equals("--noannotate")) {
272                     noAnnotate = true;
273                     continue;
274                 }
275                 if (arg.equals("-s")
276                     || arg.equals("--sourcepath")) {
277                     if (argv.length - i < 2) {
278                         printError("Missing argument to the -s/--sourcepath option", null);
279                         usage();
280                         return USAGE_ERROR;
281                     }
282                     sourcePath = argv[++i];
283                     continue;
284                 }
285                 if (arg.equals("-d")
286                     || arg.equals("--destdir")) {
287                     if (argv.length - i < 2) {
288                         printError("Missing argument to the -d/-destdir option", null);
289                         usage();
290                         return USAGE_ERROR;
291                     }
292                     destinationDirectory = argv[++i];
293                     continue;
294                 }
295                 if (arg.equals("--properties")) {
296                     if (argv.length - i < 2) {
297                         printError("Missing argument to the --properties option", null);
298                         usage();
299                         return USAGE_ERROR;
300                     }
301                     propertiesFileName = argv[++i];
302                     continue;
303                 }
304                 if (arg.length() > 0 && arg.charAt(0) == '-') {
305                     printError("Unrecognized option:" + arg, null);
306                     usage();
307                     return USAGE_ERROR;
308                 }
309                 if (arg.length() == 0) {
310                     printMessage("Ignoring empty command line argument.");
311                     continue;
312                 }
313
314                 inputNames.add(arg);
315             }
316
317             // group input file arguments
318
for (Iterator JavaDoc names = inputNames.iterator(); names.hasNext();) {
319                 final String JavaDoc name = (String JavaDoc)names.next();
320                 if (isJdoFileName(name)) {
321                     jdoFileNames.add(name);
322                 } else if (isClassFileName(name)) {
323                     classFileNames.add(name);
324                 } else if (isZipFileName(name)) {
325                     zipFileNames.add(name);
326                 } else {
327                     classNames.add(name);
328                 }
329             }
330
331             if (verbose) {
332                 printArgs();
333             }
334             return checkArgs();
335         }
336
337         /**
338          * Check command line options.
339          */

340         protected int checkArgs()
341         {
342             // at least one meta-data source must be specified for classfiles
343
if (classFileNames.size() > 0
344                 && (jdoFileNames.isEmpty()
345                     && propertiesFileName == null
346                     && sourcePath == null)) {
347                 final String JavaDoc msg
348                     = "No JDO meta-data source specified for class files";
349                 printError(msg, null);
350                 usage();
351                 return USAGE_ERROR;
352             }
353
354             // either jdo files or jdo properties specified
355
if (!jdoFileNames.isEmpty() && propertiesFileName != null) {
356                 final String JavaDoc msg
357                     = "Cannot have both jdo files and properties specified";
358                 printError(msg, null);
359                 usage();
360                 return USAGE_ERROR;
361             }
362
363             return OK;
364         }
365         /**
366          * return command line options.
367          */

368         protected String JavaDoc getArgs() {
369             String JavaDoc classnames = "";
370             for (Iterator JavaDoc i = classNames.iterator(); i.hasNext();) {
371                 classnames.concat(" " + i.next());
372             }
373             String JavaDoc jdonames = "";
374             for (Iterator JavaDoc i = jdoFileNames.iterator(); i.hasNext();) {
375                 jdonames.concat(" " + i.next());
376             }
377             String JavaDoc classfilenames = "";
378             for (Iterator JavaDoc i = classFileNames.iterator(); i.hasNext();) {
379                 classfilenames.concat(" " + i.next());
380             }
381             String JavaDoc zipnames = "";
382             for (Iterator JavaDoc i = zipFileNames.iterator(); i.hasNext();) {
383                 zipnames.concat(" " + i.next());
384             }
385             return "Enhancer: options:"+"\n"+
386             " verbose = " + verbose+"\n"+
387             " quiet = " + quiet+"\n"+
388             " forceWrite = " + forceWrite+"\n"+
389             " noWrite = " + noWrite+"\n"+
390             " inputDirectory = " + inputdir+"\n"+
391             " destinationDirectory = " + destinationDirectory+"\n"+
392             " SpeedopropertiesFileName = " + speedoproperties+"\n"+
393             " doTiming = " + doTiming+"\n"+
394             " classNames = {"+"\n"+classnames+"\n"+
395             " }"+"\n"+
396             " classfilenames = {"+"\n"+classfilenames+"\n"+
397             " }"+"\n"+
398             " jdoFileNames = {"+jdonames+"\n"+
399             " }"+"\n"+
400             " zipnames = {"+"\n"+zipnames+"\n"+
401             " }"+"\n"+
402             " dumpClass = " + dumpClass+"\n"+
403             " noAugment = " + noAugment+"\n"+
404             " noAnnotate = " + noAnnotate;
405         }
406         /**
407          * Print command line options.
408          */

409         protected void printArgs() {
410             out.println("Enhancer: options:");
411             out.println(" verbose = " + verbose);
412             out.println(" quiet = " + quiet);
413             out.println(" forceWrite = " + forceWrite);
414             out.println(" noWrite = " + noWrite);
415             out.println(" inputDirectory = " + inputdir);
416             out.println(" destinationDirectory = " + destinationDirectory);
417             out.println(" SpeedopropertiesFileName = " + speedoproperties);
418             out.println(" doTiming = " + doTiming);
419             out.println(" classNames = {");
420             for (Iterator JavaDoc i = classNames.iterator(); i.hasNext();) {
421                 out.println(" " + i.next());
422             }
423             out.println(" }");
424             out.println(" jdoFileNames = {");
425             for (Iterator JavaDoc i = jdoFileNames.iterator(); i.hasNext();) {
426                 out.println(" " + i.next());
427             }
428             out.println(" classFileNames = {");
429             for (Iterator JavaDoc i = classFileNames.iterator(); i.hasNext();) {
430                 out.println(" " + i.next());
431             }
432             out.println(" }");
433             out.println(" zipFileNames = {");
434             for (Iterator JavaDoc i = zipFileNames.iterator(); i.hasNext();) {
435                 out.println(" " + i.next());
436             }
437             out.println(" }");
438             out.println(" dumpClass = " + dumpClass);
439             out.println(" noAugment = " + noAugment);
440             out.println(" noAnnotate = " + noAnnotate);
441         }
442     }
443
444     private int initParameters()
445     {
446         final String JavaDoc propertiesFileName = opts.propertiesFileName;
447         final List JavaDoc jdoFileNames = opts.jdoFileNames;
448         final List JavaDoc ClassFileNames = opts.classFileNames;
449         final String JavaDoc sourcePath = opts.sourcePath;
450
451         try {
452             scp.logPropFile = opts.logproperties;
453
454             // Initialize the logger factory if necessary
455
try {
456                 if (scp.loggerFactory == null) {
457                     if (scp.logPropFile == null) {
458                         scp.loggerFactory = Monolog.initialize();
459                     } else {
460                         scp.loggerFactory = Monolog.getMonologFactory(scp.logPropFile);
461                     }
462                     logger = scp.loggerFactory.getLogger(SpeedoProperties.LOGGER_NAME+".start.Main");
463                 } else if (logger == null) {
464                     logger = scp.loggerFactory.getLogger(SpeedoProperties.LOGGER_NAME+".start.Main");
465                 }
466             }
467             catch (Exception JavaDoc e){
468                 e.printStackTrace();
469             }
470             logger.log(BasicLevel.DEBUG, "Entering initParameters()");
471             scp.projectName = "";
472             
473             // Setting Classpath
474
scp.classpath = new Path(project, opts.sourcePath);
475             scp.classpath.append(new Path(project, opts.destinationDirectory));
476             scp.jormclasspath = new MyArrayList(scp.classpath.list());
477             
478             // Setting directories (input, output,jdodir jormdir)
479
if (opts.inputdir != null) scp.input = opts.inputdir;
480             else scp.input = (new File JavaDoc(".")).getCanonicalPath();
481             if ( opts.destinationDirectory != null) scp.output = opts.destinationDirectory;
482             else scp.output = scp.input;
483             
484             scp.jormDir = scp.input;
485             scp.jdoDir ="file:/"+ scp.input;
486             scp.awareFilesDir = scp.input;
487
488             // Verifying the accessibility of jorm.properties
489
if (this.getClass().getClassLoader().getResourceAsStream("jorm.properties") == null) {
490                 throw new BuildException("ERROR: Impossible to " +
491                         "find the 'jorm.properties' file in the classpath, classloader="
492                         + getClass().getClassLoader());
493             }
494
495
496             // Build the .pd list.
497
jormdesc.setDir(new File JavaDoc(scp.input));
498             jormdesc.setProject(project);
499             jormdesc.setIncludes("**/*.pd");
500             ListResourceLocator lrl = new ListResourceLocator(out, true, new MyArrayList(jormdesc.getDirectoryScanner(new File JavaDoc(scp.jormDir)).getIncludedFiles()),scp.output, scp);
501             scp.jorm = lrl.getCollectionOfFiles();
502
503             // search for the .jdo files in output folder if not specified
504
if (opts.jdoFileNames.size() == 0){
505                 jdodesc.setDir(new File JavaDoc(scp.input));
506                 jdodesc.setProject(new Project());
507                 jdodesc.setIncludes("**/*.jdo");
508                 lrl = new ListResourceLocator(out, true, new MyArrayList(jdodesc.getDirectoryScanner(jdodesc.dir).getIncludedFiles()),scp.input, scp);
509                 scp.jdo = lrl.getCollectionOfFiles();
510             }
511             else {
512                 scp.jdo = opts.jdoFileNames;
513             }
514         } catch (Exception JavaDoc e1) {
515             e1.printStackTrace();
516         }
517
518         Collection JavaDoc awarefiles = new ArrayList JavaDoc();
519         try {
520             // classes to enhance must have be specified in the command line.
521
ListResourceLocator lrl = new ListResourceLocator(out, true, ClassFileNames, scp.output, scp);
522             awarefiles = lrl.getCollectionOfFiles();
523         }
524         catch (IOException JavaDoc e) {
525             e.printStackTrace();
526         }
527         scp.awareFiles = awarefiles;
528
529         logger.log(BasicLevel.DEBUG, "leaving initParameters(), ret="+OK);
530         return OK;
531     }
532     
533     private int start()
534     {
535         int res = initParameters();
536         if (res < 0) {
537             return res;
538         }
539         try {
540             logger.log(BasicLevel.DEBUG, "SpeedoCompiler init");
541             printMessage("SpeedoCompiler init");
542             sc.init();
543             logger.log(BasicLevel.DEBUG, "SpeedoCompiler process");
544             printMessage("SpeedoCompiler process");
545             sc.process();
546             logger.log(BasicLevel.DEBUG, "SpeedoCompiler end");
547             printMessage("SpeedoCompiler end");
548         } catch (SpeedoException e) {
549             e.printStackTrace();
550             throw new BuildException(getNestedException(e));
551         }
552         return res;
553     }
554     
555     private Exception JavaDoc getNestedException(Exception JavaDoc e) {
556           if (e instanceof SpeedoException
557                   && ((SpeedoException) e).getNestedException() != null) {
558               return getNestedException(((SpeedoException) e).getNestedException());
559           } else if (e instanceof PException
560                   && ((PException) e).getNestedException() != null) {
561               return getNestedException(((PException) e).getNestedException());
562           } else
563               return e;
564     }
565     
566
567     public class Description extends MatchingTask {
568
569         public File JavaDoc dir = null;
570
571         public void setDir(File JavaDoc dir) {
572             this.dir = dir;
573         }
574
575         public DirectoryScanner getDirectoryScanner(File JavaDoc p) {
576             return super.getDirectoryScanner(p);
577         }
578     }
579     
580     class MyArrayList extends ArrayList JavaDoc {
581         public MyArrayList(Object JavaDoc[] os) {
582             super(os.length);
583             for (int i = 0; i < os.length; i++)
584                 add(os[i]);
585         }
586     }
587     
588     /**
589      * Tests if a filename is a classfile name.
590      *
591      * @param filename The name of the file.
592      * @return Do we have a potential classfile?
593      */

594     static private boolean isClassFileName(String JavaDoc filename)
595     {
596         return filename.endsWith(".class");
597     }
598
599     /**
600      * Tests if a filename is a zipfile (only by testing if the extension -
601      * ignoring the case - is <code>".zip"</code> or <code>".jar"</code>).
602      *
603      * @param filename The name of the file.
604      * @param Do we have a potential zipfile?
605      */

606     static private boolean isZipFileName(String JavaDoc filename)
607     {
608         final int n = filename.length();
609         if (n < 5) {
610             return false;
611         }
612         final String JavaDoc ext = filename.substring(n - 4);
613         return ext.equalsIgnoreCase(".zip") || ext.equalsIgnoreCase(".jar");
614     }
615
616     /**
617      * Tests if a filename is a zipfile (only by testing if the extension -
618      * ignoring the case - is <code>".jar"</code>).
619      *
620      * @param filename The name of the file.
621      * @param Do we have a potential jarfile?
622      */

623     static private boolean isJarFileName(String JavaDoc filename)
624     {
625         final int n = filename.length();
626         if (n < 5) {
627             return false;
628         }
629         final String JavaDoc ext = filename.substring(n - 4);
630         return ext.equalsIgnoreCase(".jar");
631     }
632
633     /**
634      * Tests if a filename is a jdo file name.
635      *
636      * @param filename The name of the file.
637      * @return Do we have a potential jdo file?
638      */

639     static private boolean isJdoFileName(String JavaDoc filename)
640     {
641         // currently not case-tolerant
642
return filename.endsWith(".jdo");
643     }
644
645     /**
646      * Prints out an error.
647      *
648      * @param msg The error message (can be <code>null</code>).
649      * @param ex An optional exception (can be <code>null</code>).
650      */

651     private void printError(String JavaDoc msg,
652                             Throwable JavaDoc ex)
653     {
654         out.flush();
655         if (msg != null) {
656             err.println(msg + (ex != null ? ": " + ex.getMessage() : ""));
657         }
658         if (ex != null) {
659             ex.printStackTrace(err);
660         }
661     }
662
663     /**
664      * Prints out a message.
665      *
666      * @param msg The message.
667      */

668     private void printMessage(String JavaDoc msg)
669     {
670         out.println(msg);
671     }
672 }
673
Popular Tags