KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > schema2beansdev > GenBeans


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.schema2beansdev;
21
22 import java.util.*;
23 import java.io.*;
24 import java.math.BigDecimal JavaDoc;
25
26 import org.netbeans.modules.schema2beansdev.gen.JavaUtil;
27 import org.netbeans.modules.schema2beansdev.gen.WriteIfDifferentOutputStream;
28 import org.netbeans.modules.schema2beans.Common;
29 import org.netbeans.modules.schema2beans.Schema2BeansException;
30 import org.netbeans.modules.schema2beans.Schema2BeansNestedException;
31 import org.netbeans.modules.schema2beans.DDLogFlags;
32 import org.netbeans.modules.schema2beans.Version;
33 import org.netbeans.modules.schema2beansdev.metadd.MetaDD;
34
35 //******************************************************************************
36
// BEGIN_NOI18N
37
//******************************************************************************
38

39 /**
40  * This class provides the generation entry point.
41  */

42 public class GenBeans {
43     public static final String JavaDoc COMMON_BEAN = "CommonBean";
44     /**
45      * The OutputStreamProvider interface is a way of abstracting
46      * how we get an OutputStream given a filename. If GenBeans is being
47      * run as part of the IDE, OutputStream's come from different places
48      * than just opening up a regular File. This is intended for the
49      * writing of the generated files.
50      * The caller of getStream will eventually run .close on the OutputStream
51      */

52     static public interface OutputStreamProvider {
53         public OutputStream getStream(String JavaDoc dir, String JavaDoc name,
54                                       String JavaDoc extension)
55             throws java.io.IOException JavaDoc;
56
57         /**
58          * Returns true if the file in question is more older than the
59          * given time. @see java.io.File.lastModified
60          */

61         public boolean isOlderThan(String JavaDoc dir, String JavaDoc name, String JavaDoc extension,
62                                    long time) throws java.io.IOException JavaDoc;
63     }
64     
65     static public class DefaultOutputStreamProvider implements OutputStreamProvider {
66         private Config config;
67         private List generatedFiles;
68         
69         public DefaultOutputStreamProvider(Config config) {
70             this.config = config;
71             this.generatedFiles = new LinkedList();
72         }
73
74         private String JavaDoc getFilename(String JavaDoc dir, String JavaDoc name, String JavaDoc extension) {
75             return dir + "/" + name + "." + extension; // NOI18N
76
}
77         
78         public OutputStream getStream(String JavaDoc dir, String JavaDoc name,
79                                       String JavaDoc extension)
80             throws java.io.IOException JavaDoc {
81             String JavaDoc filename = getFilename(dir, name, extension);
82             if (!config.isQuiet())
83                 config.messageOut.println(Common.getMessage("MSG_GeneratingClass", filename)); // NOI18N
84
generatedFiles.add(filename);
85             //return new FileOutputStream(filename);
86
return new WriteIfDifferentOutputStream(filename);
87         }
88
89         public boolean isOlderThan(String JavaDoc dir, String JavaDoc name, String JavaDoc extension,
90                                    long time) throws java.io.IOException JavaDoc {
91             String JavaDoc filename = getFilename(dir, name, extension);
92             File f = new File(filename);
93             //System.out.println("filename="+filename+" lm="+f.lastModified());
94
return f.lastModified() < time;
95         }
96
97         public List getGeneratedFiles() {
98             return generatedFiles;
99         }
100     }
101
102     static public class Config extends S2bConfig {
103         // What kind of schema is it coming in
104
public static final int XML_SCHEMA = 0;
105         public static final int DTD = 1;
106         /*
107         int schemaType;
108
109         private boolean traceParse = false;
110         private boolean traceGen = false;
111         private boolean traceMisc = false;
112         private boolean traceDot = false;
113     
114         // filename is the name of the schema (eg, DTD) input file
115         String filename = null;
116         // fileIn is an InputStream version of filename (the source schema).
117         // If fileIn is set, then filename is ignored.
118         InputStream fileIn;
119         String docroot;
120         String rootDir = ".";
121         String packagePath;
122         String indent = "\t";
123         String mddFile;
124         // If mddIn is set, then the mdd file is read from there and
125         // we don't write our own.
126         InputStream mddIn;
127         private MetaDD mdd;
128         boolean doGeneration = true;
129         boolean scalarException;
130         boolean dumpToString;
131         boolean vetoable; // enable veto events
132         boolean standalone;
133         // auto is set when it is assumed that there is no user sitting
134         // in front of System.in
135         boolean auto;
136         // outputStreamProvider, be default, is null, which means that
137         // we use standard java.io.* calls to get the OutputStream
138         OutputStreamProvider outputStreamProvider;
139         boolean throwErrors;
140
141         // Whether or not to generate classes that do XML I/O.
142         boolean generateXMLIO;
143
144         // Whether or not to generate code to do validation
145         boolean generateValidate;
146
147         // Whether or not to generate property events
148         boolean generatePropertyEvents;
149
150         // Whether or not to generate code to be able to store events
151         boolean generateStoreEvents;
152
153         boolean generateTransactions;
154
155         boolean attributesAsProperties;
156
157         //
158         boolean generateDelegator = false;
159
160         String generateCommonInterface = null;
161
162         boolean defaultsAccessable = false;
163
164         private boolean useInterfaces = false;
165
166         // Generate an interface for the bean info accessors
167         private boolean generateInterfaces = false;
168
169         private boolean keepElementPositions = false;
170
171         private boolean removeUnreferencedNodes = false;
172
173         // If we're passed in a simple InputStream, then the inputURI will
174         // help us find relative URI's if anything gets included for imported.
175         private String inputURI;
176
177         // This is the name of the class to use for indexed properties.
178         // It must implement java.util.List
179         // Use null to mean use arrays.
180         private String indexedPropertyType;
181
182         private boolean doCompile = false;
183
184         private String dumpBeanTree = null;
185
186         private String generateDotGraph = null;
187
188         private boolean processComments = false;
189
190         private boolean processDocType = false;
191
192         private boolean checkUpToDate = false;
193
194         private boolean generateParentRefs = false;
195
196         private boolean generateHasChanged = false;
197
198         // Of all our source files, newestSourceTime represents the most
199         // recently modified one.
200         private long newestSourceTime = 0;
201
202         private String writeBeanGraphFilename;
203
204         private List readBeanGraphFilenames = new ArrayList();
205         private List readBeanGraphs = new ArrayList();
206
207         private boolean minFeatures = false;
208
209         private boolean forME = false;
210
211         private boolean generateTagsFile = false;
212         private CodeGeneratorFactory codeGeneratorFactory;
213         */

214         // What should we generate
215
public static final int OUTPUT_TRADITIONAL_BASEBEAN = 0;
216         public static final int OUTPUT_JAVABEANS = 1;
217     
218         PrintStream messageOut;
219         int jdkTarget = 131; // JDK version that we're targeting times 100
220

221         public Config() {
222             setOutputStreamProvider(new DefaultOutputStreamProvider(this));
223             setSchemaTypeNum(DTD);
224             setMessageOut(System.out);
225             // Make the default type be boolean
226
setDefaultElementType("{http://www.w3.org/2001/XMLSchema}boolean");
227             /*
228             attributesAsProperties = false;
229             indexedPropertyType = "java.util.ArrayList";
230             inputURI = null;
231             mddFile = null;
232             scalarException = true;
233             dumpToString = false;
234             vetoable = false;
235             standalone = false;
236             auto = false;
237             mddIn = null;*/

238         }
239
240         public Config(OutputStreamProvider out) {
241             setOutputStreamProvider(out);
242             setSchemaTypeNum(DTD);
243             setMessageOut(System.out);
244         }
245
246         public void readConfigs() throws java.io.IOException JavaDoc {
247             long newestSourceTime = getNewestSourceTime();
248             File[] readConfigs = getReadConfig();
249             for (int i = 0; i < readConfigs.length; ++i) {
250                 try {
251                     File configFile = readConfigs[i];
252                     org.xml.sax.InputSource JavaDoc in = new org.xml.sax.InputSource JavaDoc(new FileInputStream(configFile));
253                     javax.xml.parsers.DocumentBuilderFactory JavaDoc dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
254                     javax.xml.parsers.DocumentBuilder JavaDoc db = dbf.newDocumentBuilder();
255                     org.w3c.dom.Document JavaDoc doc = db.parse(in);
256                     readNode(doc.getDocumentElement());
257                 } catch (javax.xml.parsers.ParserConfigurationException JavaDoc e) {
258                     throw new RuntimeException JavaDoc(e);
259                 } catch (org.xml.sax.SAXException JavaDoc e) {
260                     throw new RuntimeException JavaDoc(e);
261                 }
262             }
263             setNewestSourceTime(newestSourceTime);
264         }
265
266         protected int unknownArgument(String JavaDoc[] args, String JavaDoc arg, int argNum) {
267             if (arg == "-t") {
268                 arg = args[++argNum];
269                 if (arg.equalsIgnoreCase("parse"))
270                     setTraceParse(true);
271                 else if (arg.equalsIgnoreCase("gen"))
272                     setTraceGen(true);
273                 else if (arg.equalsIgnoreCase("dot"))
274                     setTraceDot(true);
275                 else {
276                     if (!arg.equalsIgnoreCase("all"))
277                         --argNum; // unknown value, trace all, and rethink that option
278
setTraceParse(true);
279                     setTraceGen(true);
280                     setTraceMisc(true);
281                     setTraceDot(true);
282                 }
283             } else if (arg == "-version") {
284                 messageOut.println("schema2beans - " + Version.getVersion());
285                 System.exit(0);
286             } else if (arg == "-xmlschema")
287                 setSchemaTypeNum(XML_SCHEMA);
288             else if (arg == "-dtd")
289                 setSchemaTypeNum(DTD);
290             else if (arg == "-premium")
291                 buyPremium();
292             else if (arg == "-strict")
293                 useStrict();
294             else if (arg == "-basebean") {
295                 setOutputType(OUTPUT_TRADITIONAL_BASEBEAN);
296             } else if (arg == "-javabeans")
297                 setOutputType(OUTPUT_JAVABEANS);
298             else if (arg == "-commoninterface")
299                 setGenerateCommonInterface(COMMON_BEAN);
300             else if (arg == "-nocommoninterface")
301                 setGenerateCommonInterface(null);
302             else {
303                 messageOut.println("Unknown argument: "+arg);
304                 messageOut.println("Use -help.");
305                 System.exit(1);
306             }
307             return argNum;
308         }
309
310         public void showHelp(java.io.PrintStream JavaDoc out) {
311             super.showHelp(out);
312             out.println(" -version\tPrint version info");
313             out.println(" -xmlschema\tXML Schema input mode");
314             out.println(" -dtd\tDTD input mode (default)");
315             out.println(" -javaBeans\tGenerate pure JavaBeans that do not need any runtime library support (no BaseBean).");
316             out.println(" -baseBean\tForce use of BaseBean. Runtime required.");
317             out.println(" -commonInterface\tGenerate a common interface between all beans.");
318             out.println(" -premium The \"Premium\" Package. Turn on what ought to be the default switches (but can't be the default due to backwards compatibility).");
319             out.println(" -strict The \"Strict\" Package. For those who are more concerned with correctness than backwards compatibility. Turn on what ought to be the default switches (but can't be the default due to backwards compatibility). Very similar to -premium.");
320             out.println(" -no*\tAny switch that does not take an argument has a -no variant that will turn it off.");
321             out.println("\nThe bean classes are generated in the directory rootDir/packagePath, where packagePath is built using the package name specified. If the package name is not specified, the doc root element value is used as the default package name. Use the empty string to get no (default) package.");
322             out.println("\nexamples: java GenBeans -f ejb.dtd");
323             out.println(" java GenBeans -f webapp.dtd -d webapp -p myproject.webapp -r /myPath/src");
324             out.println(" java GenBeans -f webapp.xsd -xmlschema -r /myPath/src -premium");
325             out.println("\nMost of the parameters are optional. Only the file name is mandatory.");
326             out.println("With only the file name specified, the generator uses the current directory, and uses the schema docroot value as the package name.");
327         }
328         
329         public void setMessageOut(PrintStream messageOut) {
330             this.messageOut = messageOut;
331             super.setMessageOut(messageOut);
332         }
333     
334         public void setOutputType(int type) {
335             if (type == OUTPUT_JAVABEANS) {
336                 setCodeGeneratorFactory(JavaBeansFactory.newInstance());
337                 setAttributesAsProperties(true);
338             } else if (type == OUTPUT_TRADITIONAL_BASEBEAN) {
339                 if (false) {
340                     // Force extendBaseBean option
341
setOutputType(OUTPUT_JAVABEANS);
342                     setExtendBaseBean(true);
343                 } else {
344                     setCodeGeneratorFactory(null);
345                     setProcessComments(false); // we already do it anyway
346
}
347             } else {
348                 throw new IllegalArgumentException JavaDoc("type != OUTPUT_JAVABEANS && type != OUTPUT_TRADITIONAL_BASEBEAN"); // NOI18N
349
}
350         }
351
352         public CodeGeneratorFactory getCodeGeneratorFactory() {
353             if (super.getCodeGeneratorFactory() == null)
354                 setCodeGeneratorFactory(BaseBeansFactory.newInstance());
355             return super.getCodeGeneratorFactory();
356         }
357
358         public void setTarget(String JavaDoc value) {
359             BigDecimal JavaDoc num = new BigDecimal JavaDoc(value);
360             num = num.movePointRight(2);
361             jdkTarget = num.intValue();
362         }
363
364         public void setPackagePath(String JavaDoc pkg) {
365             if (pkg.equals("."))
366                 pkg = "";
367             else
368                 pkg = pkg.replace('.', '/');
369             super.setPackagePath(pkg);
370         }
371
372         public boolean isTrace() {
373             return isTraceParse() || isTraceGen() || isTraceMisc();
374         }
375
376         public void setTraceGen(boolean value) {
377             super.setTraceGen(value);
378             DDLogFlags.debug = value;
379         }
380
381         void setIfNewerSourceTime(long t) {
382             //System.out.println("setIfNewerSourceTime: newestSourceTime="+newestSourceTime+" t="+t);
383
if (t > getNewestSourceTime())
384                 setNewestSourceTime(t);
385         }
386         /*
387         public void setOutputStreamProvider(OutputStreamProvider outputStreamProvider) {
388             this.outputStreamProvider = outputStreamProvider;
389         }
390
391         public void setWriteBeanGraph(String filename) {
392             writeBeanGraphFilename = filename;
393         }
394
395         public String getWriteBeanGraph() {
396             return writeBeanGraphFilename;
397         }
398
399         public void addReadBeanGraphFilename(String filename) {
400             readBeanGraphFilenames.add(filename);
401         }
402
403         public Iterator readBeanGraphFilenames() {
404             return readBeanGraphFilenames.iterator();
405             }
406
407         public void addReadBeanGraph(org.netbeans.modules.schema2beansdev.beangraph.BeanGraph bg) {
408             readBeanGraphs.add(bg);
409         }
410         */

411
412         public Iterator readBeanGraphs() {
413             return fetchReadBeanGraphsList().iterator();
414         }
415
416         public Iterator readBeanGraphFiles() {
417             return fetchReadBeanGraphFilesList().iterator();
418         }
419
420         public int getSchemaTypeNum() {
421             if ("xmlschema".equalsIgnoreCase(getSchemaType()))
422                 return XML_SCHEMA;
423             if ("dtd".equalsIgnoreCase(getSchemaType()))
424                 return DTD;
425             throw new IllegalStateException JavaDoc(Common.getMessage("MSG_IllegalSchemaName", getSchemaType()));
426         }
427
428         public void setSchemaType(int type) {
429             setSchemaTypeNum(type);
430         }
431         
432         public void setSchemaTypeNum(int type) {
433             if (type == XML_SCHEMA)
434                 setSchemaType("xmlschema");
435             else if (type == DTD)
436                 setSchemaType("dtd");
437             else
438                 throw new IllegalStateException JavaDoc("illegal schema type: "+type);
439         }
440
441         /**
442          * @deprecated use setMddIn instead
443          */

444         public void setMDDIn(java.io.InputStream JavaDoc value) {
445             setMddIn(value);
446         }
447
448         /**
449          * @deprecated use setFileIn instead
450          */

451         public void setDTDIn(java.io.InputStream JavaDoc value) {
452             setFileIn(value);
453         }
454
455         public void setRootDir(String JavaDoc dir) {
456             setRootDir(new File(dir));
457         }
458
459         public void setIndexedPropertyType(String JavaDoc className) {
460             if ("".equals(className))
461                 className = null; // use arrays
462
super.setIndexedPropertyType(className);
463         }
464
465         public void setForME(boolean value) {
466             super.setForME(value);
467             if (value) {
468                 setOutputType(OUTPUT_JAVABEANS);
469                 setGeneratePropertyEvents(false);
470                 setIndexedPropertyType(null);
471             }
472         }
473
474         /**
475          * Turn on a bunch of the great switches that arn't on by default.
476          */

477         public void buyPremium() {
478             setSetDefaults(true);
479             setStandalone(true);
480             setDumpToString(true);
481             setThrowErrors(true);
482             setGenerateXMLIO(true);
483             setGenerateValidate(true);
484             setAttributesAsProperties(true);
485             setGenerateInterfaces(true);
486             setOptionalScalars(true);
487             setRespectExtension(true);
488             setLogSuspicious(true);
489             setGenerateCommonInterface(COMMON_BEAN);
490             setOutputType(OUTPUT_JAVABEANS);
491         }
492
493         /**
494          * For those who are more concerned with correctness than
495          * backwards compatibility.
496          */

497         public void useStrict() {
498             setSetDefaults(true);
499             setStandalone(true);
500             setDumpToString(true);
501             setThrowErrors(true);
502             setGenerateXMLIO(true);
503             setGenerateValidate(true);
504             setAttributesAsProperties(true);
505             setRespectExtension(true);
506             setOutputType(OUTPUT_JAVABEANS);
507         }
508
509         public void setMinFeatures(boolean value) {
510             super.setMinFeatures(value);
511             if (value) {
512                 setOutputType(OUTPUT_JAVABEANS);
513                 setGenerateXMLIO(false);
514                 setGenerateValidate(false);
515                 setGenerateInterfaces(false);
516                 setGenerateCommonInterface(null);
517                 setGeneratePropertyEvents(false);
518                 setGenerateStoreEvents(false);
519                 setGenerateTransactions(false);
520                 setDefaultsAccessable(false);
521                 setKeepElementPositions(false);
522                 setRemoveUnreferencedNodes(true);
523                 setProcessComments(false);
524                 setProcessDocType(false);
525                 setGenerateParentRefs(false);
526                 setGenerateHasChanged(false);
527             }
528         }
529
530         public void setExtendBaseBean(boolean value) {
531             super.setExtendBaseBean(value);
532             if (value) {
533                 setUseRuntime(true);
534                 setGenerateParentRefs(true);
535                 setGenerateValidate(true);
536                 setGeneratePropertyEvents(true);
537                 setProcessComments(true);
538                 setProcessDocType(true);
539             }
540         }
541     }
542
543     // Entry point - print help and call the parser
544
public static void main(String JavaDoc args[]) {
545         GenBeans.Config config = new GenBeans.Config();
546     
547         if (config.parseArguments(args)) {
548             config.showHelp(System.out);
549             return;
550         }
551         /*
552         if (config.getFilename() == null) {
553             config.showHelp(System.out);
554             return;
555         }
556           try {
557           for (int i=0; i<args.length; i++) {
558           if (args[i].equals("-f")) {
559           config.setFilename(new File(args[++i]));
560           help++;
561           }
562           else
563           if (args[i].equals("-d")) {
564           config.setDocRoot(args[++i]);
565           if (config.getDocRoot() == null) {
566           help = 0;
567           break;
568           }
569           }
570           else
571           if (args[i].equals("-veto")) {
572           config.setVetoable(true);
573           }
574           else
575           if (args[i].equals("-t")) {
576           ++i;
577           if (args[i].equalsIgnoreCase("parse"))
578           config.setTraceParse(true);
579           else if (args[i].equalsIgnoreCase("gen"))
580           config.setTraceGen(true);
581           else if (args[i].equalsIgnoreCase("dot"))
582           config.setTraceDot(true);
583           else {
584           if (!args[i].equalsIgnoreCase("all"))
585           --i; // unknown value, trace all, and rethink that option
586           config.setTraceParse(true);
587           config.setTraceGen(true);
588           config.setTraceMisc(true);
589           config.setTraceDot(true);
590           }
591           }
592           else
593           if (args[i].equals("-ts")) {
594           config.setDumpToString(true);
595           }
596           else
597           if (args[i].equals("-version")) {
598           System.out.println("schema2beans - " + Version.getVersion());
599           return;
600           }
601           else
602           if (args[i].equals("-noe")) {
603           config.setScalarException(false);
604           }
605           else
606           if (args[i].equals("-p")) {
607           config.setPackagePath(args[++i]);
608           if (config.getPackagePath() == null) {
609           help = 0;
610           break;
611           }
612           }
613           else
614           if (args[i].equals("-r")) {
615           String dir = args[++i];
616           if (dir == null) {
617           help = 0;
618           break;
619           }
620           config.setRootDir(new File(dir));
621           }
622           else
623           if (args[i].equals("-st")) {
624           config.setStandalone(true);
625           }
626           else
627           if (args[i].equals("-sp")) {
628           tab = args[++i];
629           }
630           else
631           if (args[i].equals("-mdd")) {
632           String f = args[++i];
633           if (f == null) {
634           help = 0;
635           break;
636           }
637           config.setMddFile(new File(f));
638           } else if (args[i].equalsIgnoreCase("-xmlschema")) {
639           config.setSchemaTypeNum(Config.XML_SCHEMA);
640           } else if (args[i].equalsIgnoreCase("-dtd")) {
641           config.setSchemaTypeNum(Config.DTD);
642           } else if (args[i].equalsIgnoreCase("-throw")) {
643           config.setThrowErrors(true);
644           } else if (args[i].equalsIgnoreCase("-basebean")) {
645           config.setOutputType(Config.OUTPUT_TRADITIONAL_BASEBEAN);
646           } else if (args[i].equalsIgnoreCase("-javabeans")) {
647           config.setOutputType(Config.OUTPUT_JAVABEANS);
648           } else if (args[i].equalsIgnoreCase("-validate")) {
649           config.setGenerateValidate(true);
650           } else if (args[i].equalsIgnoreCase("-novalidate")) {
651           config.setGenerateValidate(false);
652           } else if (args[i].equalsIgnoreCase("-propertyevents")) {
653           config.setGeneratePropertyEvents(true);
654           } else if (args[i].equalsIgnoreCase("-nopropertyevents")) {
655           config.setGeneratePropertyEvents(false);
656           } else if (args[i].equalsIgnoreCase("-transactions")) {
657           config.setGenerateTransactions(true);
658           } else if (args[i].equalsIgnoreCase("-attrprop")) {
659           config.setAttributesAsProperties(true);
660           } else if (args[i].equalsIgnoreCase("-noattrprop")) {
661           config.setAttributesAsProperties(false);
662           } else if (args[i].equalsIgnoreCase("-indexedpropertytype")) {
663           config.setIndexedPropertyType(args[++i]);
664           } else if (args[i].equalsIgnoreCase("-delegator")) {
665           config.setGenerateDelegator(true);
666           } else if (args[i].equalsIgnoreCase("-premium")) {
667           config.buyPremium();
668           } else if (args[i].equalsIgnoreCase("-commoninterface")) {
669           config.setGenerateCommonInterface(COMMON_BEAN);
670           } else if (args[i].equalsIgnoreCase("-nocommoninterface")) {
671           config.setGenerateCommonInterface(null);
672           } else if (args[i].equalsIgnoreCase("-commoninterfacename")) {
673           config.setGenerateCommonInterface(args[++i]);
674           } else if (args[i].equalsIgnoreCase("-compile")) {
675           config.setDoCompile(true);
676           } else if (args[i].equalsIgnoreCase("-auto")) {
677           config.setAuto(true);
678           } else if (args[i].equalsIgnoreCase("-defaultsaccessable")) {
679           config.setDefaultsAccessable(true);
680           } else if (args[i].equalsIgnoreCase("-useinterfaces")) {
681           config.setUseInterfaces(true);
682           } else if (args[i].equalsIgnoreCase("-geninterfaces")) {
683           config.setGenerateInterfaces(true);
684           } else if (args[i].equalsIgnoreCase("-nogeninterfaces")) {
685           config.setGenerateInterfaces(false);
686           } else if (args[i].equalsIgnoreCase("-keepelementpositions")) {
687           config.setKeepElementPositions(true);
688           } else if (args[i].equalsIgnoreCase("-comments")) {
689           config.setProcessComments(true);
690           } else if (args[i].equalsIgnoreCase("-doctype")) {
691           config.setProcessDocType(true);
692           } else if (args[i].equalsIgnoreCase("-dumpbeantree")) {
693           config.setDumpBeanTree(new File(args[++i]));
694           } else if (args[i].equalsIgnoreCase("-removeunreferencednodes")) {
695           config.setRemoveUnreferencedNodes(true);
696           } else if (args[i].equalsIgnoreCase("-writebeangraph")) {
697           config.setWriteBeanGraphFile(new File(args[++i]));
698           } else if (args[i].equalsIgnoreCase("-readbeangraph")) {
699           config.addReadBeanGraphFiles(new File(args[++i]));
700           } else if (args[i].equalsIgnoreCase("-gendotgraph")) {
701           config.setGenerateDotGraph(new File(args[++i]));
702           } else if (args[i].equalsIgnoreCase("-delegatedir")) {
703           config.setDelegateDir(new File(args[++i]));
704           } else if (args[i].equalsIgnoreCase("-delegatepackage")) {
705           config.setDelegatePackage(args[++i]);
706           } else if (args[i].equalsIgnoreCase("-checkuptodate")) {
707           config.setCheckUpToDate(true);
708           } else if (args[i].equalsIgnoreCase("-haschanged")) {
709           config.setGenerateHasChanged(true);
710           } else if (args[i].equalsIgnoreCase("-generateSwitches")) {
711           config.setGenerateSwitches(true);
712           } else if (args[i].equalsIgnoreCase("-min")) {
713           config.setMinFeatures(true);
714           } else if (args[i].equalsIgnoreCase("-forme")) {
715           config.setForME(true);
716           } else if (args[i].equalsIgnoreCase("-tagsfile")) {
717           config.setGenerateTagsFile(true);
718           } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("--help")) {
719           help = 0;
720           } else {
721           System.out.println("Unknown argument: "+args[i]);
722           System.out.println("Use -help.");
723           System.exit(1);
724           }
725           }
726           } catch (Exception e) {
727           help = 0;
728           }
729     
730           if (help < 1) {
731           System.out.println("usage:");
732           System.out.println("java "+GenBeans.class.getName()+" -f filename [-d docRoot] [-t] [-p package] [-r rootDir] \n\t[-sp number] [-mdd filename] [-noe] [-ts] [-veto] [-version]\n\t[-st] [-throw] [-dtd|-xmlschema] [-javabeans] [-validate]\n\t[-propertyevents] [-attrprop] [-delegator] [-commonInterface] [-commonInterfaceName name]\n\t[-premium] [-compile] [-defaultsAccessable] [-auto]\n\t[-useinterfaces] [-geninterfaces] [-keepelementpositions]\n\t[-dumpbeantree filename] [-removeUnreferencedNodes]\n\t[-genDotGraph filename] [-comments] [-checkUpToDate]\n\t[-writeBeanGraph filename] [-readBeanGraph filename]*\n\t[-hasChanged] [-min] [-forME] [-tagsFile]\n");
733           System.out.println("where:");
734           System.out.println(" -f file name of the DTD");
735           System.out.println(" -d DTD root element name (for example webapp or ejb-jar)");
736           System.out.println(" -p package name");
737           System.out.println(" -r base root directory (root of the package path)");
738           System.out.println(" -sp set the indentation to use 'number' spaces instead of \n the default tab (\ ) value");
739           System.out.println(" -mdd provides extra information that the dtd cannot provide. \n If the file doesn't exist, a skeleton file is created and \n no bean generation happens.");
740           System.out.println(" -noe do not throw the NoSuchElement exception when a scalar property\n has no value, return a default '0' value instead.");
741           System.out.println(" -ts the toString() of the bean returns the full content\n of the bean sub-tree instead of its simple name.");
742           System.out.println(" -veto generate vetoable properties (only for non-bean properties).");
743           System.out.println(" -st standalone mode - do not generate NetBeans dependencies");
744           System.out.println(" -throw generate code that prefers to pass exceptions\n through instead of converting them to RuntimeException (recommended).");
745           System.out.println(" -dtd DTD input mode (default)");
746           System.out.println(" -xmlschema XML Schema input mode");
747           System.out.println(" -javabeans Generate pure JavaBeans that do not need\n any runtime library support (no BaseBean).");
748           System.out.println(" -validate Generate a validate method for doing validation.");
749           System.out.println(" -propertyevents Generate methods for dealing with property events (always on for BaseBean type).");
750           System.out.println(" -attrprop Attributes become like any other property");
751           System.out.println(" -delegator Generate a delegator class for every bean generated.");
752           System.out.println(" -commonInterface Generate a common interface between all beans.");
753           System.out.println(" -commonInterfaceName Name the common interface.");
754           System.out.println(" -premium The \"Premium\" Package. Turn on what ought to be the default switches (but can't be the default due to backwards compatibility).");
755           System.out.println(" -min Generate the minimum Java Beans. Reduce features in favor of reduced class file size.");
756           System.out.println(" -compile Compile all generated classes using javac.");
757           System.out.println(" -defaultsAccessable Generate methods to be able to get at default values.");
758           System.out.println(" -useInterfaces Getters and setters signatures would any defined interface on the bean.");
759           System.out.println(" -genInterfaces For every bean generated, generate an interfaces for it's accessors.");
760           System.out.println(" -keepElementPositions Keep track of the positions of elements (no BaseBean support).");
761           System.out.println(" -dumpBeanTree filename Write out the bean tree to filename.");
762           System.out.println(" -removeUnreferencedNodes Do not generate unreferenced nodes from the bean graph.");
763           System.out.println(" -writeBeanGraph Write out a beangraph XML file. Useful for connecting separate bean graphs.");
764           System.out.println(" -readBeanGraph Read in and use the results of another bean graph.");
765           System.out.println(" -genDotGraph filename Generate a .dot style file for use with GraphViz.");
766           System.out.println(" -comments Process and keep comments (always on for BaseBean type).");
767           System.out.println(" -doctype Process and keep Document Types (always on for BaseBean type).");
768           System.out.println(" -hasChanged Generate code to keep track if the bean graph has changed.");
769           System.out.println(" -checkUpToDate Only do generation if the source files are newer than the to be generated files.");
770           System.out.println(" -forME Generate code for use on J2ME.");
771           System.out.println(" -tagsFile Generate a class that has all schema element & attribute names");
772           System.out.println(" -t [parse|gen|all]\ttracing.");
773         
774           System.out.println("\n\nThe bean classes are generated in the directory rootDir/packagePath, where packagePath is built using the package name specified. If the package name is not specified, the doc root element value is used as the default package name. Use the empty string to get no (default) package.");
775           System.out.println("\nexamples: java GenBeans -f ejb.dtd");
776           System.out.println(" java GenBeans -f webapp.dtd -d webapp -p myproject.webapp -r /myPath/src");
777           System.out.println(" java GenBeans -f webapp.xsd -xmlschema -r /myPath/src -premium");
778           System.out.println("\nMost of the parameters are optional. Only the file name is mandatory.");
779           System.out.println("With only the file name specified, the generator uses the current directory, and uses the schema docroot value as the package name.");
780           }
781           else*/

782         DDLogFlags.debug = config.isTrace();
783         
784         try {
785             doIt(config);
786         } catch (Exception JavaDoc e) {
787             e.printStackTrace();
788             System.exit(1);
789         }
790     }
791     
792     public static void doIt(Config config) throws java.io.IOException JavaDoc, Schema2BeansException {
793         normalizeConfig(config);
794
795         calculateNewestSourceTime(config);
796
797         boolean needToWriteMetaDD = processMetaDD(config);
798
799         // The class that build the DTD object graph
800
TreeBuilder tree = new TreeBuilder(config);
801     
802         // The file parser calling back the handler
803
SchemaParser parser = null;
804         boolean tryAgain;
805         int schemaType = config.getSchemaTypeNum();
806         SchemaParseException lastException = null;
807         do {
808             tryAgain = false;
809             if (schemaType == Config.XML_SCHEMA) {
810                 XMLSchemaParser xmlSchemaParser = new XMLSchemaParser(config, tree);
811                 if (config.getInputURI() != null)
812                     xmlSchemaParser.setInputURI(config.getInputURI());
813                 parser = xmlSchemaParser;
814             } else {
815                 parser = new DocDefParser(config, tree);
816             }
817             readBeanGraphs(config);
818     
819             try {
820                 // parse the DTD, building the object graph
821
parser.process();
822             } catch (SchemaParseException e) {
823                 if (schemaType == Config.DTD) {
824                     // Retry as XML Schema
825
tryAgain = true;
826                     schemaType = Config.XML_SCHEMA;
827                 } else {
828                     if (lastException == null)
829                         throw e;
830                     else
831                         throw lastException;
832                 }
833                 lastException = e;
834             }
835         } while (tryAgain);
836         config.setSchemaTypeNum(schemaType);
837
838         // Build the beans from the graph, and code generate them out to disk.
839
BeanBuilder builder = new BeanBuilder(tree, config,
840                                               config.getCodeGeneratorFactory());
841         builder.process();
842
843         if (needToWriteMetaDD) {
844             try {
845                 config.messageOut.println("Writing metaDD XML file"); // NOI18N
846
FileOutputStream mddOut = new FileOutputStream(config.getMddFile());
847                 config.getMetaDD().write(mddOut);
848                 mddOut.close();
849             } catch (IOException e) {
850                 config.messageOut.println("Failed to write the mdd file: " +
851                                           e.getMessage()); // NOI18N
852
throw e;
853             }
854         }
855
856         if (config.isDoCompile() &&
857             config.getOutputStreamProvider() instanceof DefaultOutputStreamProvider) {
858             DefaultOutputStreamProvider out = (DefaultOutputStreamProvider) config.getOutputStreamProvider();
859             String JavaDoc[] javacArgs = new String JavaDoc[out.getGeneratedFiles().size()];
860             int javaFileCount = 0;
861             for (Iterator it = out.getGeneratedFiles().iterator(); it.hasNext(); ) {
862                 javacArgs[javaFileCount] = (String JavaDoc) it.next();
863                 ++javaFileCount;
864             }
865
866             if (javaFileCount == 0) {
867                 if (!config.isQuiet())
868                     config.messageOut.println(Common.getMessage("MSG_NothingToCompile"));
869             } else {
870                 if (!config.isQuiet())
871                     config.messageOut.println(Common.getMessage("MSG_Compiling"));
872                 try {
873                     Class JavaDoc javacClass = Class.forName("com.sun.tools.javac.Main");
874                     java.lang.reflect.Method JavaDoc compileMethod = javacClass.getDeclaredMethod("compile", new Class JavaDoc[] {String JavaDoc[].class, PrintWriter.class});
875                     // com.sun.tools.javac.Main.compile(javacArgs, pw);
876
PrintWriter pw = new PrintWriter(config.messageOut, true);
877                     Object JavaDoc result = compileMethod.invoke(null,
878                                                 new Object JavaDoc[] {javacArgs, pw});
879                     pw.flush();
880                     int compileExitCode = 0;
881                     if (result instanceof Integer JavaDoc)
882                         compileExitCode = ((Integer JavaDoc)result).intValue();
883                     if (compileExitCode != 0)
884                         throw new RuntimeException JavaDoc("Compile errors: javac had an exit code of "+compileExitCode);
885                 } catch (java.lang.Exception JavaDoc e) {
886                     // Maybe it's just a missing $JRE/tools.jar from
887
// the CLASSPATH.
888
//config.messageOut.println(Common.getMessage("MSG_UnableToCompile"));
889
//config.messageOut.println(e.getClass().getName()+": "+e.getMessage()); // NOI18N
890
//e.printStackTrace();
891
if (e instanceof IOException)
892                         throw (IOException) e;
893                     if (e instanceof Schema2BeansException)
894                         throw (Schema2BeansException) e;
895                     throw new Schema2BeansNestedException(Common.getMessage("MSG_UnableToCompile"), e);
896                 }
897             }
898         }
899     }
900
901     // Do some config parameter validation/adjustment.
902
protected static void normalizeConfig(Config config) throws IOException {
903         if (config.getIndentAmount() > 0) {
904             config.setIndent("");
905             for(int i = 0; i < config.getIndentAmount(); i++)
906                 config.setIndent(config.getIndent()+" ");
907         }
908         if (config.isGenerateTransactions()) {
909             config.setGeneratePropertyEvents(true);
910             config.setGenerateStoreEvents(true);
911         } else if (!config.isGeneratePropertyEvents() && config.isGenerateStoreEvents())
912             config.setGenerateStoreEvents(false);
913         if (config.isGenerateHasChanged())
914             config.setGenerateParentRefs(true);
915
916         config.readConfigs();
917         if (config.getWriteConfig() != null) {
918             config.write(new FileOutputStream(config.getWriteConfig()));
919         }
920     }
921
922     private static void readBeanGraphs(Config config) throws IOException {
923         try {
924             for (Iterator it = config.readBeanGraphFiles(); it.hasNext(); ) {
925                 File filename = (File) it.next();
926                 InputStream in = new FileInputStream(filename);
927                 org.netbeans.modules.schema2beansdev.beangraph.BeanGraph bg = org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.read(in);
928                 in.close();
929                 config.addReadBeanGraphs(bg);
930             }
931         } catch (javax.xml.parsers.ParserConfigurationException JavaDoc e) {
932             throw new RuntimeException JavaDoc(e);
933         } catch (org.xml.sax.SAXException JavaDoc e) {
934             throw new RuntimeException JavaDoc(e);
935         }
936     }
937
938     /**
939      * @return whether or not the MetaDD should be written out at the end.
940      */

941     private static boolean processMetaDD(Config config) throws IOException {
942         boolean needToWriteMetaDD = false;
943         MetaDD mdd;
944         //
945
// Either creates the metaDD file or read the existing one
946
//
947
if (config.getMddFile() != null || config.getMddIn() != null) {
948             File file = config.getMddFile();
949         
950             if (config.getMddIn() == null && !file.exists()) {
951                 config.setDoGeneration(false);
952                 if (!config.isAuto()) {
953                     if (!askYesOrNo(config.messageOut, "The mdd file " + config.getMddFile() + // NOI18N
954
" doesn't exist. Should we create it (y/n)? ")) { // NOI18N
955
config.messageOut.println("Generation aborted."); // NOI18N
956
return false;
957                     }
958                 }
959                 needToWriteMetaDD = true;
960                 mdd = new MetaDD();
961             } else {
962                 try {
963                     InputStream is = config.getMddIn();
964                     if (config.getMddIn() == null) {
965                         is = new FileInputStream(config.getMddFile());
966                         config.messageOut.println(Common.getMessage("MSG_UsingMdd",
967                                                                     config.getMddFile()));
968                     }
969                     mdd = MetaDD.read(is);
970                     if (config.getMddIn() == null) {
971                         is.close();
972                     }
973                 } catch (IOException e) {
974                     if (config.isTraceParse())
975                         e.printStackTrace();
976                     throw new IOException(Common.
977                                           getMessage("CantCreateMetaDDFile_msg", e.getMessage()));
978                 } catch (javax.xml.parsers.ParserConfigurationException JavaDoc e) {
979                     if (config.isTraceParse())
980                         e.printStackTrace();
981                     throw new IOException(Common.
982                                           getMessage("CantCreateMetaDDFile_msg", e.getMessage()));
983                 } catch (org.xml.sax.SAXException JavaDoc e) {
984                     if (config.isTraceParse())
985                         e.printStackTrace();
986                     throw new IOException(Common.
987                                           getMessage("CantCreateMetaDDFile_msg", e.getMessage()));
988                 }
989             }
990         } else {
991             // Create a MetaDD to look stuff up in later on, even though
992
// it wasn't read in, and we're not going to write it out.
993
mdd = new MetaDD();
994         }
995         config.setMetaDD(mdd);
996         return needToWriteMetaDD;
997     }
998
999     private static boolean askYesOrNo(PrintStream out, String JavaDoc prompt) throws IOException {
1000        out.print(prompt);
1001        BufferedReader rd =
1002            new BufferedReader(new InputStreamReader(System.in));
1003            
1004        String JavaDoc str;
1005        str = rd.readLine();
1006        
1007        return str.equalsIgnoreCase("y"); // NOI18N
1008
}
1009
1010    private static void calculateNewestSourceTime(Config config) {
1011        if (config.getFilename() != null) {
1012            config.setIfNewerSourceTime(config.getFilename().lastModified());
1013        }
1014        if (config.getMddFile() != null) {
1015            config.setIfNewerSourceTime(config.getMddFile().lastModified());
1016        }
1017        for (Iterator it = config.readBeanGraphFiles(); it.hasNext(); ) {
1018            File f = (File) it.next();
1019            config.setIfNewerSourceTime(f.lastModified());
1020        }
1021
1022        // Need to also check the times on schema2beans.jar & schema2beansdev.jar
1023
config.setIfNewerSourceTime(getLastModified(org.netbeans.modules.schema2beans.BaseBean.class));
1024        config.setIfNewerSourceTime(getLastModified(BeanClass.class));
1025        config.setIfNewerSourceTime(getLastModified(GenBeans.class));
1026        config.setIfNewerSourceTime(getLastModified(BeanBuilder.class));
1027        config.setIfNewerSourceTime(getLastModified(TreeBuilder.class));
1028        config.setIfNewerSourceTime(getLastModified(GraphLink.class));
1029        config.setIfNewerSourceTime(getLastModified(GraphNode.class));
1030        config.setIfNewerSourceTime(getLastModified(JavaBeanClass.class));
1031        //System.out.println("config.getNewestSourceTime="+config.getNewestSourceTime());
1032
}
1033
1034    private static long getLastModified(Class JavaDoc cls) {
1035        try {
1036            String JavaDoc shortName = cls.getName().substring(1+cls.getName().lastIndexOf('.'));
1037            java.net.URL JavaDoc url = cls.getResource(shortName + ".class");
1038            String JavaDoc file = url.getFile();
1039            //System.out.println("url="+url);
1040
if ("file".equals(url.getProtocol())) {
1041                // example: file='/home/cliffwd/cvs/dublin/nb_all/schema2beans/rt/src/org/netbeans/modules/schema2beans/GenBeans.class'
1042
String JavaDoc result = file.substring(0, file.length() - cls.getName().length() - 6);
1043                return new File(file).lastModified();
1044            } else if ("jar".equals(url.getProtocol())) {
1045                // example: file = 'jar:/usr/local/j2sdkee1.3.1/lib/j2ee.jar!/org/w3c/dom/Node.class'
1046
String JavaDoc jarFile = file.substring(file.indexOf(':')+1);
1047                jarFile = jarFile.substring(0, jarFile.indexOf('!'));
1048                //System.out.println("jarFile="+jarFile);
1049
return new File(jarFile).lastModified();
1050            }
1051            return url.openConnection().getDate();
1052        } catch (java.io.IOException JavaDoc e) {
1053            return 0;
1054        }
1055    }
1056}
1057
1058//******************************************************************************
1059
// END_NOI18N
1060
//******************************************************************************
1061
Popular Tags