Source Code Cross Referenced for Options.java in  » 6.0-JDK-Modules » jaxb-xjc » com » sun » tools » xjc » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules » jaxb xjc » com.sun.tools.xjc 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


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 Development
0008:         * and Distribution License("CDDL") (collectively, the "License").  You
0009:         * may not use this file except in compliance with the License. You can obtain
0010:         * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
0011:         * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
0012:         * language governing permissions and limitations under the License.
0013:         * 
0014:         * When distributing the software, include this License Header Notice in each
0015:         * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
0016:         * Sun designates this particular file as subject to the "Classpath" exception
0017:         * as provided by Sun in the GPL Version 2 section of the License file that
0018:         * accompanied this code.  If applicable, add the following below the License
0019:         * Header, with the fields enclosed by brackets [] replaced by your own
0020:         * identifying information: "Portions Copyrighted [year]
0021:         * [name of copyright owner]"
0022:         * 
0023:         * Contributor(s):
0024:         * 
0025:         * If you wish your version of this file to be governed by only the CDDL or
0026:         * only the GPL Version 2, indicate your decision by adding "[Contributor]
0027:         * elects to include this software in this distribution under the [CDDL or GPL
0028:         * Version 2] license."  If you don't indicate a single choice of license, a
0029:         * recipient has the option to distribute your version of this file under
0030:         * either the CDDL, the GPL Version 2 or to extend the choice of license to
0031:         * its licensees as provided above.  However, if you add GPL Version 2 code
0032:         * and therefore, elected the GPL Version 2 license, then the option applies
0033:         * only if the new code is made subject to such option by the copyright
0034:         * holder.
0035:         */
0036:
0037:        package com.sun.tools.xjc;
0038:
0039:        import java.io.BufferedReader;
0040:        import java.io.File;
0041:        import java.io.FileInputStream;
0042:        import java.io.IOException;
0043:        import java.io.InputStreamReader;
0044:        import java.io.PrintWriter;
0045:        import java.io.StringWriter;
0046:        import java.lang.reflect.Array;
0047:        import java.lang.reflect.InvocationTargetException;
0048:        import java.net.MalformedURLException;
0049:        import java.net.URL;
0050:        import java.net.URLClassLoader;
0051:        import java.text.SimpleDateFormat;
0052:        import java.util.ArrayList;
0053:        import java.util.Date;
0054:        import java.util.Enumeration;
0055:        import java.util.HashSet;
0056:        import java.util.List;
0057:        import java.util.Set;
0058:        import java.util.regex.Matcher;
0059:        import java.util.regex.Pattern;
0060:
0061:        import com.sun.codemodel.CodeWriter;
0062:        import com.sun.codemodel.JPackage;
0063:        import com.sun.codemodel.JResourceFile;
0064:        import com.sun.codemodel.writer.FileCodeWriter;
0065:        import com.sun.codemodel.writer.PrologCodeWriter;
0066:        import com.sun.org.apache.xml.internal.resolver.CatalogManager;
0067:        import com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver;
0068:        import com.sun.tools.xjc.api.ClassNameAllocator;
0069:        import com.sun.tools.xjc.api.SpecVersion;
0070:        import com.sun.tools.xjc.generator.bean.field.FieldRendererFactory;
0071:        import com.sun.tools.xjc.model.Model;
0072:        import com.sun.tools.xjc.reader.Util;
0073:        import com.sun.xml.bind.api.impl.NameConverter;
0074:
0075:        import org.xml.sax.EntityResolver;
0076:        import org.xml.sax.InputSource;
0077:
0078:        /**
0079:         * Global options.
0080:         * 
0081:         * <p>
0082:         * This class stores invocation configuration for XJC.
0083:         * The configuration in this class shoule be abstract enough so that
0084:         * it could be parsed from both command-line or Ant.
0085:         */
0086:        public class Options {
0087:            /** If "-debug" is specified. */
0088:            public boolean debugMode;
0089:
0090:            /** If the "-verbose" option is specified. */
0091:            public boolean verbose;
0092:
0093:            /** If the "-quiet" option is specified. */
0094:            public boolean quiet;
0095:
0096:            /** If the -readOnly option is specified. */
0097:            public boolean readOnly;
0098:
0099:            /** No file header comment (to be more friendly with diff.) */
0100:            public boolean noFileHeader;
0101:
0102:            /**
0103:             * Check the source schemas with extra scrutiny.
0104:             * The exact meaning depends on the schema language.
0105:             */
0106:            public boolean strictCheck = true;
0107:
0108:            /**
0109:             * If -explicit-annotation option is specified.
0110:             * <p>
0111:             * This generates code that works around issues specific to 1.4 runtime.
0112:             */
0113:            public boolean runtime14 = false;
0114:
0115:            /**
0116:             * If true, try to resolve name conflicts automatically by assigning mechanical numbers.
0117:             */
0118:            public boolean automaticNameConflictResolution = false;
0119:
0120:            /**
0121:             * strictly follow the compatibility rules and reject schemas that
0122:             * contain features from App. E.2, use vendor binding extensions
0123:             */
0124:            public static final int STRICT = 1;
0125:            /**
0126:             * loosely follow the compatibility rules and allow the use of vendor
0127:             * binding extensions
0128:             */
0129:            public static final int EXTENSION = 2;
0130:
0131:            /**
0132:             * this switch determines how carefully the compiler will follow
0133:             * the compatibility rules in the spec. Either <code>STRICT</code>
0134:             * or <code>EXTENSION</code>.
0135:             */
0136:            public int compatibilityMode = STRICT;
0137:
0138:            public boolean isExtensionMode() {
0139:                return compatibilityMode == EXTENSION;
0140:            }
0141:
0142:            /**
0143:             * Generates output for the specified version of the runtime.
0144:             */
0145:            public SpecVersion target = SpecVersion.V2_1;
0146:
0147:            /**
0148:             * Target direcoty when producing files.
0149:             * <p>
0150:             * This field is not used when XJC is driven through the XJC API.
0151:             * Plugins that need to generate extra files should do so by using
0152:             * {@link JPackage#addResourceFile(JResourceFile)}.
0153:             */
0154:            public File targetDir = new File(".");
0155:
0156:            /**
0157:             * Actually stores {@link CatalogResolver}, but the field
0158:             * type is made to {@link EntityResolver} so that XJC can be
0159:             * used even if resolver.jar is not available in the classpath.
0160:             */
0161:            public EntityResolver entityResolver = null;
0162:
0163:            /**
0164:             * Type of input schema language. One of the <code>SCHEMA_XXX</code>
0165:             * constants.
0166:             */
0167:            private Language schemaLanguage = null;
0168:
0169:            /**
0170:             * The -p option that should control the default Java package that
0171:             * will contain the generated code. Null if unspecified.
0172:             */
0173:            public String defaultPackage = null;
0174:
0175:            /**
0176:             * Similar to the -p option, but this one works with a lower priority,
0177:             * and customizations overrides this. Used by JAX-RPC.
0178:             */
0179:            public String defaultPackage2 = null;
0180:
0181:            /**
0182:             * Input schema files as a list of {@link InputSource}s.
0183:             */
0184:            private final List<InputSource> grammars = new ArrayList<InputSource>();
0185:
0186:            private final List<InputSource> bindFiles = new ArrayList<InputSource>();
0187:
0188:            // Proxy setting.
0189:            private String proxyHost = null;
0190:            private String proxyPort = null;
0191:            private String proxyUser = null;
0192:            private String proxyPassword = null;
0193:
0194:            /**
0195:             * {@link Plugin}s that are enabled in this compilation.
0196:             */
0197:            public final List<Plugin> activePlugins = new ArrayList<Plugin>();
0198:
0199:            /**
0200:             * All discovered {@link Plugin}s.
0201:             * This is lazily parsed, so that we can take '-cp' option into account.
0202:             *
0203:             * @see #getAllPlugins()
0204:             */
0205:            private List<Plugin> allPlugins;
0206:
0207:            /**
0208:             * Set of URIs that plug-ins recognize as extension bindings.
0209:             */
0210:            public final Set<String> pluginURIs = new HashSet<String>();
0211:
0212:            /**
0213:             * This allocator has the final say on deciding the class name.
0214:             */
0215:            public ClassNameAllocator classNameAllocator;
0216:
0217:            /**
0218:             * This switch controls whether or not xjc will generate package level annotations
0219:             */
0220:            public boolean packageLevelAnnotations = true;
0221:
0222:            /**
0223:             * This {@link FieldRendererFactory} determines how the fields are generated.
0224:             */
0225:            private FieldRendererFactory fieldRendererFactory = new FieldRendererFactory();
0226:            /**
0227:             * Used to detect if two {@link Plugin}s try to overwrite {@link #fieldRendererFactory}.
0228:             */
0229:            private Plugin fieldRendererFactoryOwner = null;
0230:
0231:            /**
0232:             * If this is non-null, we use this {@link NameConverter} over the one
0233:             * given in the schema/binding.
0234:             */
0235:            private NameConverter nameConverter = null;
0236:            /**
0237:             * Used to detect if two {@link Plugin}s try to overwrite {@link #nameConverter}.
0238:             */
0239:            private Plugin nameConverterOwner = null;
0240:
0241:            /**
0242:             * Gets the active {@link FieldRendererFactory} that shall be used to build {@link Model}.
0243:             *
0244:             * @return always non-null.
0245:             */
0246:            public FieldRendererFactory getFieldRendererFactory() {
0247:                return fieldRendererFactory;
0248:            }
0249:
0250:            /**
0251:             * Sets the {@link FieldRendererFactory}.
0252:             *
0253:             * <p>
0254:             * This method is for plugins to call to set a custom {@link FieldRendererFactory}.
0255:             *
0256:             * @param frf
0257:             *      The {@link FieldRendererFactory} to be installed. Must not be null.
0258:             * @param owner
0259:             *      Identifies the plugin that owns this {@link FieldRendererFactory}.
0260:             *      When two {@link Plugin}s try to call this method, this allows XJC
0261:             *      to report it as a user-friendly error message.
0262:             *
0263:             * @throws BadCommandLineException
0264:             *      If a conflit happens, this exception carries a user-friendly error
0265:             *      message, indicating a conflict.
0266:             */
0267:            public void setFieldRendererFactory(FieldRendererFactory frf,
0268:                    Plugin owner) throws BadCommandLineException {
0269:                // since this method is for plugins, make it bit more fool-proof than usual
0270:                if (frf == null)
0271:                    throw new IllegalArgumentException();
0272:                if (fieldRendererFactoryOwner != null) {
0273:                    throw new BadCommandLineException(Messages.format(
0274:                            Messages.FIELD_RENDERER_CONFLICT,
0275:                            fieldRendererFactoryOwner.getOptionName(), owner
0276:                                    .getOptionName()));
0277:                }
0278:                this .fieldRendererFactoryOwner = owner;
0279:                this .fieldRendererFactory = frf;
0280:            }
0281:
0282:            /**
0283:             * Gets the active {@link NameConverter} that shall be used to build {@link Model}.
0284:             *
0285:             * @return can be null, in which case it's up to the binding.
0286:             */
0287:            public NameConverter getNameConverter() {
0288:                return nameConverter;
0289:            }
0290:
0291:            /**
0292:             * Sets the {@link NameConverter}.
0293:             *
0294:             * <p>
0295:             * This method is for plugins to call to set a custom {@link NameConverter}.
0296:             *
0297:             * @param nc
0298:             *      The {@link NameConverter} to be installed. Must not be null.
0299:             * @param owner
0300:             *      Identifies the plugin that owns this {@link NameConverter}.
0301:             *      When two {@link Plugin}s try to call this method, this allows XJC
0302:             *      to report it as a user-friendly error message.
0303:             *
0304:             * @throws BadCommandLineException
0305:             *      If a conflit happens, this exception carries a user-friendly error
0306:             *      message, indicating a conflict.
0307:             */
0308:            public void setNameConverter(NameConverter nc, Plugin owner)
0309:                    throws BadCommandLineException {
0310:                // since this method is for plugins, make it bit more fool-proof than usual
0311:                if (nc == null)
0312:                    throw new IllegalArgumentException();
0313:                if (nameConverter != null) {
0314:                    throw new BadCommandLineException(Messages.format(
0315:                            Messages.NAME_CONVERTER_CONFLICT,
0316:                            nameConverterOwner.getOptionName(), owner
0317:                                    .getOptionName()));
0318:                }
0319:                this .nameConverterOwner = owner;
0320:                this .nameConverter = nc;
0321:            }
0322:
0323:            /**
0324:             * Gets all the {@link Plugin}s discovered so far.
0325:             *
0326:             * <p>
0327:             * A plugins are enumerated when this method is called for the first time,
0328:             * by taking {@link #classpaths} into account. That means
0329:             * "-cp plugin.jar" has to come before you specify options to enable it.
0330:             */
0331:            public List<Plugin> getAllPlugins() {
0332:                if (allPlugins == null) {
0333:                    allPlugins = new ArrayList<Plugin>();
0334:                    ClassLoader ucl = getUserClassLoader(getClass()
0335:                            .getClassLoader());
0336:                    for (Plugin aug : findServices(Plugin.class, ucl))
0337:                        allPlugins.add(aug);
0338:                }
0339:
0340:                return allPlugins;
0341:            }
0342:
0343:            public Language getSchemaLanguage() {
0344:                if (schemaLanguage == null)
0345:                    schemaLanguage = guessSchemaLanguage();
0346:                return schemaLanguage;
0347:            }
0348:
0349:            public void setSchemaLanguage(Language _schemaLanguage) {
0350:                this .schemaLanguage = _schemaLanguage;
0351:            }
0352:
0353:            /** Input schema files. */
0354:            public InputSource[] getGrammars() {
0355:                return grammars.toArray(new InputSource[grammars.size()]);
0356:            }
0357:
0358:            /**
0359:             * Adds a new input schema.
0360:             */
0361:            public void addGrammar(InputSource is) {
0362:                grammars.add(absolutize(is));
0363:            }
0364:
0365:            private InputSource fileToInputSource(File source) {
0366:                try {
0367:                    String url = source.toURL().toExternalForm();
0368:                    return new InputSource(Util.escapeSpace(url));
0369:                } catch (MalformedURLException e) {
0370:                    return new InputSource(source.getPath());
0371:                }
0372:            }
0373:
0374:            public void addGrammar(File source) {
0375:                addGrammar(fileToInputSource(source));
0376:            }
0377:
0378:            /**
0379:             * Recursively scan directories and add all XSD files in it.
0380:             */
0381:            public void addGrammarRecursive(File dir) {
0382:                addRecursive(dir, ".xsd", grammars);
0383:            }
0384:
0385:            private void addRecursive(File dir, String suffix,
0386:                    List<InputSource> result) {
0387:                File[] files = dir.listFiles();
0388:                if (files == null)
0389:                    return; // work defensively
0390:
0391:                for (File f : files) {
0392:                    if (f.isDirectory())
0393:                        addRecursive(f, suffix, result);
0394:                    else if (f.getPath().endsWith(suffix))
0395:                        result.add(absolutize(fileToInputSource(f)));
0396:                }
0397:            }
0398:
0399:            private InputSource absolutize(InputSource is) {
0400:                // absolutize all the system IDs in the input,
0401:                // so that we can map system IDs to DOM trees.
0402:                try {
0403:                    URL baseURL = new File(".").getCanonicalFile().toURL();
0404:                    is.setSystemId(new URL(baseURL, is.getSystemId())
0405:                            .toExternalForm());
0406:                } catch (IOException e) {
0407:                    // ignore
0408:                }
0409:                return is;
0410:            }
0411:
0412:            /** Input external binding files. */
0413:            public InputSource[] getBindFiles() {
0414:                return bindFiles.toArray(new InputSource[bindFiles.size()]);
0415:            }
0416:
0417:            /**
0418:             * Adds a new binding file.
0419:             */
0420:            public void addBindFile(InputSource is) {
0421:                bindFiles.add(absolutize(is));
0422:            }
0423:
0424:            /**
0425:             * Adds a new binding file.
0426:             */
0427:            public void addBindFile(File bindFile) {
0428:                bindFiles.add(fileToInputSource(bindFile));
0429:            }
0430:
0431:            /**
0432:             * Recursively scan directories and add all ".xjb" files in it.
0433:             */
0434:            public void addBindFileRecursive(File dir) {
0435:                addRecursive(dir, ".xjb", bindFiles);
0436:            }
0437:
0438:            public final List<URL> classpaths = new ArrayList<URL>();
0439:
0440:            /**
0441:             * Gets a classLoader that can load classes specified via the
0442:             * -classpath option.
0443:             */
0444:            public URLClassLoader getUserClassLoader(ClassLoader parent) {
0445:                return new URLClassLoader(classpaths.toArray(new URL[classpaths
0446:                        .size()]), parent);
0447:            }
0448:
0449:            /**
0450:             * Parses an option <code>args[i]</code> and return
0451:             * the number of tokens consumed.
0452:             * 
0453:             * @return
0454:             *      0 if the argument is not understood. Returning 0
0455:             *      will let the caller report an error.
0456:             * @exception BadCommandLineException
0457:             *      If the callee wants to provide a custom message for an error.
0458:             */
0459:            public int parseArgument(String[] args, int i)
0460:                    throws BadCommandLineException {
0461:                if (args[i].equals("-classpath") || args[i].equals("-cp")) {
0462:                    File file = new File(requireArgument(args[i], args, ++i));
0463:                    try {
0464:                        classpaths.add(file.toURL());
0465:                    } catch (MalformedURLException e) {
0466:                        throw new BadCommandLineException(Messages.format(
0467:                                Messages.NOT_A_VALID_FILENAME, file), e);
0468:                    }
0469:                    return 2;
0470:                }
0471:                if (args[i].equals("-d")) {
0472:                    targetDir = new File(requireArgument("-d", args, ++i));
0473:                    if (!targetDir.exists())
0474:                        throw new BadCommandLineException(Messages.format(
0475:                                Messages.NON_EXISTENT_DIR, targetDir));
0476:                    return 2;
0477:                }
0478:                if (args[i].equals("-readOnly")) {
0479:                    readOnly = true;
0480:                    return 1;
0481:                }
0482:                if (args[i].equals("-p")) {
0483:                    defaultPackage = requireArgument("-p", args, ++i);
0484:                    if (defaultPackage.length() == 0) { // user specified default package
0485:                        // there won't be any package to annotate, so disable them
0486:                        // automatically as a usability feature
0487:                        packageLevelAnnotations = false;
0488:                    }
0489:                    return 2;
0490:                }
0491:                if (args[i].equals("-debug")) {
0492:                    debugMode = true;
0493:                    verbose = true;
0494:                    return 1;
0495:                }
0496:                if (args[i].equals("-nv")) {
0497:                    strictCheck = false;
0498:                    return 1;
0499:                }
0500:                if (args[i].equals("-npa")) {
0501:                    packageLevelAnnotations = false;
0502:                    return 1;
0503:                }
0504:                if (args[i].equals("-no-header")) {
0505:                    noFileHeader = true;
0506:                    return 1;
0507:                }
0508:                if (args[i].equals("-verbose")) {
0509:                    verbose = true;
0510:                    return 1;
0511:                }
0512:                if (args[i].equals("-quiet")) {
0513:                    quiet = true;
0514:                    return 1;
0515:                }
0516:                if (args[i].equals("-XexplicitAnnotation")) {
0517:                    runtime14 = true;
0518:                    return 1;
0519:                }
0520:                if (args[i].equals("-XautoNameResolution")) {
0521:                    automaticNameConflictResolution = true;
0522:                    return 1;
0523:                }
0524:                if (args[i].equals("-b")) {
0525:                    addFile(requireArgument("-b", args, ++i), bindFiles, ".xjb");
0526:                    return 2;
0527:                }
0528:                if (args[i].equals("-dtd")) {
0529:                    schemaLanguage = Language.DTD;
0530:                    return 1;
0531:                }
0532:                if (args[i].equals("-relaxng")) {
0533:                    schemaLanguage = Language.RELAXNG;
0534:                    return 1;
0535:                }
0536:                if (args[i].equals("-relaxng-compact")) {
0537:                    schemaLanguage = Language.RELAXNG_COMPACT;
0538:                    return 1;
0539:                }
0540:                if (args[i].equals("-xmlschema")) {
0541:                    schemaLanguage = Language.XMLSCHEMA;
0542:                    return 1;
0543:                }
0544:                if (args[i].equals("-wsdl")) {
0545:                    schemaLanguage = Language.WSDL;
0546:                    return 1;
0547:                }
0548:                if (args[i].equals("-extension")) {
0549:                    compatibilityMode = EXTENSION;
0550:                    return 1;
0551:                }
0552:                if (args[i].equals("-target")) {
0553:                    String token = requireArgument("-target", args, ++i);
0554:                    target = SpecVersion.parse(token);
0555:                    if (target == null)
0556:                        throw new BadCommandLineException(Messages.format(
0557:                                Messages.ILLEGAL_TARGET_VERSION, token));
0558:                    return 2;
0559:                }
0560:                if (args[i].equals("-httpproxyfile")) {
0561:                    if (i == args.length - 1 || args[i + 1].startsWith("-")) {
0562:                        throw new BadCommandLineException(Messages
0563:                                .format(Messages.MISSING_PROXYFILE));
0564:                    }
0565:
0566:                    File file = new File(args[++i]);
0567:                    if (!file.exists()) {
0568:                        throw new BadCommandLineException(Messages.format(
0569:                                Messages.NO_SUCH_FILE, file));
0570:                    }
0571:
0572:                    try {
0573:                        BufferedReader in = new BufferedReader(
0574:                                new InputStreamReader(
0575:                                        new FileInputStream(file), "UTF-8"));
0576:                        parseProxy(in.readLine());
0577:                        in.close();
0578:                    } catch (IOException e) {
0579:                        throw new BadCommandLineException(
0580:                                Messages.format(Messages.FAILED_TO_PARSE, file,
0581:                                        e.getMessage()), e);
0582:                    }
0583:
0584:                    return 2;
0585:                }
0586:                if (args[i].equals("-httpproxy")) {
0587:                    if (i == args.length - 1 || args[i + 1].startsWith("-")) {
0588:                        throw new BadCommandLineException(Messages
0589:                                .format(Messages.MISSING_PROXY));
0590:                    }
0591:
0592:                    parseProxy(args[++i]);
0593:                    return 2;
0594:                }
0595:                if (args[i].equals("-host")) {
0596:                    proxyHost = requireArgument("-host", args, ++i);
0597:                    return 2;
0598:                }
0599:                if (args[i].equals("-port")) {
0600:                    proxyPort = requireArgument("-port", args, ++i);
0601:                    return 2;
0602:                }
0603:                if (args[i].equals("-catalog")) {
0604:                    // use Sun's "XML Entity and URI Resolvers" by Norman Walsh
0605:                    // to resolve external entities.
0606:                    // http://www.sun.com/xml/developers/resolver/
0607:
0608:                    File catalogFile = new File(requireArgument("-catalog",
0609:                            args, ++i));
0610:                    try {
0611:                        addCatalog(catalogFile);
0612:                    } catch (IOException e) {
0613:                        throw new BadCommandLineException(Messages.format(
0614:                                Messages.FAILED_TO_PARSE, catalogFile, e
0615:                                        .getMessage()), e);
0616:                    }
0617:                    return 2;
0618:                }
0619:                if (args[i].equals("-source")) {
0620:                    String version = requireArgument("-source", args, ++i);
0621:                    //For source 1.0 the 1.0 Driver is loaded
0622:                    //Hence anything other than 2.0 is defaulted to
0623:                    //2.0
0624:                    if (!version.equals("2.0") && !version.equals("2.1"))
0625:                        throw new BadCommandLineException(Messages
0626:                                .format(Messages.DEFAULT_VERSION));
0627:                    return 2;
0628:                }
0629:                if (args[i].equals("-Xtest-class-name-allocator")) {
0630:                    classNameAllocator = new ClassNameAllocator() {
0631:                        public String assignClassName(String packageName,
0632:                                String className) {
0633:                            System.out.printf("assignClassName(%s,%s)\n",
0634:                                    packageName, className);
0635:                            return className + "_Type";
0636:                        }
0637:                    };
0638:                    return 1;
0639:                }
0640:
0641:                // see if this is one of the extensions
0642:                for (Plugin plugin : getAllPlugins()) {
0643:                    try {
0644:                        if (('-' + plugin.getOptionName()).equals(args[i])) {
0645:                            activePlugins.add(plugin);
0646:                            plugin.onActivated(this );
0647:                            pluginURIs.addAll(plugin.getCustomizationURIs());
0648:
0649:                            // give the plugin a chance to parse arguments to this option.
0650:                            // this is new in 2.1, and due to the backward compatibility reason,
0651:                            // if plugin didn't understand it, we still return 1 to indicate
0652:                            // that this option is consumed.
0653:                            int r = plugin.parseArgument(this , args, i);
0654:                            if (r != 0)
0655:                                return r;
0656:                            else
0657:                                return 1;
0658:                        }
0659:
0660:                        int r = plugin.parseArgument(this , args, i);
0661:                        if (r != 0)
0662:                            return r;
0663:                    } catch (IOException e) {
0664:                        throw new BadCommandLineException(e.getMessage(), e);
0665:                    }
0666:                }
0667:
0668:                return 0; // unrecognized
0669:            }
0670:
0671:            private void parseProxy(String text) throws BadCommandLineException {
0672:                // syntax is [user[:password]@]proxyHost:proxyPort
0673:                String token = "([^@:]+)";
0674:                Pattern p = Pattern.compile("(?:" + token + "(?:\\:" + token
0675:                        + ")?\\@)?" + token + "(?:\\:" + token + ")");
0676:
0677:                Matcher matcher = p.matcher(text);
0678:                if (!matcher.matches())
0679:                    throw new BadCommandLineException(Messages.format(
0680:                            Messages.ILLEGAL_PROXY, text));
0681:
0682:                proxyUser = matcher.group(1);
0683:                proxyPassword = matcher.group(2);
0684:                proxyHost = matcher.group(3);
0685:                proxyPort = matcher.group(4);
0686:                try {
0687:                    Integer.valueOf(proxyPort);
0688:                } catch (NumberFormatException e) {
0689:                    throw new BadCommandLineException(Messages.format(
0690:                            Messages.ILLEGAL_PROXY, text));
0691:                }
0692:            }
0693:
0694:            /**
0695:             * Obtains an operand and reports an error if it's not there.
0696:             */
0697:            public String requireArgument(String optionName, String[] args,
0698:                    int i) throws BadCommandLineException {
0699:                if (i == args.length || args[i].startsWith("-")) {
0700:                    throw new BadCommandLineException(Messages.format(
0701:                            Messages.MISSING_OPERAND, optionName));
0702:                }
0703:                return args[i];
0704:            }
0705:
0706:            /**
0707:             * Parses a token to a file (or a set of files)
0708:             * and add them as {@link InputSource} to the specified list.
0709:             *
0710:             * @param suffix
0711:             *      If the given token is a directory name, we do a recusive search
0712:             *      and find all files that have the given suffix.
0713:             */
0714:            private void addFile(String name, List<InputSource> target,
0715:                    String suffix) throws BadCommandLineException {
0716:                Object src;
0717:                try {
0718:                    src = Util.getFileOrURL(name);
0719:                } catch (IOException e) {
0720:                    throw new BadCommandLineException(Messages.format(
0721:                            Messages.NOT_A_FILE_NOR_URL, name));
0722:                }
0723:                if (src instanceof  URL) {
0724:                    target.add(absolutize(new InputSource(Util
0725:                            .escapeSpace(((URL) src).toExternalForm()))));
0726:                } else {
0727:                    File fsrc = (File) src;
0728:                    if (fsrc.isDirectory()) {
0729:                        addRecursive(fsrc, suffix, target);
0730:                    } else {
0731:                        target.add(absolutize(fileToInputSource(fsrc)));
0732:                    }
0733:                }
0734:            }
0735:
0736:            /**
0737:             * Adds a new catalog file.
0738:             */
0739:            public void addCatalog(File catalogFile) throws IOException {
0740:                if (entityResolver == null) {
0741:                    CatalogManager.getStaticManager()
0742:                            .setIgnoreMissingProperties(true);
0743:                    entityResolver = new CatalogResolver(true);
0744:                }
0745:                ((CatalogResolver) entityResolver).getCatalog().parseCatalog(
0746:                        catalogFile.getPath());
0747:            }
0748:
0749:            /**
0750:             * Parses arguments and fill fields of this object.
0751:             * 
0752:             * @exception BadCommandLineException
0753:             *      thrown when there's a problem in the command-line arguments
0754:             */
0755:            public void parseArguments(String[] args)
0756:                    throws BadCommandLineException {
0757:
0758:                for (int i = 0; i < args.length; i++) {
0759:                    if (args[i].length() == 0)
0760:                        throw new BadCommandLineException();
0761:                    if (args[i].charAt(0) == '-') {
0762:                        int j = parseArgument(args, i);
0763:                        if (j == 0)
0764:                            throw new BadCommandLineException(Messages.format(
0765:                                    Messages.UNRECOGNIZED_PARAMETER, args[i]));
0766:                        i += (j - 1);
0767:                    } else {
0768:                        if (args[i].endsWith(".jar"))
0769:                            scanEpisodeFile(new File(args[i]));
0770:                        else
0771:                            addFile(args[i], grammars, ".xsd");
0772:                    }
0773:                }
0774:
0775:                // configure proxy
0776:                if (proxyHost != null || proxyPort != null) {
0777:                    if (proxyHost != null && proxyPort != null) {
0778:                        System.setProperty("http.proxyHost", proxyHost);
0779:                        System.setProperty("http.proxyPort", proxyPort);
0780:                        System.setProperty("https.proxyHost", proxyHost);
0781:                        System.setProperty("https.proxyPort", proxyPort);
0782:                    } else if (proxyHost == null) {
0783:                        throw new BadCommandLineException(Messages
0784:                                .format(Messages.MISSING_PROXYHOST));
0785:                    } else {
0786:                        throw new BadCommandLineException(Messages
0787:                                .format(Messages.MISSING_PROXYPORT));
0788:                    }
0789:                    if (proxyUser != null)
0790:                        System.setProperty("http.proxyUser", proxyUser);
0791:                    if (proxyPassword != null)
0792:                        System.setProperty("http.proxyPassword", proxyPassword);
0793:
0794:                }
0795:
0796:                if (grammars.size() == 0)
0797:                    throw new BadCommandLineException(Messages
0798:                            .format(Messages.MISSING_GRAMMAR));
0799:
0800:                if (schemaLanguage == null)
0801:                    schemaLanguage = guessSchemaLanguage();
0802:
0803:                if (pluginLoadFailure != null)
0804:                    throw new BadCommandLineException(Messages.format(
0805:                            Messages.PLUGIN_LOAD_FAILURE, pluginLoadFailure));
0806:            }
0807:
0808:            /**
0809:             * Finds the <tt>META-INF/sun-jaxb.episode</tt> file to add as a binding customization.
0810:             */
0811:            private void scanEpisodeFile(File jar)
0812:                    throws BadCommandLineException {
0813:                try {
0814:                    URLClassLoader ucl = new URLClassLoader(new URL[] { jar
0815:                            .toURL() });
0816:                    Enumeration<URL> resources = ucl
0817:                            .findResources("META-INF/sun-jaxb.episode");
0818:                    while (resources.hasMoreElements()) {
0819:                        URL url = resources.nextElement();
0820:                        addBindFile(new InputSource(url.toExternalForm()));
0821:                    }
0822:                } catch (IOException e) {
0823:                    throw new BadCommandLineException(Messages.format(
0824:                            Messages.FAILED_TO_LOAD, jar, e.getMessage()), e);
0825:                }
0826:            }
0827:
0828:            /**
0829:             * Guesses the schema language.
0830:             */
0831:            public Language guessSchemaLanguage() {
0832:                // otherwise, use the file extension.
0833:                // not a good solution, but very easy.
0834:                String name = grammars.get(0).getSystemId().toLowerCase();
0835:
0836:                if (name.endsWith(".rng"))
0837:                    return Language.RELAXNG;
0838:                if (name.endsWith(".rnc"))
0839:                    return Language.RELAXNG_COMPACT;
0840:                if (name.endsWith(".dtd"))
0841:                    return Language.DTD;
0842:                if (name.endsWith(".wsdl"))
0843:                    return Language.WSDL;
0844:
0845:                // by default, assume XML Schema
0846:                return Language.XMLSCHEMA;
0847:            }
0848:
0849:            /**
0850:             * Creates a configured CodeWriter that produces files into the specified directory.
0851:             */
0852:            public CodeWriter createCodeWriter() throws IOException {
0853:                return createCodeWriter(new FileCodeWriter(targetDir, readOnly));
0854:            }
0855:
0856:            /**
0857:             * Creates a configured CodeWriter that produces files into the specified directory.
0858:             */
0859:            public CodeWriter createCodeWriter(CodeWriter core) {
0860:                if (noFileHeader)
0861:                    return core;
0862:
0863:                return new PrologCodeWriter(core, getPrologComment());
0864:            }
0865:
0866:            /**
0867:             * Gets the string suitable to be used as the prolog comment baked into artifacts.
0868:             * This is the string like "This file was generated by the JAXB RI on YYYY/mm/dd..."
0869:             */
0870:            public String getPrologComment() {
0871:                // generate format syntax: <date> 'at' <time>
0872:                String format = Messages.format(Messages.DATE_FORMAT) + " '"
0873:                        + Messages.format(Messages.AT) + "' "
0874:                        + Messages.format(Messages.TIME_FORMAT);
0875:                SimpleDateFormat dateFormat = new SimpleDateFormat(format);
0876:
0877:                return Messages.format(Messages.FILE_PROLOG_COMMENT, dateFormat
0878:                        .format(new Date()));
0879:            }
0880:
0881:            /**
0882:             * If a plugin failed to load, report.
0883:             */
0884:            private static String pluginLoadFailure;
0885:
0886:            /**
0887:             * Looks for all "META-INF/services/[className]" files and
0888:             * create one instance for each class name found inside this file.
0889:             */
0890:            private static <T> T[] findServices(Class<T> clazz,
0891:                    ClassLoader classLoader) {
0892:                // if true, print debug output
0893:                final boolean debug = com.sun.tools.xjc.util.Util
0894:                        .getSystemProperty(Options.class, "findServices") != null;
0895:
0896:                // if we are running on Mustang or Dolphin, use ServiceLoader
0897:                // so that we can take advantage of JSR-277 module system.
0898:                try {
0899:                    Class<?> serviceLoader = Class
0900:                            .forName("java.util.ServiceLoader");
0901:                    if (debug)
0902:                        System.out.println("Using java.util.ServiceLoader");
0903:                    Iterable<T> itr = (Iterable<T>) serviceLoader.getMethod(
0904:                            "load", Class.class, ClassLoader.class).invoke(
0905:                            null, clazz, classLoader);
0906:                    List<T> r = new ArrayList<T>();
0907:                    for (T t : itr)
0908:                        r.add(t);
0909:                    return r.toArray((T[]) Array.newInstance(clazz, r.size()));
0910:                } catch (ClassNotFoundException e) {
0911:                    // fall through
0912:                } catch (IllegalAccessException e) {
0913:                    Error x = new IllegalAccessError();
0914:                    x.initCause(e);
0915:                    throw x;
0916:                } catch (InvocationTargetException e) {
0917:                    Throwable x = e.getTargetException();
0918:                    if (x instanceof  RuntimeException)
0919:                        throw (RuntimeException) x;
0920:                    if (x instanceof  Error)
0921:                        throw (Error) x;
0922:                    throw new Error(x);
0923:                } catch (NoSuchMethodException e) {
0924:                    Error x = new NoSuchMethodError();
0925:                    x.initCause(e);
0926:                    throw x;
0927:                }
0928:
0929:                String serviceId = "META-INF/services/" + clazz.getName();
0930:
0931:                // used to avoid creating the same instance twice
0932:                Set<String> classNames = new HashSet<String>();
0933:
0934:                if (debug) {
0935:                    System.out.println("Looking for " + serviceId
0936:                            + " for add-ons");
0937:                }
0938:
0939:                // try to find services in CLASSPATH
0940:                try {
0941:                    Enumeration<URL> e = classLoader.getResources(serviceId);
0942:                    if (e == null)
0943:                        return (T[]) Array.newInstance(clazz, 0);
0944:
0945:                    ArrayList<T> a = new ArrayList<T>();
0946:                    while (e.hasMoreElements()) {
0947:                        URL url = e.nextElement();
0948:                        BufferedReader reader = null;
0949:
0950:                        if (debug) {
0951:                            System.out.println("Checking " + url
0952:                                    + " for an add-on");
0953:                        }
0954:
0955:                        try {
0956:                            reader = new BufferedReader(new InputStreamReader(
0957:                                    url.openStream()));
0958:                            String impl;
0959:                            while ((impl = reader.readLine()) != null) {
0960:                                // try to instanciate the object
0961:                                impl = impl.trim();
0962:                                if (classNames.add(impl)) {
0963:                                    Class implClass = classLoader
0964:                                            .loadClass(impl);
0965:                                    if (!clazz.isAssignableFrom(implClass)) {
0966:                                        pluginLoadFailure = impl
0967:                                                + " is not a subclass of "
0968:                                                + clazz + ". Skipping";
0969:                                        if (debug)
0970:                                            System.out
0971:                                                    .println(pluginLoadFailure);
0972:                                        continue;
0973:                                    }
0974:                                    if (debug) {
0975:                                        System.out
0976:                                                .println("Attempting to instanciate "
0977:                                                        + impl);
0978:                                    }
0979:                                    a.add(clazz.cast(implClass.newInstance()));
0980:                                }
0981:                            }
0982:                            reader.close();
0983:                        } catch (Exception ex) {
0984:                            // let it go.
0985:                            StringWriter w = new StringWriter();
0986:                            ex.printStackTrace(new PrintWriter(w));
0987:                            pluginLoadFailure = w.toString();
0988:                            if (debug) {
0989:                                System.out.println(pluginLoadFailure);
0990:                            }
0991:                            if (reader != null) {
0992:                                try {
0993:                                    reader.close();
0994:                                } catch (IOException ex2) {
0995:                                    // ignore
0996:                                }
0997:                            }
0998:                        }
0999:                    }
1000:
1001:                    return a.toArray((T[]) Array.newInstance(clazz, a.size()));
1002:                } catch (Throwable e) {
1003:                    // ignore any error
1004:                    StringWriter w = new StringWriter();
1005:                    e.printStackTrace(new PrintWriter(w));
1006:                    pluginLoadFailure = w.toString();
1007:                    if (debug) {
1008:                        System.out.println(pluginLoadFailure);
1009:                    }
1010:                    return (T[]) Array.newInstance(clazz, 0);
1011:                }
1012:            }
1013:
1014:            // this is a convenient place to expose the build version to xjc plugins
1015:            public static String getBuildID() {
1016:                return Messages.format(Messages.BUILD_ID);
1017:            }
1018:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.