0001: /*
0002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
0003: *
0004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
0005: *
0006: * The contents of this file are subject to the terms of either the GNU
0007: * General Public License Version 2 only ("GPL") or the Common
0008: * Development and Distribution License("CDDL") (collectively, the
0009: * "License"). You may not use this file except in compliance with the
0010: * License. You can obtain a copy of the License at
0011: * http://www.netbeans.org/cddl-gplv2.html
0012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
0013: * specific language governing permissions and limitations under the
0014: * License. When distributing the software, include this License Header
0015: * Notice in each file and include the License file at
0016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
0017: * particular file as subject to the "Classpath" exception as provided
0018: * by Sun in the GPL Version 2 section of the License file that
0019: * accompanied this code. If applicable, add the following below the
0020: * License Header, with the fields enclosed by brackets [] replaced by
0021: * your own identifying information:
0022: * "Portions Copyrighted [year] [name of copyright owner]"
0023: *
0024: * Contributor(s):
0025: *
0026: * The Original Software is NetBeans. The Initial Developer of the Original
0027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
0028: * Microsystems, Inc. All Rights Reserved.
0029: *
0030: * If you wish your version of this file to be governed by only the CDDL
0031: * or only the GPL Version 2, indicate your decision by adding
0032: * "[Contributor] elects to include this software in this distribution
0033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
0034: * single choice of license, a recipient has the option to distribute
0035: * your version of this file under either the CDDL, the GPL Version 2 or
0036: * to extend the choice of license to its licensees as provided above.
0037: * However, if you add GPL Version 2 code and therefore, elected the GPL
0038: * Version 2 license, then the option applies only if the new code is
0039: * made subject to such option by the copyright holder.
0040: */
0041:
0042: package org.netbeans.modules.schema2beansdev;
0043:
0044: import java.util.*;
0045: import java.io.*;
0046: import java.math.BigDecimal;
0047:
0048: import org.netbeans.modules.schema2beansdev.gen.JavaUtil;
0049: import org.netbeans.modules.schema2beansdev.gen.WriteIfDifferentOutputStream;
0050: import org.netbeans.modules.schema2beans.Common;
0051: import org.netbeans.modules.schema2beans.Schema2BeansException;
0052: import org.netbeans.modules.schema2beans.Schema2BeansNestedException;
0053: import org.netbeans.modules.schema2beans.DDLogFlags;
0054: import org.netbeans.modules.schema2beans.Version;
0055: import org.netbeans.modules.schema2beansdev.metadd.MetaDD;
0056:
0057: //******************************************************************************
0058: // BEGIN_NOI18N
0059: //******************************************************************************
0060:
0061: /**
0062: * This class provides the generation entry point.
0063: */
0064: public class GenBeans {
0065: public static final String COMMON_BEAN = "CommonBean";
0066:
0067: /**
0068: * The OutputStreamProvider interface is a way of abstracting
0069: * how we get an OutputStream given a filename. If GenBeans is being
0070: * run as part of the IDE, OutputStream's come from different places
0071: * than just opening up a regular File. This is intended for the
0072: * writing of the generated files.
0073: * The caller of getStream will eventually run .close on the OutputStream
0074: */
0075: static public interface OutputStreamProvider {
0076: public OutputStream getStream(String dir, String name,
0077: String extension) throws java.io.IOException;
0078:
0079: /**
0080: * Returns true if the file in question is more older than the
0081: * given time. @see java.io.File.lastModified
0082: */
0083: public boolean isOlderThan(String dir, String name,
0084: String extension, long time) throws java.io.IOException;
0085: }
0086:
0087: static public class DefaultOutputStreamProvider implements
0088: OutputStreamProvider {
0089: private Config config;
0090: private List generatedFiles;
0091:
0092: public DefaultOutputStreamProvider(Config config) {
0093: this .config = config;
0094: this .generatedFiles = new LinkedList();
0095: }
0096:
0097: private String getFilename(String dir, String name,
0098: String extension) {
0099: return dir + "/" + name + "." + extension; // NOI18N
0100: }
0101:
0102: public OutputStream getStream(String dir, String name,
0103: String extension) throws java.io.IOException {
0104: String filename = getFilename(dir, name, extension);
0105: if (!config.isQuiet())
0106: config.messageOut.println(Common.getMessage(
0107: "MSG_GeneratingClass", filename)); // NOI18N
0108: generatedFiles.add(filename);
0109: //return new FileOutputStream(filename);
0110: return new WriteIfDifferentOutputStream(filename);
0111: }
0112:
0113: public boolean isOlderThan(String dir, String name,
0114: String extension, long time) throws java.io.IOException {
0115: String filename = getFilename(dir, name, extension);
0116: File f = new File(filename);
0117: //System.out.println("filename="+filename+" lm="+f.lastModified());
0118: return f.lastModified() < time;
0119: }
0120:
0121: public List getGeneratedFiles() {
0122: return generatedFiles;
0123: }
0124: }
0125:
0126: static public class Config extends S2bConfig {
0127: // What kind of schema is it coming in
0128: public static final int XML_SCHEMA = 0;
0129: public static final int DTD = 1;
0130: /*
0131: int schemaType;
0132:
0133: private boolean traceParse = false;
0134: private boolean traceGen = false;
0135: private boolean traceMisc = false;
0136: private boolean traceDot = false;
0137:
0138: // filename is the name of the schema (eg, DTD) input file
0139: String filename = null;
0140: // fileIn is an InputStream version of filename (the source schema).
0141: // If fileIn is set, then filename is ignored.
0142: InputStream fileIn;
0143: String docroot;
0144: String rootDir = ".";
0145: String packagePath;
0146: String indent = "\t";
0147: String mddFile;
0148: // If mddIn is set, then the mdd file is read from there and
0149: // we don't write our own.
0150: InputStream mddIn;
0151: private MetaDD mdd;
0152: boolean doGeneration = true;
0153: boolean scalarException;
0154: boolean dumpToString;
0155: boolean vetoable; // enable veto events
0156: boolean standalone;
0157: // auto is set when it is assumed that there is no user sitting
0158: // in front of System.in
0159: boolean auto;
0160: // outputStreamProvider, be default, is null, which means that
0161: // we use standard java.io.* calls to get the OutputStream
0162: OutputStreamProvider outputStreamProvider;
0163: boolean throwErrors;
0164:
0165: // Whether or not to generate classes that do XML I/O.
0166: boolean generateXMLIO;
0167:
0168: // Whether or not to generate code to do validation
0169: boolean generateValidate;
0170:
0171: // Whether or not to generate property events
0172: boolean generatePropertyEvents;
0173:
0174: // Whether or not to generate code to be able to store events
0175: boolean generateStoreEvents;
0176:
0177: boolean generateTransactions;
0178:
0179: boolean attributesAsProperties;
0180:
0181: //
0182: boolean generateDelegator = false;
0183:
0184: String generateCommonInterface = null;
0185:
0186: boolean defaultsAccessable = false;
0187:
0188: private boolean useInterfaces = false;
0189:
0190: // Generate an interface for the bean info accessors
0191: private boolean generateInterfaces = false;
0192:
0193: private boolean keepElementPositions = false;
0194:
0195: private boolean removeUnreferencedNodes = false;
0196:
0197: // If we're passed in a simple InputStream, then the inputURI will
0198: // help us find relative URI's if anything gets included for imported.
0199: private String inputURI;
0200:
0201: // This is the name of the class to use for indexed properties.
0202: // It must implement java.util.List
0203: // Use null to mean use arrays.
0204: private String indexedPropertyType;
0205:
0206: private boolean doCompile = false;
0207:
0208: private String dumpBeanTree = null;
0209:
0210: private String generateDotGraph = null;
0211:
0212: private boolean processComments = false;
0213:
0214: private boolean processDocType = false;
0215:
0216: private boolean checkUpToDate = false;
0217:
0218: private boolean generateParentRefs = false;
0219:
0220: private boolean generateHasChanged = false;
0221:
0222: // Of all our source files, newestSourceTime represents the most
0223: // recently modified one.
0224: private long newestSourceTime = 0;
0225:
0226: private String writeBeanGraphFilename;
0227:
0228: private List readBeanGraphFilenames = new ArrayList();
0229: private List readBeanGraphs = new ArrayList();
0230:
0231: private boolean minFeatures = false;
0232:
0233: private boolean forME = false;
0234:
0235: private boolean generateTagsFile = false;
0236: private CodeGeneratorFactory codeGeneratorFactory;
0237: */
0238: // What should we generate
0239: public static final int OUTPUT_TRADITIONAL_BASEBEAN = 0;
0240: public static final int OUTPUT_JAVABEANS = 1;
0241:
0242: PrintStream messageOut;
0243: int jdkTarget = 131; // JDK version that we're targeting times 100
0244:
0245: public Config() {
0246: setOutputStreamProvider(new DefaultOutputStreamProvider(
0247: this ));
0248: setSchemaTypeNum(DTD);
0249: setMessageOut(System.out);
0250: // Make the default type be boolean
0251: setDefaultElementType("{http://www.w3.org/2001/XMLSchema}boolean");
0252: /*
0253: attributesAsProperties = false;
0254: indexedPropertyType = "java.util.ArrayList";
0255: inputURI = null;
0256: mddFile = null;
0257: scalarException = true;
0258: dumpToString = false;
0259: vetoable = false;
0260: standalone = false;
0261: auto = false;
0262: mddIn = null;*/
0263: }
0264:
0265: public Config(OutputStreamProvider out) {
0266: setOutputStreamProvider(out);
0267: setSchemaTypeNum(DTD);
0268: setMessageOut(System.out);
0269: }
0270:
0271: public void readConfigs() throws java.io.IOException {
0272: long newestSourceTime = getNewestSourceTime();
0273: File[] readConfigs = getReadConfig();
0274: for (int i = 0; i < readConfigs.length; ++i) {
0275: try {
0276: File configFile = readConfigs[i];
0277: org.xml.sax.InputSource in = new org.xml.sax.InputSource(
0278: new FileInputStream(configFile));
0279: javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory
0280: .newInstance();
0281: javax.xml.parsers.DocumentBuilder db = dbf
0282: .newDocumentBuilder();
0283: org.w3c.dom.Document doc = db.parse(in);
0284: readNode(doc.getDocumentElement());
0285: } catch (javax.xml.parsers.ParserConfigurationException e) {
0286: throw new RuntimeException(e);
0287: } catch (org.xml.sax.SAXException e) {
0288: throw new RuntimeException(e);
0289: }
0290: }
0291: setNewestSourceTime(newestSourceTime);
0292: }
0293:
0294: protected int unknownArgument(String[] args, String arg,
0295: int argNum) {
0296: if (arg == "-t") {
0297: arg = args[++argNum];
0298: if (arg.equalsIgnoreCase("parse"))
0299: setTraceParse(true);
0300: else if (arg.equalsIgnoreCase("gen"))
0301: setTraceGen(true);
0302: else if (arg.equalsIgnoreCase("dot"))
0303: setTraceDot(true);
0304: else {
0305: if (!arg.equalsIgnoreCase("all"))
0306: --argNum; // unknown value, trace all, and rethink that option
0307: setTraceParse(true);
0308: setTraceGen(true);
0309: setTraceMisc(true);
0310: setTraceDot(true);
0311: }
0312: } else if (arg == "-version") {
0313: messageOut.println("schema2beans - "
0314: + Version.getVersion());
0315: System.exit(0);
0316: } else if (arg == "-xmlschema")
0317: setSchemaTypeNum(XML_SCHEMA);
0318: else if (arg == "-dtd")
0319: setSchemaTypeNum(DTD);
0320: else if (arg == "-premium")
0321: buyPremium();
0322: else if (arg == "-strict")
0323: useStrict();
0324: else if (arg == "-basebean") {
0325: setOutputType(OUTPUT_TRADITIONAL_BASEBEAN);
0326: } else if (arg == "-javabeans")
0327: setOutputType(OUTPUT_JAVABEANS);
0328: else if (arg == "-commoninterface")
0329: setGenerateCommonInterface(COMMON_BEAN);
0330: else if (arg == "-nocommoninterface")
0331: setGenerateCommonInterface(null);
0332: else {
0333: messageOut.println("Unknown argument: " + arg);
0334: messageOut.println("Use -help.");
0335: System.exit(1);
0336: }
0337: return argNum;
0338: }
0339:
0340: public void showHelp(java.io.PrintStream out) {
0341: super .showHelp(out);
0342: out.println(" -version\tPrint version info");
0343: out.println(" -xmlschema\tXML Schema input mode");
0344: out.println(" -dtd\tDTD input mode (default)");
0345: out
0346: .println(" -javaBeans\tGenerate pure JavaBeans that do not need any runtime library support (no BaseBean).");
0347: out
0348: .println(" -baseBean\tForce use of BaseBean. Runtime required.");
0349: out
0350: .println(" -commonInterface\tGenerate a common interface between all beans.");
0351: out
0352: .println(" -premium The \"Premium\" Package. Turn on what ought to be the default switches (but can't be the default due to backwards compatibility).");
0353: out
0354: .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.");
0355: out
0356: .println(" -no*\tAny switch that does not take an argument has a -no variant that will turn it off.");
0357: out
0358: .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.");
0359: out.println("\nexamples: java GenBeans -f ejb.dtd");
0360: out
0361: .println(" java GenBeans -f webapp.dtd -d webapp -p myproject.webapp -r /myPath/src");
0362: out
0363: .println(" java GenBeans -f webapp.xsd -xmlschema -r /myPath/src -premium");
0364: out
0365: .println("\nMost of the parameters are optional. Only the file name is mandatory.");
0366: out
0367: .println("With only the file name specified, the generator uses the current directory, and uses the schema docroot value as the package name.");
0368: }
0369:
0370: public void setMessageOut(PrintStream messageOut) {
0371: this .messageOut = messageOut;
0372: super .setMessageOut(messageOut);
0373: }
0374:
0375: public void setOutputType(int type) {
0376: if (type == OUTPUT_JAVABEANS) {
0377: setCodeGeneratorFactory(JavaBeansFactory.newInstance());
0378: setAttributesAsProperties(true);
0379: } else if (type == OUTPUT_TRADITIONAL_BASEBEAN) {
0380: if (false) {
0381: // Force extendBaseBean option
0382: setOutputType(OUTPUT_JAVABEANS);
0383: setExtendBaseBean(true);
0384: } else {
0385: setCodeGeneratorFactory(null);
0386: setProcessComments(false); // we already do it anyway
0387: }
0388: } else {
0389: throw new IllegalArgumentException(
0390: "type != OUTPUT_JAVABEANS && type != OUTPUT_TRADITIONAL_BASEBEAN"); // NOI18N
0391: }
0392: }
0393:
0394: public CodeGeneratorFactory getCodeGeneratorFactory() {
0395: if (super .getCodeGeneratorFactory() == null)
0396: setCodeGeneratorFactory(BaseBeansFactory.newInstance());
0397: return super .getCodeGeneratorFactory();
0398: }
0399:
0400: public void setTarget(String value) {
0401: BigDecimal num = new BigDecimal(value);
0402: num = num.movePointRight(2);
0403: jdkTarget = num.intValue();
0404: }
0405:
0406: public void setPackagePath(String pkg) {
0407: if (pkg.equals("."))
0408: pkg = "";
0409: else
0410: pkg = pkg.replace('.', '/');
0411: super .setPackagePath(pkg);
0412: }
0413:
0414: public boolean isTrace() {
0415: return isTraceParse() || isTraceGen() || isTraceMisc();
0416: }
0417:
0418: public void setTraceGen(boolean value) {
0419: super .setTraceGen(value);
0420: DDLogFlags.debug = value;
0421: }
0422:
0423: void setIfNewerSourceTime(long t) {
0424: //System.out.println("setIfNewerSourceTime: newestSourceTime="+newestSourceTime+" t="+t);
0425: if (t > getNewestSourceTime())
0426: setNewestSourceTime(t);
0427: }
0428:
0429: /*
0430: public void setOutputStreamProvider(OutputStreamProvider outputStreamProvider) {
0431: this.outputStreamProvider = outputStreamProvider;
0432: }
0433:
0434: public void setWriteBeanGraph(String filename) {
0435: writeBeanGraphFilename = filename;
0436: }
0437:
0438: public String getWriteBeanGraph() {
0439: return writeBeanGraphFilename;
0440: }
0441:
0442: public void addReadBeanGraphFilename(String filename) {
0443: readBeanGraphFilenames.add(filename);
0444: }
0445:
0446: public Iterator readBeanGraphFilenames() {
0447: return readBeanGraphFilenames.iterator();
0448: }
0449:
0450: public void addReadBeanGraph(org.netbeans.modules.schema2beansdev.beangraph.BeanGraph bg) {
0451: readBeanGraphs.add(bg);
0452: }
0453: */
0454:
0455: public Iterator readBeanGraphs() {
0456: return fetchReadBeanGraphsList().iterator();
0457: }
0458:
0459: public Iterator readBeanGraphFiles() {
0460: return fetchReadBeanGraphFilesList().iterator();
0461: }
0462:
0463: public int getSchemaTypeNum() {
0464: if ("xmlschema".equalsIgnoreCase(getSchemaType()))
0465: return XML_SCHEMA;
0466: if ("dtd".equalsIgnoreCase(getSchemaType()))
0467: return DTD;
0468: throw new IllegalStateException(Common.getMessage(
0469: "MSG_IllegalSchemaName", getSchemaType()));
0470: }
0471:
0472: public void setSchemaType(int type) {
0473: setSchemaTypeNum(type);
0474: }
0475:
0476: public void setSchemaTypeNum(int type) {
0477: if (type == XML_SCHEMA)
0478: setSchemaType("xmlschema");
0479: else if (type == DTD)
0480: setSchemaType("dtd");
0481: else
0482: throw new IllegalStateException("illegal schema type: "
0483: + type);
0484: }
0485:
0486: /**
0487: * @deprecated use setMddIn instead
0488: */
0489: public void setMDDIn(java.io.InputStream value) {
0490: setMddIn(value);
0491: }
0492:
0493: /**
0494: * @deprecated use setFileIn instead
0495: */
0496: public void setDTDIn(java.io.InputStream value) {
0497: setFileIn(value);
0498: }
0499:
0500: public void setRootDir(String dir) {
0501: setRootDir(new File(dir));
0502: }
0503:
0504: public void setIndexedPropertyType(String className) {
0505: if ("".equals(className))
0506: className = null; // use arrays
0507: super .setIndexedPropertyType(className);
0508: }
0509:
0510: public void setForME(boolean value) {
0511: super .setForME(value);
0512: if (value) {
0513: setOutputType(OUTPUT_JAVABEANS);
0514: setGeneratePropertyEvents(false);
0515: setIndexedPropertyType(null);
0516: }
0517: }
0518:
0519: /**
0520: * Turn on a bunch of the great switches that arn't on by default.
0521: */
0522: public void buyPremium() {
0523: setSetDefaults(true);
0524: setStandalone(true);
0525: setDumpToString(true);
0526: setThrowErrors(true);
0527: setGenerateXMLIO(true);
0528: setGenerateValidate(true);
0529: setAttributesAsProperties(true);
0530: setGenerateInterfaces(true);
0531: setOptionalScalars(true);
0532: setRespectExtension(true);
0533: setLogSuspicious(true);
0534: setGenerateCommonInterface(COMMON_BEAN);
0535: setOutputType(OUTPUT_JAVABEANS);
0536: }
0537:
0538: /**
0539: * For those who are more concerned with correctness than
0540: * backwards compatibility.
0541: */
0542: public void useStrict() {
0543: setSetDefaults(true);
0544: setStandalone(true);
0545: setDumpToString(true);
0546: setThrowErrors(true);
0547: setGenerateXMLIO(true);
0548: setGenerateValidate(true);
0549: setAttributesAsProperties(true);
0550: setRespectExtension(true);
0551: setOutputType(OUTPUT_JAVABEANS);
0552: }
0553:
0554: public void setMinFeatures(boolean value) {
0555: super .setMinFeatures(value);
0556: if (value) {
0557: setOutputType(OUTPUT_JAVABEANS);
0558: setGenerateXMLIO(false);
0559: setGenerateValidate(false);
0560: setGenerateInterfaces(false);
0561: setGenerateCommonInterface(null);
0562: setGeneratePropertyEvents(false);
0563: setGenerateStoreEvents(false);
0564: setGenerateTransactions(false);
0565: setDefaultsAccessable(false);
0566: setKeepElementPositions(false);
0567: setRemoveUnreferencedNodes(true);
0568: setProcessComments(false);
0569: setProcessDocType(false);
0570: setGenerateParentRefs(false);
0571: setGenerateHasChanged(false);
0572: }
0573: }
0574:
0575: public void setExtendBaseBean(boolean value) {
0576: super .setExtendBaseBean(value);
0577: if (value) {
0578: setUseRuntime(true);
0579: setGenerateParentRefs(true);
0580: setGenerateValidate(true);
0581: setGeneratePropertyEvents(true);
0582: setProcessComments(true);
0583: setProcessDocType(true);
0584: }
0585: }
0586: }
0587:
0588: // Entry point - print help and call the parser
0589: public static void main(String args[]) {
0590: GenBeans.Config config = new GenBeans.Config();
0591:
0592: if (config.parseArguments(args)) {
0593: config.showHelp(System.out);
0594: return;
0595: }
0596: /*
0597: if (config.getFilename() == null) {
0598: config.showHelp(System.out);
0599: return;
0600: }
0601: try {
0602: for (int i=0; i<args.length; i++) {
0603: if (args[i].equals("-f")) {
0604: config.setFilename(new File(args[++i]));
0605: help++;
0606: }
0607: else
0608: if (args[i].equals("-d")) {
0609: config.setDocRoot(args[++i]);
0610: if (config.getDocRoot() == null) {
0611: help = 0;
0612: break;
0613: }
0614: }
0615: else
0616: if (args[i].equals("-veto")) {
0617: config.setVetoable(true);
0618: }
0619: else
0620: if (args[i].equals("-t")) {
0621: ++i;
0622: if (args[i].equalsIgnoreCase("parse"))
0623: config.setTraceParse(true);
0624: else if (args[i].equalsIgnoreCase("gen"))
0625: config.setTraceGen(true);
0626: else if (args[i].equalsIgnoreCase("dot"))
0627: config.setTraceDot(true);
0628: else {
0629: if (!args[i].equalsIgnoreCase("all"))
0630: --i; // unknown value, trace all, and rethink that option
0631: config.setTraceParse(true);
0632: config.setTraceGen(true);
0633: config.setTraceMisc(true);
0634: config.setTraceDot(true);
0635: }
0636: }
0637: else
0638: if (args[i].equals("-ts")) {
0639: config.setDumpToString(true);
0640: }
0641: else
0642: if (args[i].equals("-version")) {
0643: System.out.println("schema2beans - " + Version.getVersion());
0644: return;
0645: }
0646: else
0647: if (args[i].equals("-noe")) {
0648: config.setScalarException(false);
0649: }
0650: else
0651: if (args[i].equals("-p")) {
0652: config.setPackagePath(args[++i]);
0653: if (config.getPackagePath() == null) {
0654: help = 0;
0655: break;
0656: }
0657: }
0658: else
0659: if (args[i].equals("-r")) {
0660: String dir = args[++i];
0661: if (dir == null) {
0662: help = 0;
0663: break;
0664: }
0665: config.setRootDir(new File(dir));
0666: }
0667: else
0668: if (args[i].equals("-st")) {
0669: config.setStandalone(true);
0670: }
0671: else
0672: if (args[i].equals("-sp")) {
0673: tab = args[++i];
0674: }
0675: else
0676: if (args[i].equals("-mdd")) {
0677: String f = args[++i];
0678: if (f == null) {
0679: help = 0;
0680: break;
0681: }
0682: config.setMddFile(new File(f));
0683: } else if (args[i].equalsIgnoreCase("-xmlschema")) {
0684: config.setSchemaTypeNum(Config.XML_SCHEMA);
0685: } else if (args[i].equalsIgnoreCase("-dtd")) {
0686: config.setSchemaTypeNum(Config.DTD);
0687: } else if (args[i].equalsIgnoreCase("-throw")) {
0688: config.setThrowErrors(true);
0689: } else if (args[i].equalsIgnoreCase("-basebean")) {
0690: config.setOutputType(Config.OUTPUT_TRADITIONAL_BASEBEAN);
0691: } else if (args[i].equalsIgnoreCase("-javabeans")) {
0692: config.setOutputType(Config.OUTPUT_JAVABEANS);
0693: } else if (args[i].equalsIgnoreCase("-validate")) {
0694: config.setGenerateValidate(true);
0695: } else if (args[i].equalsIgnoreCase("-novalidate")) {
0696: config.setGenerateValidate(false);
0697: } else if (args[i].equalsIgnoreCase("-propertyevents")) {
0698: config.setGeneratePropertyEvents(true);
0699: } else if (args[i].equalsIgnoreCase("-nopropertyevents")) {
0700: config.setGeneratePropertyEvents(false);
0701: } else if (args[i].equalsIgnoreCase("-transactions")) {
0702: config.setGenerateTransactions(true);
0703: } else if (args[i].equalsIgnoreCase("-attrprop")) {
0704: config.setAttributesAsProperties(true);
0705: } else if (args[i].equalsIgnoreCase("-noattrprop")) {
0706: config.setAttributesAsProperties(false);
0707: } else if (args[i].equalsIgnoreCase("-indexedpropertytype")) {
0708: config.setIndexedPropertyType(args[++i]);
0709: } else if (args[i].equalsIgnoreCase("-delegator")) {
0710: config.setGenerateDelegator(true);
0711: } else if (args[i].equalsIgnoreCase("-premium")) {
0712: config.buyPremium();
0713: } else if (args[i].equalsIgnoreCase("-commoninterface")) {
0714: config.setGenerateCommonInterface(COMMON_BEAN);
0715: } else if (args[i].equalsIgnoreCase("-nocommoninterface")) {
0716: config.setGenerateCommonInterface(null);
0717: } else if (args[i].equalsIgnoreCase("-commoninterfacename")) {
0718: config.setGenerateCommonInterface(args[++i]);
0719: } else if (args[i].equalsIgnoreCase("-compile")) {
0720: config.setDoCompile(true);
0721: } else if (args[i].equalsIgnoreCase("-auto")) {
0722: config.setAuto(true);
0723: } else if (args[i].equalsIgnoreCase("-defaultsaccessable")) {
0724: config.setDefaultsAccessable(true);
0725: } else if (args[i].equalsIgnoreCase("-useinterfaces")) {
0726: config.setUseInterfaces(true);
0727: } else if (args[i].equalsIgnoreCase("-geninterfaces")) {
0728: config.setGenerateInterfaces(true);
0729: } else if (args[i].equalsIgnoreCase("-nogeninterfaces")) {
0730: config.setGenerateInterfaces(false);
0731: } else if (args[i].equalsIgnoreCase("-keepelementpositions")) {
0732: config.setKeepElementPositions(true);
0733: } else if (args[i].equalsIgnoreCase("-comments")) {
0734: config.setProcessComments(true);
0735: } else if (args[i].equalsIgnoreCase("-doctype")) {
0736: config.setProcessDocType(true);
0737: } else if (args[i].equalsIgnoreCase("-dumpbeantree")) {
0738: config.setDumpBeanTree(new File(args[++i]));
0739: } else if (args[i].equalsIgnoreCase("-removeunreferencednodes")) {
0740: config.setRemoveUnreferencedNodes(true);
0741: } else if (args[i].equalsIgnoreCase("-writebeangraph")) {
0742: config.setWriteBeanGraphFile(new File(args[++i]));
0743: } else if (args[i].equalsIgnoreCase("-readbeangraph")) {
0744: config.addReadBeanGraphFiles(new File(args[++i]));
0745: } else if (args[i].equalsIgnoreCase("-gendotgraph")) {
0746: config.setGenerateDotGraph(new File(args[++i]));
0747: } else if (args[i].equalsIgnoreCase("-delegatedir")) {
0748: config.setDelegateDir(new File(args[++i]));
0749: } else if (args[i].equalsIgnoreCase("-delegatepackage")) {
0750: config.setDelegatePackage(args[++i]);
0751: } else if (args[i].equalsIgnoreCase("-checkuptodate")) {
0752: config.setCheckUpToDate(true);
0753: } else if (args[i].equalsIgnoreCase("-haschanged")) {
0754: config.setGenerateHasChanged(true);
0755: } else if (args[i].equalsIgnoreCase("-generateSwitches")) {
0756: config.setGenerateSwitches(true);
0757: } else if (args[i].equalsIgnoreCase("-min")) {
0758: config.setMinFeatures(true);
0759: } else if (args[i].equalsIgnoreCase("-forme")) {
0760: config.setForME(true);
0761: } else if (args[i].equalsIgnoreCase("-tagsfile")) {
0762: config.setGenerateTagsFile(true);
0763: } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("--help")) {
0764: help = 0;
0765: } else {
0766: System.out.println("Unknown argument: "+args[i]);
0767: System.out.println("Use -help.");
0768: System.exit(1);
0769: }
0770: }
0771: } catch (Exception e) {
0772: help = 0;
0773: }
0774:
0775: if (help < 1) {
0776: System.out.println("usage:");
0777: 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");
0778: System.out.println("where:");
0779: System.out.println(" -f file name of the DTD");
0780: System.out.println(" -d DTD root element name (for example webapp or ejb-jar)");
0781: System.out.println(" -p package name");
0782: System.out.println(" -r base root directory (root of the package path)");
0783: System.out.println(" -sp set the indentation to use 'number' spaces instead of \n the default tab (\ ) value");
0784: 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.");
0785: System.out.println(" -noe do not throw the NoSuchElement exception when a scalar property\n has no value, return a default '0' value instead.");
0786: System.out.println(" -ts the toString() of the bean returns the full content\n of the bean sub-tree instead of its simple name.");
0787: System.out.println(" -veto generate vetoable properties (only for non-bean properties).");
0788: System.out.println(" -st standalone mode - do not generate NetBeans dependencies");
0789: System.out.println(" -throw generate code that prefers to pass exceptions\n through instead of converting them to RuntimeException (recommended).");
0790: System.out.println(" -dtd DTD input mode (default)");
0791: System.out.println(" -xmlschema XML Schema input mode");
0792: System.out.println(" -javabeans Generate pure JavaBeans that do not need\n any runtime library support (no BaseBean).");
0793: System.out.println(" -validate Generate a validate method for doing validation.");
0794: System.out.println(" -propertyevents Generate methods for dealing with property events (always on for BaseBean type).");
0795: System.out.println(" -attrprop Attributes become like any other property");
0796: System.out.println(" -delegator Generate a delegator class for every bean generated.");
0797: System.out.println(" -commonInterface Generate a common interface between all beans.");
0798: System.out.println(" -commonInterfaceName Name the common interface.");
0799: 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).");
0800: System.out.println(" -min Generate the minimum Java Beans. Reduce features in favor of reduced class file size.");
0801: System.out.println(" -compile Compile all generated classes using javac.");
0802: System.out.println(" -defaultsAccessable Generate methods to be able to get at default values.");
0803: System.out.println(" -useInterfaces Getters and setters signatures would any defined interface on the bean.");
0804: System.out.println(" -genInterfaces For every bean generated, generate an interfaces for it's accessors.");
0805: System.out.println(" -keepElementPositions Keep track of the positions of elements (no BaseBean support).");
0806: System.out.println(" -dumpBeanTree filename Write out the bean tree to filename.");
0807: System.out.println(" -removeUnreferencedNodes Do not generate unreferenced nodes from the bean graph.");
0808: System.out.println(" -writeBeanGraph Write out a beangraph XML file. Useful for connecting separate bean graphs.");
0809: System.out.println(" -readBeanGraph Read in and use the results of another bean graph.");
0810: System.out.println(" -genDotGraph filename Generate a .dot style file for use with GraphViz.");
0811: System.out.println(" -comments Process and keep comments (always on for BaseBean type).");
0812: System.out.println(" -doctype Process and keep Document Types (always on for BaseBean type).");
0813: System.out.println(" -hasChanged Generate code to keep track if the bean graph has changed.");
0814: System.out.println(" -checkUpToDate Only do generation if the source files are newer than the to be generated files.");
0815: System.out.println(" -forME Generate code for use on J2ME.");
0816: System.out.println(" -tagsFile Generate a class that has all schema element & attribute names");
0817: System.out.println(" -t [parse|gen|all]\ttracing.");
0818:
0819: 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.");
0820: System.out.println("\nexamples: java GenBeans -f ejb.dtd");
0821: System.out.println(" java GenBeans -f webapp.dtd -d webapp -p myproject.webapp -r /myPath/src");
0822: System.out.println(" java GenBeans -f webapp.xsd -xmlschema -r /myPath/src -premium");
0823: System.out.println("\nMost of the parameters are optional. Only the file name is mandatory.");
0824: 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.");
0825: }
0826: else*/
0827: DDLogFlags.debug = config.isTrace();
0828:
0829: try {
0830: doIt(config);
0831: } catch (Exception e) {
0832: e.printStackTrace();
0833: System.exit(1);
0834: }
0835: }
0836:
0837: public static void doIt(Config config) throws java.io.IOException,
0838: Schema2BeansException {
0839: normalizeConfig(config);
0840:
0841: calculateNewestSourceTime(config);
0842:
0843: boolean needToWriteMetaDD = processMetaDD(config);
0844:
0845: // The class that build the DTD object graph
0846: TreeBuilder tree = new TreeBuilder(config);
0847:
0848: // The file parser calling back the handler
0849: SchemaParser parser = null;
0850: boolean tryAgain;
0851: int schemaType = config.getSchemaTypeNum();
0852: SchemaParseException lastException = null;
0853: do {
0854: tryAgain = false;
0855: if (schemaType == Config.XML_SCHEMA) {
0856: XMLSchemaParser xmlSchemaParser = new XMLSchemaParser(
0857: config, tree);
0858: if (config.getInputURI() != null)
0859: xmlSchemaParser.setInputURI(config.getInputURI());
0860: parser = xmlSchemaParser;
0861: } else {
0862: parser = new DocDefParser(config, tree);
0863: }
0864: readBeanGraphs(config);
0865:
0866: try {
0867: // parse the DTD, building the object graph
0868: parser.process();
0869: } catch (SchemaParseException e) {
0870: if (schemaType == Config.DTD) {
0871: // Retry as XML Schema
0872: tryAgain = true;
0873: schemaType = Config.XML_SCHEMA;
0874: } else {
0875: if (lastException == null)
0876: throw e;
0877: else
0878: throw lastException;
0879: }
0880: lastException = e;
0881: }
0882: } while (tryAgain);
0883: config.setSchemaTypeNum(schemaType);
0884:
0885: // Build the beans from the graph, and code generate them out to disk.
0886: BeanBuilder builder = new BeanBuilder(tree, config, config
0887: .getCodeGeneratorFactory());
0888: builder.process();
0889:
0890: if (needToWriteMetaDD) {
0891: try {
0892: config.messageOut.println("Writing metaDD XML file"); // NOI18N
0893: FileOutputStream mddOut = new FileOutputStream(config
0894: .getMddFile());
0895: config.getMetaDD().write(mddOut);
0896: mddOut.close();
0897: } catch (IOException e) {
0898: config.messageOut
0899: .println("Failed to write the mdd file: "
0900: + e.getMessage()); // NOI18N
0901: throw e;
0902: }
0903: }
0904:
0905: if (config.isDoCompile()
0906: && config.getOutputStreamProvider() instanceof DefaultOutputStreamProvider) {
0907: DefaultOutputStreamProvider out = (DefaultOutputStreamProvider) config
0908: .getOutputStreamProvider();
0909: String[] javacArgs = new String[out.getGeneratedFiles()
0910: .size()];
0911: int javaFileCount = 0;
0912: for (Iterator it = out.getGeneratedFiles().iterator(); it
0913: .hasNext();) {
0914: javacArgs[javaFileCount] = (String) it.next();
0915: ++javaFileCount;
0916: }
0917:
0918: if (javaFileCount == 0) {
0919: if (!config.isQuiet())
0920: config.messageOut.println(Common
0921: .getMessage("MSG_NothingToCompile"));
0922: } else {
0923: if (!config.isQuiet())
0924: config.messageOut.println(Common
0925: .getMessage("MSG_Compiling"));
0926: try {
0927: Class javacClass = Class
0928: .forName("com.sun.tools.javac.Main");
0929: java.lang.reflect.Method compileMethod = javacClass
0930: .getDeclaredMethod("compile", new Class[] {
0931: String[].class, PrintWriter.class });
0932: // com.sun.tools.javac.Main.compile(javacArgs, pw);
0933: PrintWriter pw = new PrintWriter(config.messageOut,
0934: true);
0935: Object result = compileMethod.invoke(null,
0936: new Object[] { javacArgs, pw });
0937: pw.flush();
0938: int compileExitCode = 0;
0939: if (result instanceof Integer)
0940: compileExitCode = ((Integer) result).intValue();
0941: if (compileExitCode != 0)
0942: throw new RuntimeException(
0943: "Compile errors: javac had an exit code of "
0944: + compileExitCode);
0945: } catch (java.lang.Exception e) {
0946: // Maybe it's just a missing $JRE/tools.jar from
0947: // the CLASSPATH.
0948: //config.messageOut.println(Common.getMessage("MSG_UnableToCompile"));
0949: //config.messageOut.println(e.getClass().getName()+": "+e.getMessage()); // NOI18N
0950: //e.printStackTrace();
0951: if (e instanceof IOException)
0952: throw (IOException) e;
0953: if (e instanceof Schema2BeansException)
0954: throw (Schema2BeansException) e;
0955: throw new Schema2BeansNestedException(Common
0956: .getMessage("MSG_UnableToCompile"), e);
0957: }
0958: }
0959: }
0960: }
0961:
0962: // Do some config parameter validation/adjustment.
0963: protected static void normalizeConfig(Config config)
0964: throws IOException {
0965: if (config.getIndentAmount() > 0) {
0966: config.setIndent("");
0967: for (int i = 0; i < config.getIndentAmount(); i++)
0968: config.setIndent(config.getIndent() + " ");
0969: }
0970: if (config.isGenerateTransactions()) {
0971: config.setGeneratePropertyEvents(true);
0972: config.setGenerateStoreEvents(true);
0973: } else if (!config.isGeneratePropertyEvents()
0974: && config.isGenerateStoreEvents())
0975: config.setGenerateStoreEvents(false);
0976: if (config.isGenerateHasChanged())
0977: config.setGenerateParentRefs(true);
0978:
0979: config.readConfigs();
0980: if (config.getWriteConfig() != null) {
0981: config.write(new FileOutputStream(config.getWriteConfig()));
0982: }
0983: }
0984:
0985: private static void readBeanGraphs(Config config)
0986: throws IOException {
0987: try {
0988: for (Iterator it = config.readBeanGraphFiles(); it
0989: .hasNext();) {
0990: File filename = (File) it.next();
0991: InputStream in = new FileInputStream(filename);
0992: org.netbeans.modules.schema2beansdev.beangraph.BeanGraph bg = org.netbeans.modules.schema2beansdev.beangraph.BeanGraph
0993: .read(in);
0994: in.close();
0995: config.addReadBeanGraphs(bg);
0996: }
0997: } catch (javax.xml.parsers.ParserConfigurationException e) {
0998: throw new RuntimeException(e);
0999: } catch (org.xml.sax.SAXException e) {
1000: throw new RuntimeException(e);
1001: }
1002: }
1003:
1004: /**
1005: * @return whether or not the MetaDD should be written out at the end.
1006: */
1007: private static boolean processMetaDD(Config config)
1008: throws IOException {
1009: boolean needToWriteMetaDD = false;
1010: MetaDD mdd;
1011: //
1012: // Either creates the metaDD file or read the existing one
1013: //
1014: if (config.getMddFile() != null || config.getMddIn() != null) {
1015: File file = config.getMddFile();
1016:
1017: if (config.getMddIn() == null && !file.exists()) {
1018: config.setDoGeneration(false);
1019: if (!config.isAuto()) {
1020: if (!askYesOrNo(config.messageOut, "The mdd file "
1021: + config.getMddFile() + // NOI18N
1022: " doesn't exist. Should we create it (y/n)? ")) { // NOI18N
1023: config.messageOut
1024: .println("Generation aborted."); // NOI18N
1025: return false;
1026: }
1027: }
1028: needToWriteMetaDD = true;
1029: mdd = new MetaDD();
1030: } else {
1031: try {
1032: InputStream is = config.getMddIn();
1033: if (config.getMddIn() == null) {
1034: is = new FileInputStream(config.getMddFile());
1035: config.messageOut.println(Common.getMessage(
1036: "MSG_UsingMdd", config.getMddFile()));
1037: }
1038: mdd = MetaDD.read(is);
1039: if (config.getMddIn() == null) {
1040: is.close();
1041: }
1042: } catch (IOException e) {
1043: if (config.isTraceParse())
1044: e.printStackTrace();
1045: throw new IOException(Common.getMessage(
1046: "CantCreateMetaDDFile_msg", e.getMessage()));
1047: } catch (javax.xml.parsers.ParserConfigurationException e) {
1048: if (config.isTraceParse())
1049: e.printStackTrace();
1050: throw new IOException(Common.getMessage(
1051: "CantCreateMetaDDFile_msg", e.getMessage()));
1052: } catch (org.xml.sax.SAXException e) {
1053: if (config.isTraceParse())
1054: e.printStackTrace();
1055: throw new IOException(Common.getMessage(
1056: "CantCreateMetaDDFile_msg", e.getMessage()));
1057: }
1058: }
1059: } else {
1060: // Create a MetaDD to look stuff up in later on, even though
1061: // it wasn't read in, and we're not going to write it out.
1062: mdd = new MetaDD();
1063: }
1064: config.setMetaDD(mdd);
1065: return needToWriteMetaDD;
1066: }
1067:
1068: private static boolean askYesOrNo(PrintStream out, String prompt)
1069: throws IOException {
1070: out.print(prompt);
1071: BufferedReader rd = new BufferedReader(new InputStreamReader(
1072: System.in));
1073:
1074: String str;
1075: str = rd.readLine();
1076:
1077: return str.equalsIgnoreCase("y"); // NOI18N
1078: }
1079:
1080: private static void calculateNewestSourceTime(Config config) {
1081: if (config.getFilename() != null) {
1082: config.setIfNewerSourceTime(config.getFilename()
1083: .lastModified());
1084: }
1085: if (config.getMddFile() != null) {
1086: config.setIfNewerSourceTime(config.getMddFile()
1087: .lastModified());
1088: }
1089: for (Iterator it = config.readBeanGraphFiles(); it.hasNext();) {
1090: File f = (File) it.next();
1091: config.setIfNewerSourceTime(f.lastModified());
1092: }
1093:
1094: // Need to also check the times on schema2beans.jar & schema2beansdev.jar
1095: config
1096: .setIfNewerSourceTime(getLastModified(org.netbeans.modules.schema2beans.BaseBean.class));
1097: config.setIfNewerSourceTime(getLastModified(BeanClass.class));
1098: config.setIfNewerSourceTime(getLastModified(GenBeans.class));
1099: config.setIfNewerSourceTime(getLastModified(BeanBuilder.class));
1100: config.setIfNewerSourceTime(getLastModified(TreeBuilder.class));
1101: config.setIfNewerSourceTime(getLastModified(GraphLink.class));
1102: config.setIfNewerSourceTime(getLastModified(GraphNode.class));
1103: config
1104: .setIfNewerSourceTime(getLastModified(JavaBeanClass.class));
1105: //System.out.println("config.getNewestSourceTime="+config.getNewestSourceTime());
1106: }
1107:
1108: private static long getLastModified(Class cls) {
1109: try {
1110: String shortName = cls.getName().substring(
1111: 1 + cls.getName().lastIndexOf('.'));
1112: java.net.URL url = cls.getResource(shortName + ".class");
1113: String file = url.getFile();
1114: //System.out.println("url="+url);
1115: if ("file".equals(url.getProtocol())) {
1116: // example: file='/home/cliffwd/cvs/dublin/nb_all/schema2beans/rt/src/org/netbeans/modules/schema2beans/GenBeans.class'
1117: String result = file.substring(0, file.length()
1118: - cls.getName().length() - 6);
1119: return new File(file).lastModified();
1120: } else if ("jar".equals(url.getProtocol())) {
1121: // example: file = 'jar:/usr/local/j2sdkee1.3.1/lib/j2ee.jar!/org/w3c/dom/Node.class'
1122: String jarFile = file.substring(file.indexOf(':') + 1);
1123: jarFile = jarFile.substring(0, jarFile.indexOf('!'));
1124: //System.out.println("jarFile="+jarFile);
1125: return new File(jarFile).lastModified();
1126: }
1127: return url.openConnection().getDate();
1128: } catch (java.io.IOException e) {
1129: return 0;
1130: }
1131: }
1132: }
1133:
1134: //******************************************************************************
1135: // END_NOI18N
1136: //******************************************************************************
|