src/share/jaxws_classes/com/sun/tools/internal/xjc/api/impl/s2j/SchemaCompilerImpl.java

Tue, 06 Mar 2012 16:09:35 -0800

author
ohair
date
Tue, 06 Mar 2012 16:09:35 -0800
changeset 286
f50545b5e2f1
child 368
0989ad8c0860
permissions
-rw-r--r--

7150322: Stop using drop source bundles in jaxws
Reviewed-by: darcy, ohrstrom

     1 /*
     2  * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.internal.xjc.api.impl.s2j;
    28 import java.io.IOException;
    29 import java.net.MalformedURLException;
    30 import java.net.URI;
    31 import java.net.URISyntaxException;
    32 import java.net.URL;
    34 import javax.xml.XMLConstants;
    35 import javax.xml.stream.XMLStreamException;
    36 import javax.xml.stream.XMLStreamReader;
    37 import javax.xml.validation.SchemaFactory;
    39 import com.sun.codemodel.internal.JCodeModel;
    40 import com.sun.istack.internal.NotNull;
    41 import com.sun.istack.internal.SAXParseException2;
    42 import com.sun.tools.internal.xjc.ErrorReceiver;
    43 import com.sun.tools.internal.xjc.ModelLoader;
    44 import com.sun.tools.internal.xjc.Options;
    45 import com.sun.tools.internal.xjc.api.ClassNameAllocator;
    46 import com.sun.tools.internal.xjc.api.ErrorListener;
    47 import com.sun.tools.internal.xjc.api.SchemaCompiler;
    48 import com.sun.tools.internal.xjc.api.SpecVersion;
    49 import com.sun.tools.internal.xjc.model.Model;
    50 import com.sun.tools.internal.xjc.outline.Outline;
    51 import com.sun.tools.internal.xjc.reader.internalizer.DOMForest;
    52 import com.sun.tools.internal.xjc.reader.internalizer.SCDBasedBindingSet;
    53 import com.sun.tools.internal.xjc.reader.xmlschema.parser.LSInputSAXWrapper;
    54 import com.sun.tools.internal.xjc.reader.xmlschema.parser.XMLSchemaInternalizationLogic;
    55 import com.sun.xml.internal.bind.unmarshaller.DOMScanner;
    56 import com.sun.xml.internal.xsom.XSSchemaSet;
    58 import org.w3c.dom.Element;
    59 import org.w3c.dom.ls.LSInput;
    60 import org.w3c.dom.ls.LSResourceResolver;
    61 import org.xml.sax.ContentHandler;
    62 import org.xml.sax.EntityResolver;
    63 import org.xml.sax.InputSource;
    64 import org.xml.sax.SAXException;
    65 import org.xml.sax.SAXParseException;
    66 import org.xml.sax.helpers.LocatorImpl;
    68 /**
    69  * {@link SchemaCompiler} implementation.
    70  *
    71  * This class builds a {@link DOMForest} until the {@link #bind()} method,
    72  * then this method does the rest of the hard work.
    73  *
    74  * @see ModelLoader
    75  *
    76  * @author
    77  *     Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
    78  */
    79 public final class SchemaCompilerImpl extends ErrorReceiver implements SchemaCompiler {
    81     /**
    82      * User-specified error receiver.
    83      * This field can be null, in which case errors need to be discarded.
    84      */
    85     private ErrorListener errorListener;
    87     protected final Options opts = new Options();
    89     protected @NotNull DOMForest forest;
    91     /**
    92      * Set to true once an error is found.
    93      */
    94     private boolean hadError;
    96     public SchemaCompilerImpl() {
    97         opts.compatibilityMode = Options.EXTENSION;
    98         resetSchema();
   100         if(System.getProperty("xjc-api.test")!=null) {
   101             opts.debugMode = true;
   102             opts.verbose = true;
   103         }
   104     }
   106     @NotNull
   107     public Options getOptions() {
   108         return opts;
   109     }
   111     public ContentHandler getParserHandler( String systemId ) {
   112         return forest.getParserHandler(systemId,true);
   113     }
   115     public void parseSchema( String systemId, Element element ) {
   116         checkAbsoluteness(systemId);
   117         try {
   118             DOMScanner scanner = new DOMScanner();
   120             // use a locator that sets the system ID correctly
   121             // so that we can resolve relative URLs in most of the case.
   122             // it still doesn't handle xml:base and XInclude and all those things
   123             // correctly. There's just no way to make all those things work with DOM!
   124             LocatorImpl loc = new LocatorImpl();
   125             loc.setSystemId(systemId);
   126             scanner.setLocator(loc);
   128             scanner.setContentHandler(getParserHandler(systemId));
   129             scanner.scan(element);
   130         } catch (SAXException e) {
   131             // since parsing DOM shouldn't cause a SAX exception
   132             // and our handler will never throw it, it's not clear
   133             // if this will ever happen.
   134             fatalError(new SAXParseException2(
   135                 e.getMessage(), null, systemId,-1,-1, e));
   136         }
   137     }
   139     public void parseSchema(InputSource source) {
   140         checkAbsoluteness(source.getSystemId());
   141         try {
   142             forest.parse(source,true);
   143         } catch (SAXException e) {
   144             // parsers are required to report an error to ErrorHandler,
   145             // so we should never see this error.
   146             e.printStackTrace();
   147         }
   148     }
   150     public void setTargetVersion(SpecVersion version) {
   151         if(version==null)
   152             version = SpecVersion.LATEST;
   153         opts.target = version;
   154     }
   156     public void parseSchema(String systemId, XMLStreamReader reader) throws XMLStreamException {
   157         checkAbsoluteness(systemId);
   158         forest.parse(systemId,reader,true);
   159     }
   161     /**
   162      * Checks if the system ID is absolute.
   163      */
   164     @SuppressWarnings("ResultOfObjectAllocationIgnored")
   165     private void checkAbsoluteness(String systemId) {
   166         // we need to be able to handle system IDs like "urn:foo", which java.net.URL can't process,
   167         // but OTOH we also need to be able to process system IDs like "file://a b c/def.xsd",
   168         // which java.net.URI can't process. So for now, let's fail only if both of them fail.
   169         // eventually we need a proper URI class that works for us.
   170         try {
   171             new URL(systemId);
   172         } catch( MalformedURLException _ ) {
   173             try {
   174                 new URI(systemId);
   175             } catch (URISyntaxException e ) {
   176                 throw new IllegalArgumentException("system ID '"+systemId+"' isn't absolute",e);
   177             }
   178         }
   179     }
   181     public void setEntityResolver(EntityResolver entityResolver) {
   182         forest.setEntityResolver(entityResolver);
   183         opts.entityResolver = entityResolver;
   184     }
   186     public void setDefaultPackageName(String packageName) {
   187         opts.defaultPackage2 = packageName;
   188     }
   190     public void forcePackageName(String packageName) {
   191         opts.defaultPackage = packageName;
   192     }
   194     public void setClassNameAllocator(ClassNameAllocator allocator) {
   195         opts.classNameAllocator = allocator;
   196     }
   198     public void resetSchema() {
   199         forest = new DOMForest(new XMLSchemaInternalizationLogic());
   200         forest.setErrorHandler(this);
   201         forest.setEntityResolver(opts.entityResolver);
   202     }
   204     public JAXBModelImpl bind() {
   205         // this has been problematic. turn it off.
   206 //        if(!forest.checkSchemaCorrectness(this))
   207 //            return null;
   209         // parse all the binding files given via XJC -b options.
   210         // this also takes care of the binding files given in the -episode option.
   211         for (InputSource is : opts.getBindFiles())
   212             parseSchema(is);
   214         // internalization
   215         SCDBasedBindingSet scdBasedBindingSet = forest.transform(opts.isExtensionMode());
   217         if (!NO_CORRECTNESS_CHECK) {
   218             // correctness check
   219             SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
   221             // fix for https://jaxb.dev.java.net/issues/show_bug.cgi?id=795
   222             // taken from SchemaConstraintChecker, TODO XXX FIXME UGLY
   223             if (opts.entityResolver != null) {
   224                 sf.setResourceResolver(new LSResourceResolver() {
   225                     public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
   226                         try {
   227                             // XSOM passes the namespace URI to the publicID parameter.
   228                             // we do the same here .
   229                             InputSource is = opts.entityResolver.resolveEntity(namespaceURI, systemId);
   230                             if (is == null) return null;
   231                             return new LSInputSAXWrapper(is);
   232                         } catch (SAXException e) {
   233                             // TODO: is this sufficient?
   234                             return null;
   235                         } catch (IOException e) {
   236                             // TODO: is this sufficient?
   237                             return null;
   238                         }
   239                     }
   240                 });
   241             }
   243             sf.setErrorHandler(new DowngradingErrorHandler(this));
   244             forest.weakSchemaCorrectnessCheck(sf);
   245             if (hadError)
   246                 return null;    // error in the correctness check. abort now
   247         }
   249         JCodeModel codeModel = new JCodeModel();
   251         ModelLoader gl = new ModelLoader(opts,codeModel,this);
   252         try {
   253             XSSchemaSet result = gl.createXSOM(forest, scdBasedBindingSet);
   254             if(result==null)
   255                 return null;
   257             // we need info about each field, so we go ahead and generate the
   258             // skeleton at this point.
   259             // REVISIT: we should separate FieldRenderer and FieldAccessor
   260             // so that accessors can be used before we build the code.
   261             Model model = gl.annotateXMLSchema(result);
   262             if(model==null)   return null;
   264             if(hadError)        return null;    // if we have any error by now, abort
   266             model.setPackageLevelAnnotations(opts.packageLevelAnnotations);
   268             Outline context = model.generateCode(opts,this);
   269             if(context==null)   return null;
   271             if(hadError)        return null;
   273             return new JAXBModelImpl(context);
   274         } catch( SAXException e ) {
   275             // since XSOM uses our parser that scans DOM,
   276             // no parser error is possible.
   277             // all the other errors will be directed to ErrorReceiver
   278             // before it's thrown, so when the exception is thrown
   279             // the error should have already been reported.
   281             // thus ignore.
   282             return null;
   283         }
   284     }
   286     public void setErrorListener(ErrorListener errorListener) {
   287         this.errorListener = errorListener;
   288     }
   290     public void info(SAXParseException exception) {
   291         if(errorListener!=null)
   292             errorListener.info(exception);
   293     }
   294     public void warning(SAXParseException exception) {
   295         if(errorListener!=null)
   296             errorListener.warning(exception);
   297     }
   298     public void error(SAXParseException exception) {
   299         hadError = true;
   300         if(errorListener!=null)
   301             errorListener.error(exception);
   302     }
   303     public void fatalError(SAXParseException exception) {
   304         hadError = true;
   305         if(errorListener!=null)
   306             errorListener.fatalError(exception);
   307     }
   309     /**
   310      * We use JAXP 1.3 to do a schema correctness check, but we know
   311      * it doesn't always work. So in case some people hit the problem,
   312      * this switch is here so that they can turn it off as a workaround.
   313      */
   314     private static boolean NO_CORRECTNESS_CHECK = false;
   316     static {
   317         try {
   318             NO_CORRECTNESS_CHECK = Boolean.getBoolean(SchemaCompilerImpl.class.getName()+".noCorrectnessCheck");
   319         } catch( Throwable t) {
   320             // ignore
   321         }
   322     }
   323 }

mercurial