Home » xmlbeans-2.5.0-src » org.apache » xmlbeans » [javadoc | source]

    1   /*   Copyright 2004 The Apache Software Foundation
    2    *
    3    *   Licensed under the Apache License, Version 2.0 (the "License");
    4    *   you may not use this file except in compliance with the License.
    5    *   You may obtain a copy of the License at
    6    *
    7    *       http://www.apache.org/licenses/LICENSE-2.0
    8    *
    9    *   Unless required by applicable law or agreed to in writing, software
   10    *   distributed under the License is distributed on an "AS IS" BASIS,
   11    *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   12    *   See the License for the specific language governing permissions and
   13    *  limitations under the License.
   14    */
   15   
   16   package org.apache.xmlbeans;
   17   
   18   import javax.xml.namespace.QName;
   19   import java.lang.reflect.Field;
   20   import java.lang.reflect.InvocationTargetException;
   21   import java.lang.reflect.Method;
   22   import java.lang.reflect.Constructor;
   23   import java.lang.ref.SoftReference;
   24   import java.io.File;
   25   
   26   import javax.xml.stream.XMLStreamReader;
   27   
   28   import org.w3c.dom.Node;
   29   
   30   /**
   31    * Provides an assortment of utilities
   32    * for managing XML Bean types, type systems, QNames, paths,
   33    * and queries.
   34    */
   35   public final class XmlBeans
   36   {
   37       private static String XMLBEANS_TITLE = "org.apache.xmlbeans";
   38       private static String XMLBEANS_VERSION = "2.5.0";
   39       private static String XMLBEANS_VENDOR = "Apache Software Foundation";
   40   
   41       static
   42       {
   43           Package pkg = XmlBeans.class.getPackage();
   44           if (pkg != null)
   45           {
   46               XMLBEANS_TITLE = pkg.getImplementationTitle();
   47               XMLBEANS_VERSION = pkg.getImplementationVersion();
   48               XMLBEANS_VENDOR = pkg.getImplementationVendor();
   49           }
   50       }
   51   
   52       /**
   53        * Returns the XmlBeans Package title, "org.apache.xmlbeans",
   54        * the value of
   55        * {@link Package#getImplementationTitle() XmlBeans.class.getPackage().getImplementationTitle()}.
   56        */
   57       public static final String getTitle()
   58       {
   59           return XMLBEANS_TITLE;
   60       }
   61   
   62       /**
   63        * Returns the XmlBeans vendor, "Apache Software Foundation",
   64        * the value of
   65        * {@link Package#getImplementationVendor() XmlBeans.class.getPackage().getImplementationVendor()}.
   66        */
   67       public static final String getVendor()
   68       {
   69           return XMLBEANS_VENDOR;
   70       }
   71   
   72       /**
   73        * Returns the XmlBeans version,
   74        * the value of
   75        * {@link Package#getImplementationVersion() XmlBeans.class.getPackage().getImplementationVersion()}.
   76        */
   77       public static final String getVersion()
   78       {
   79           return XMLBEANS_VERSION;
   80       }
   81   
   82       /**
   83        * Thread local QName cache for general use
   84        */
   85       private static final ThreadLocal _threadLocalLoaderQNameCache =
   86           new ThreadLocal()
   87           {
   88               protected Object initialValue()
   89               {
   90                   return new SoftReference(new QNameCache( 32 ));
   91               }
   92           };
   93   
   94       /**
   95        * Returns a thread local QNameCache
   96        */
   97       public static QNameCache getQNameCache ( )
   98       {
   99           SoftReference softRef = (SoftReference)_threadLocalLoaderQNameCache.get();
  100           QNameCache qnameCache = (QNameCache) (softRef).get();
  101           if (qnameCache==null)
  102           {
  103               qnameCache = new QNameCache( 32 );
  104               _threadLocalLoaderQNameCache.set(new SoftReference(qnameCache));
  105           }
  106           return qnameCache;
  107       }
  108   
  109       /**
  110        * Obtains a name from the thread local QNameCache
  111        */
  112       public static QName getQName ( String localPart )
  113       {
  114           return getQNameCache().getName( "",  localPart );
  115       }
  116   
  117       /**
  118        * Obtains a name from the thread local QNameCache
  119        */
  120   
  121       public static QName getQName ( String namespaceUri, String localPart )
  122       {
  123           return getQNameCache().getName( namespaceUri,  localPart );
  124       }
  125   
  126       private static final Method _getContextTypeLoaderMethod = buildGetContextTypeLoaderMethod();
  127       private static final Method _getBuiltinSchemaTypeSystemMethod = buildGetBuiltinSchemaTypeSystemMethod();
  128       private static final Method _getNoTypeMethod = buildGetNoTypeMethod();
  129       private static final Method _typeLoaderBuilderMethod = buildTypeLoaderBuilderMethod();
  130       private static final Method _compilationMethod = buildCompilationMethod();
  131       private static final Method _nodeToCursorMethod = buildNodeToCursorMethod();
  132       private static final Method _nodeToXmlObjectMethod = buildNodeToXmlObjectMethod();
  133       private static final Method _nodeToXmlStreamMethod = buildNodeToXmlStreamMethod();
  134       private static final Method _streamToNodeMethod = buildStreamToNodeMethod();
  135       private static final Constructor _pathResourceLoaderConstructor = buildPathResourceLoaderConstructor();
  136   
  137       private static RuntimeException causedException ( RuntimeException e, Throwable cause )
  138       {
  139           e.initCause( cause );
  140   
  141           return e;
  142       }
  143   
  144       private static XmlException wrappedException(Throwable e)
  145       {
  146           if (e instanceof XmlException)
  147               return (XmlException) e;
  148   
  149           return new XmlException( e.getMessage(), e );
  150       }
  151   
  152       private static final Constructor buildConstructor ( String className, Class[] args )
  153       {
  154           try
  155           {
  156               return
  157                   Class.forName(
  158                       className, false, XmlBeans.class.getClassLoader() ).
  159                   getConstructor( args );
  160           }
  161           catch ( Exception e )
  162           {
  163               throw causedException(
  164                   new IllegalStateException(
  165                       "Cannot load constructor for " + className +
  166                   ": verify that xbean.jar is on the classpath" ), e );
  167           }
  168       }
  169   
  170       private static final Method buildMethod ( String className, String methodName, Class[] args )
  171       {
  172           try
  173           {
  174               return
  175                   Class.forName(
  176                       className, false, XmlBeans.class.getClassLoader() ).
  177                           getMethod( methodName, args );
  178           }
  179           catch ( Exception e )
  180           {
  181               throw causedException(
  182                   new IllegalStateException(
  183                       "Cannot load " + methodName +
  184                           ": verify that xbean.jar is on the classpath" ), e );
  185           }
  186       }
  187   
  188       private static final Method buildNoArgMethod ( String className, String methodName )
  189       {
  190           return buildMethod( className, methodName, new Class[ 0 ] );
  191       }
  192   
  193       private static final Method buildNodeMethod ( String className, String methodName )
  194       {
  195           return buildMethod( className, methodName, new Class[] { Node.class } );
  196       }
  197   
  198       private static Method buildGetContextTypeLoaderMethod()
  199       {
  200           return buildNoArgMethod( "org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl", "getContextTypeLoader" );
  201       }
  202   
  203   
  204       private static final Method buildGetBuiltinSchemaTypeSystemMethod()
  205       {
  206           return buildNoArgMethod( "org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem", "get" );
  207       }
  208   
  209       private static final Method buildGetNoTypeMethod()
  210       {
  211           return buildNoArgMethod( "org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem", "getNoType" );
  212       }
  213   
  214       private static final Method buildTypeLoaderBuilderMethod ( )
  215       {
  216           return
  217               buildMethod(
  218                   "org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl", "build",
  219                   new Class[] { SchemaTypeLoader[].class, ResourceLoader.class, ClassLoader.class } );
  220       }
  221   
  222       private static final Method buildCompilationMethod()
  223       {
  224           return
  225               buildMethod(
  226                   "org.apache.xmlbeans.impl.schema.SchemaTypeSystemCompiler", "compile",
  227                   new Class[] { String.class, SchemaTypeSystem.class, XmlObject[].class, BindingConfig.class, SchemaTypeLoader.class, Filer.class, XmlOptions.class } );
  228       }
  229   
  230       private static final Method buildNodeToCursorMethod()
  231       {
  232           return buildNodeMethod( "org.apache.xmlbeans.impl.store.Locale", "nodeToCursor" );
  233       }
  234   
  235       private static final Method buildNodeToXmlObjectMethod()
  236       {
  237           return buildNodeMethod( "org.apache.xmlbeans.impl.store.Locale", "nodeToXmlObject" );
  238       }
  239   
  240       private static final Method buildNodeToXmlStreamMethod()
  241       {
  242           return buildNodeMethod( "org.apache.xmlbeans.impl.store.Locale", "nodeToXmlStream" );
  243       }
  244   
  245       private static final Method buildStreamToNodeMethod()
  246       {
  247           return
  248               buildMethod(
  249                   "org.apache.xmlbeans.impl.store.Locale", "streamToNode",
  250                   new Class[] { XMLStreamReader.class } );
  251       }
  252   
  253       private static final Constructor buildPathResourceLoaderConstructor()
  254       {
  255           return
  256               buildConstructor(
  257                   "org.apache.xmlbeans.impl.schema.PathResourceLoader",
  258                   new Class[] { File[].class } );
  259       }
  260   
  261       /**
  262        * Compiles an XPath, returning a String equal to that which was passed,
  263        * but whose identity is that of one which has been precompiled and cached.
  264        */
  265       public static String compilePath ( String pathExpr ) throws XmlException
  266       {
  267           return compilePath( pathExpr, null );
  268       }
  269   
  270       /**
  271        * Compiles an XPath, returning a String equal to that which was passed,
  272        * but whose identity is that of one which has been precompiled and cached;
  273        * takes an option for specifying text that indicates the name of context node.
  274        * The default is "this", as in "$this".
  275        *
  276        * @param  options  Options for the path. For example, you can call
  277        * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
  278        * method to specify a particular name for the expression
  279        * variable that indicates the context node.
  280        */
  281       public static String compilePath ( String pathExpr, XmlOptions options )
  282           throws XmlException
  283       {
  284           return getContextTypeLoader().compilePath( pathExpr, options );
  285       }
  286   
  287       /**
  288        * Compiles an XQuery, returning a String equal to that which was passed,
  289        * but whose identity is that of one which has been precompiled and cached.
  290        */
  291       public static String compileQuery ( String queryExpr ) throws XmlException
  292       {
  293           return compileQuery( queryExpr, null );
  294       }
  295   
  296       /**
  297        * Compiles an XQuery, returning a String equal to that which was passed,
  298        * but whose identity is that of one which has been precompiled and cached;
  299        * takes an option for specifying text that indicates the context node.
  300        *
  301        * @param  options  Options for the query. For example, you can call
  302        * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
  303        * method to specify a particular name for the expression
  304        * variable that indicates the context node and the
  305        * {@link XmlOptions#setXqueryVariables(java.util.Map) XmlOptions.setXqueryVariables(Map)}
  306        * method to map external variable names to values.
  307        */
  308       public static String compileQuery ( String queryExpr, XmlOptions options )
  309           throws XmlException
  310       {
  311           return getContextTypeLoader().compileQuery( queryExpr, options );
  312       }
  313   
  314       /**
  315        * Gets the SchemaTypeLoader based on the current thread's context
  316        * ClassLoader. This is the SchemaTypeLoader that is used to assign
  317        * schema types to XML documents by default. The SchemaTypeLoader is
  318        * also consulted to resolve wildcards and xsi:type attributes.
  319        * <p>
  320        * The "parse" methods of XmlBeans all delegate to the
  321        * "parseInstance" methods of the context type loader.
  322        */
  323       public static SchemaTypeLoader getContextTypeLoader()
  324       {
  325           try
  326           {
  327               return (SchemaTypeLoader)_getContextTypeLoaderMethod.invoke(null, null);
  328           }
  329           catch (IllegalAccessException e)
  330           {
  331               throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl.getContextTypeLoader(): verify that version of xbean.jar is correct"), e);
  332           }
  333           catch (InvocationTargetException e)
  334           {
  335               Throwable t = e.getCause();
  336               IllegalStateException ise = new IllegalStateException(t.getMessage());
  337               ise.initCause(t); // use initCause() to support Java 1.4
  338               throw ise;
  339           }
  340       }
  341   
  342       /**
  343        * Returns the builtin type system. This SchemaTypeSystem contains
  344        * only the 46 builtin types defined by the XML Schema specification.
  345        */
  346       public static SchemaTypeSystem getBuiltinTypeSystem()
  347       {
  348           try
  349           {
  350               return (SchemaTypeSystem)_getBuiltinSchemaTypeSystemMethod.invoke(null, null);
  351           }
  352           catch (IllegalAccessException e)
  353           {
  354               throw causedException(new IllegalStateException("No access to BuiltinSchemaTypeSystem.get(): verify that version of xbean.jar is correct"), e);
  355           }
  356           catch (InvocationTargetException e)
  357           {
  358               Throwable t = e.getCause();
  359               IllegalStateException ise = new IllegalStateException(t.getMessage());
  360               ise.initCause(t); // use initCause() to support Java 1.4
  361               throw ise;
  362           }
  363       }
  364   
  365       /**
  366        * Creates an XmlCursor for a DOM node which is implemented by XmlBwans
  367        */
  368       public static XmlCursor nodeToCursor ( Node n )
  369       {
  370           try
  371           {
  372               return (XmlCursor) _nodeToCursorMethod.invoke( null, new Object[] { n } );
  373           }
  374           catch ( IllegalAccessException e )
  375           {
  376               throw causedException(
  377                   new IllegalStateException(
  378                       "No access to nodeToCursor verify that version of xbean.jar is correct" ), e );
  379           }
  380           catch ( InvocationTargetException e )
  381           {
  382               Throwable t = e.getCause();
  383               IllegalStateException ise = new IllegalStateException(t.getMessage());
  384               ise.initCause(t); // use initCause() to support Java 1.4
  385               throw ise;
  386           }
  387       }
  388   
  389       /**
  390        * Creates an XmlObject for a DOM node which is implemented by XmlBwans
  391        */
  392       public static XmlObject nodeToXmlObject ( Node n )
  393       {
  394           try
  395           {
  396               return (XmlObject) _nodeToXmlObjectMethod.invoke( null, new Object[] { n } );
  397           }
  398           catch ( IllegalAccessException e )
  399           {
  400               throw causedException(
  401                   new IllegalStateException(
  402                       "No access to nodeToXmlObject verify that version of xbean.jar is correct" ), e );
  403           }
  404           catch ( InvocationTargetException e )
  405           {
  406               Throwable t = e.getCause();
  407               IllegalStateException ise = new IllegalStateException(t.getMessage());
  408               ise.initCause(t); // use initCause() to support Java 1.4
  409               throw ise;
  410           }
  411       }
  412   
  413       /**
  414        * Creates an XmlObject for a DOM node which is implemented by XmlBwans
  415        */
  416       public static XMLStreamReader nodeToXmlStreamReader ( Node n )
  417       {
  418           try
  419           {
  420               return (XMLStreamReader) _nodeToXmlStreamMethod.invoke( null, new Object[] { n } );
  421           }
  422           catch ( IllegalAccessException e )
  423           {
  424               throw causedException(
  425                   new IllegalStateException(
  426                       "No access to nodeToXmlStreamReader verify that version of xbean.jar is correct" ), e );
  427           }
  428           catch ( InvocationTargetException e )
  429           {
  430               Throwable t = e.getCause();
  431               IllegalStateException ise = new IllegalStateException(t.getMessage());
  432               ise.initCause(t); // use initCause() to support Java 1.4
  433               throw ise;
  434           }
  435       }
  436   
  437       /**
  438        * Returns the XmlObject for a DOM node which is implemented by XmlBwans
  439        */
  440       public static Node streamToNode ( XMLStreamReader xs )
  441       {
  442           try
  443           {
  444               return (Node) _streamToNodeMethod.invoke( null, new Object[] { xs } );
  445           }
  446           catch ( IllegalAccessException e )
  447           {
  448               throw causedException(
  449                   new IllegalStateException(
  450                       "No access to streamToNode verify that version of xbean.jar is correct" ), e );
  451           }
  452           catch ( InvocationTargetException e )
  453           {
  454               Throwable t = e.getCause();
  455               IllegalStateException ise = new IllegalStateException(t.getMessage());
  456               ise.initCause(t); // use initCause() to support Java 1.4
  457               throw ise;
  458           }
  459       }
  460   
  461       /**
  462        * Returns the SchemaTypeSystem that results from compiling the XML
  463        * schema definitions passed.
  464        * <p>
  465        * Just like compileXsd, but uses the context type loader for
  466        * linking, and returns a unioned typeloader that is suitable for
  467        * creating instances.
  468        */
  469       public static SchemaTypeLoader loadXsd(XmlObject[] schemas) throws XmlException
  470       {
  471           return loadXsd(schemas, null);
  472       }
  473   
  474       /**
  475        * <p>Returns the SchemaTypeSystem that results from compiling the XML
  476        * schema definitions passed in <em>schemas</em>.</p>
  477        *
  478        * <p>This is just like compileXsd, but uses the context type loader for
  479        * linking, and returns a unioned typeloader that is suitable for
  480        * creating instances.</p>
  481        *
  482        * <p>Use the <em>options</em> parameter to specify one or both of the following:</p>
  483        *
  484        * <ul>
  485        * <li>A collection instance that should be used as an error listener during
  486        * compilation, as described in {@link XmlOptions#setErrorListener}.</li>
  487        * <li>Whether validation should not be done when building the SchemaTypeSystem,
  488        * as described in {@link XmlOptions#setCompileNoValidation}.</li>
  489        * </ul>
  490        *
  491        * @param schemas The schema definitions from which to build the schema type system.
  492        * @param options Options specifying an error listener and/or validation behavior.
  493        */
  494       public static SchemaTypeLoader loadXsd(XmlObject[] schemas, XmlOptions options) throws XmlException
  495       {
  496           try
  497           {
  498               SchemaTypeSystem sts =
  499                   (SchemaTypeSystem)
  500                       _compilationMethod.invoke(
  501                           null, new Object[] { null, null, schemas, null, getContextTypeLoader(), null, options });
  502   
  503               if (sts == null)
  504                   return null;
  505   
  506               return
  507                   typeLoaderUnion(
  508                       new SchemaTypeLoader[] { sts, getContextTypeLoader() } );
  509           }
  510           catch (IllegalAccessException e)
  511           {
  512               throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl.forSchemaXml(): verify that version of xbean.jar is correct"), e);
  513           }
  514           catch (InvocationTargetException e)
  515           {
  516               throw wrappedException(e.getCause());
  517           }
  518       }
  519   
  520       /**
  521        * <p>Returns the SchemaTypeSystem that results from compiling the XML
  522        * schema definitions passed.</p>
  523        *
  524        * <p>The XmlObjects passed in should be w3c &lt;schema&gt; elements whose type
  525        * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in
  526        * the XML namespace http://www.w3c.org/2001/XMLSchema.)  Also
  527        * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.</p>
  528        *
  529        * <p>The optional second argument is a SchemaTypeLoader which will be
  530        * consulted for already-compiled schema types which may be linked
  531        * while processing the given schemas.</p>
  532        *
  533        * <p>The SchemaTypeSystem that is returned should be combined
  534        * (via {@link #typeLoaderUnion}) with the typepath typeloader in order
  535        * to create a typeloader that can be used for creating and validating
  536        * instances.</p>
  537        *
  538        * <p>Use the <em>options</em> parameter to specify the following:</p>
  539        *
  540        * <ul>
  541        * <li>A collection instance that should be used as an error listener during
  542        * compilation, as described in {@link XmlOptions#setErrorListener}.</li>
  543        * <li>Whether validation should not be done when building the SchemaTypeSystem,
  544        * as described in {@link XmlOptions#setCompileNoValidation}.</li>
  545        * </ul>
  546        *
  547        * @param schemas The schema definitions from which to build the schema type system.
  548        * @param typepath The path to already-compiled schema types for linking while processing.
  549        * @param options Options specifying an error listener and/or validation behavior.
  550        */
  551       public static SchemaTypeSystem compileXsd(XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException
  552       {
  553           return compileXmlBeans(null, null, schemas, null, typepath, null, options);
  554       }
  555   
  556       /**
  557        * <p>Returns the SchemaTypeSystem that results from augumenting the
  558        * SchemaTypeSystem passed in by incrementally adding the given XML
  559        * schema definitions.</p>
  560        *
  561        * <p>These could be new definitions (if the Schema document is not recorded into
  562        * the existing SchemaTypeSystem), modifications to the already existing
  563        * definitions (if the Schema document is already recorded in the existing
  564        * SchemaTypeSystem), or deletions (if the Schema document is already recorded
  565        * in the existing SchemaTypeSystem and the new definitions are empty).
  566        * The identity of documents is established using
  567        * {@link XmlDocumentProperties#getSourceName}, so if the caller choses to
  568        * construct the Schema definitions using other methods than parsing an
  569        * XML document, they should make sure that the names returned by that
  570        * method are consistent with the caller's intent (add/modify).</p>
  571        *
  572        * <p>The XmlObjects passed in should be w3c &lt;schema&gt; elements whose type
  573        * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in
  574        * the XML namespace http://www.w3c.org/2001/XMLSchema.)  Also
  575        * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.</p>
  576        *
  577        * <p>The optional second argument is a SchemaTypeLoader which will be
  578        * consulted for already-compiled schema types which may be linked
  579        * while processing the given schemas.</p>
  580        *
  581        * <p>The SchemaTypeSystem that is returned should be combined
  582        * (via {@link #typeLoaderUnion}) with the typepath typeloader in order
  583        * to create a typeloader that can be used for creating and validating
  584        * instances.</p>
  585        *
  586        * <p>Use the <em>options</em> parameter to specify the following:</p>
  587        *
  588        * <ul>
  589        * <li>A collection instance that should be used as an error listener during
  590        * compilation, as described in {@link XmlOptions#setErrorListener}.</li>
  591        * <li>Whether validation should not be done when building the SchemaTypeSystem,
  592        * as described in {@link XmlOptions#setCompileNoValidation}.</li>
  593        * </ul>
  594        *
  595        * @param schemas The schema definitions from which to build the schema type system.
  596        * @param typepath The path to already-compiled schema types for linking while processing.
  597        * @param options Options specifying an error listener and/or validation behavior.
  598        */
  599       public static SchemaTypeSystem compileXsd(SchemaTypeSystem system, XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException
  600       {
  601           return compileXmlBeans(null, system, schemas, null, typepath, null, options);
  602       }
  603   
  604       /**
  605        * <p>Returns the SchemaTypeSystem that results from augumenting the
  606        * SchemaTypeSystem passed in by incrementally adding the given XML
  607        * schema definitions.</p>
  608        *
  609        * <p>These could be new definitions (if the Schema document is not recorded into
  610        * the existing SchemaTypeSystem), modifications to the already existing
  611        * definitions (if the Schema document is already recorded in the existing
  612        * SchemaTypeSystem), or deletions (if the Schema document is already recorded
  613        * in the existing SchemaTypeSystem and the new definitions are empty).
  614        * The identity of documents is established using
  615        * {@link XmlDocumentProperties#getSourceName}, so if the caller choses to
  616        * construct the Schema definitions using other methods than parsing an
  617        * XML document, they should make sure that the names returned by that
  618        * method are consistent with the caller's intent (add/modify).</p>
  619        *
  620        * <p>The XmlObjects passed in should be w3c &lt;schema&gt; elements whose type
  621        * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in
  622        * the XML namespace http://www.w3c.org/2001/XMLSchema.)  Also
  623        * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.</p>
  624        *
  625        * <p>The optional name argument is used to name the compiled schema type system.
  626        * A randomly generated name will be used if the name is null.</p>
  627        *
  628        * <p>The optional {@link BindingConfig} argument is used to control the shape
  629        * of the generated code. A <code>BindingConfig</code> isn't used if <code>Filer</code>
  630        * is null.</p>
  631        *
  632        * <p>The optional SchemaTypeLoader argument will be
  633        * consulted for already-compiled schema types which may be linked
  634        * while processing the given schemas. If not specified, the context
  635        * typeloader (as returned by {@link #getContextTypeLoader}) will be used.</p>
  636        *
  637        * <p>The optional {@link Filer} argument is used to create new binary or source
  638        * files which are the product of the compilation.  If the Filer is null, the
  639        * schema binaries (.xsb) files and source files won't be generated.</p>
  640        *
  641        * <p>The SchemaTypeSystem that is returned should be combined
  642        * (via {@link #typeLoaderUnion}) with the typepath typeloader in order
  643        * to create a typeloader that can be used for creating and validating
  644        * instances.</p>
  645        *
  646        * <p>Use the <em>options</em> parameter to specify the following:</p>
  647        *
  648        * <ul>
  649        * <li>A collection instance that should be used as an error listener during
  650        * compilation, as described in {@link XmlOptions#setErrorListener}.</li>
  651        * <li>Whether validation should not be done when building the SchemaTypeSystem,
  652        * as described in {@link XmlOptions#setCompileNoValidation}.</li>
  653        * </ul>
  654        *
  655        * @param name The type system name or null to use a randomly generated name.
  656        * @param system A pre-existing SchemaTypeSystem used in incremental compilation.
  657        * @param schemas The schema definitions from which to build the schema type system.
  658        * @param config The configuration controls the code generation shape.
  659        * @param typepath The path to already-compiled schema types for linking while processing.
  660        * @param filer The Filer instance used to create binary binding files and source text files.
  661        * @param options Options specifying an error listener and/or validation behavior.
  662        */
  663       public static SchemaTypeSystem compileXmlBeans(String name, SchemaTypeSystem system, XmlObject[] schemas, BindingConfig config, SchemaTypeLoader typepath, Filer filer, XmlOptions options) throws XmlException
  664       {
  665           try
  666           {
  667               return (SchemaTypeSystem)_compilationMethod.invoke(null, new Object[] { name, system, schemas, config, typepath != null ? typepath : getContextTypeLoader(), filer, options });
  668           }
  669           catch (IllegalAccessException e)
  670           {
  671               throw new IllegalStateException("No access to SchemaTypeLoaderImpl.forSchemaXml(): verify that version of xbean.jar is correct");
  672           }
  673           catch (InvocationTargetException e)
  674           {
  675               throw wrappedException(e.getCause());
  676           }
  677       }
  678   
  679   
  680       /**
  681        * Returns the union of a list of typeLoaders. The returned
  682        * SchemaTypeLoader searches the given list of SchemaTypeLoaders
  683        * in order from first to last.
  684        */
  685       public static SchemaTypeLoader typeLoaderUnion(SchemaTypeLoader[] typeLoaders)
  686       {
  687           try
  688           {
  689               if (typeLoaders.length == 1)
  690                   return typeLoaders[0];
  691   
  692               return (SchemaTypeLoader)_typeLoaderBuilderMethod.invoke(null, new Object[] {typeLoaders, null, null});
  693           }
  694           catch (IllegalAccessException e)
  695           {
  696               throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl: verify that version of xbean.jar is correct"), e);
  697           }
  698           catch (InvocationTargetException e)
  699           {
  700               Throwable t = e.getCause();
  701               IllegalStateException ise = new IllegalStateException(t.getMessage());
  702               ise.initCause(t); // use initCause() to support Java 1.4
  703               throw ise;
  704           }
  705       }
  706   
  707       /**
  708        * Returns a SchemaTypeLoader that searches for compiled schema types
  709        * in the given ClassLoader.
  710        */
  711       public static SchemaTypeLoader typeLoaderForClassLoader(ClassLoader loader)
  712       {
  713           try
  714           {
  715               return (SchemaTypeLoader)_typeLoaderBuilderMethod.invoke(null, new Object[] {null, null, loader});
  716           }
  717           catch (IllegalAccessException e)
  718           {
  719               throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl: verify that version of xbean.jar is correct"), e);
  720           }
  721           catch (InvocationTargetException e)
  722           {
  723               Throwable t = e.getCause();
  724               IllegalStateException ise = new IllegalStateException(t.getMessage());
  725               ise.initCause(t); // use initCause() to support Java 1.4
  726               throw ise;
  727           }
  728       }
  729   
  730       /**
  731        * Returns a SchemaTypeLoader that searches for compiled schema types
  732        * in the given ResourceLoader.
  733        *
  734        * @see XmlBeans#resourceLoaderForPath(File[])
  735        */
  736       public static SchemaTypeLoader typeLoaderForResource(ResourceLoader resourceLoader)
  737       {
  738           try
  739           {
  740               return (SchemaTypeLoader)_typeLoaderBuilderMethod.invoke(null, new Object[] {null, resourceLoader, null});
  741           }
  742           catch (IllegalAccessException e)
  743           {
  744               throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl: verify that version of xbean.jar is correct"), e);
  745           }
  746           catch (InvocationTargetException e)
  747           {
  748               Throwable t = e.getCause();
  749               IllegalStateException ise = new IllegalStateException(t.getMessage());
  750               ise.initCause(t); // use initCause() to support Java 1.4
  751               throw ise;
  752           }
  753       }
  754   
  755       private static final String HOLDER_CLASS_NAME = "TypeSystemHolder";
  756       private static final String TYPE_SYSTEM_FIELD = "typeSystem";
  757   
  758       /**
  759        * Returns the SchemaTypeSystem of the given name (as returned by
  760        * {@link SchemaTypeSystem#getName}) for the given ClassLoader.
  761        * <p>
  762        * Note: you will almost always need typeLoaderForClassLoader()
  763        * instead (see {@link XmlBeans#typeLoaderForClassLoader}).
  764        */
  765       public static SchemaTypeSystem typeSystemForClassLoader(ClassLoader loader, String stsName)
  766       {
  767           try
  768           {
  769               Class clazz = loader.loadClass(stsName + "." + HOLDER_CLASS_NAME);
  770               SchemaTypeSystem sts = (SchemaTypeSystem)
  771                   (clazz.getDeclaredField(TYPE_SYSTEM_FIELD).get(null));
  772               if (sts == null)
  773               {
  774                   throw new RuntimeException("SchemaTypeSystem is null for field " +
  775                       TYPE_SYSTEM_FIELD + " on class with name " + stsName +
  776                       "." + HOLDER_CLASS_NAME +
  777                       ". Please verify the version of xbean.jar is correct.");
  778               }
  779               return sts;
  780           }
  781           catch (ClassNotFoundException e)
  782           {
  783               throw causedException(new RuntimeException("Cannot load SchemaTypeSystem. " +
  784                   "Unable to load class with name " + stsName + "." + HOLDER_CLASS_NAME +
  785                   ". Make sure the generated binary files are on the classpath."), e);
  786           }
  787           catch (NoSuchFieldException e)
  788           {
  789               throw causedException(new RuntimeException("Cannot find field " +
  790                   TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME +
  791                   ". Please verify the version of xbean.jar is correct."), e);
  792           }
  793           catch (IllegalAccessException e)
  794           {
  795               throw causedException(new RuntimeException("Field " +
  796                   TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME +
  797                   "is not accessible. Please verify the version of xbean.jar is correct."), e);
  798           }
  799       }
  800   
  801       /**
  802        * Returns a new ResourceLoader for a search path where each component of
  803        * the path is either a directory or a compiled xbean jar.
  804        */
  805       public static ResourceLoader resourceLoaderForPath(File[] path)
  806       {
  807           try
  808           {
  809               return (ResourceLoader)_pathResourceLoaderConstructor.newInstance(new Object[] {path});
  810           }
  811           catch (IllegalAccessException e)
  812           {
  813               throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl: verify that version of xbean.jar is correct"), e);
  814           }
  815           catch (InstantiationException e)
  816           {
  817               throw causedException(new IllegalStateException(e.getMessage()), e);
  818           }
  819           catch (InvocationTargetException e)
  820           {
  821               Throwable t = e.getCause();
  822               IllegalStateException ise = new IllegalStateException(t.getMessage());
  823               ise.initCause(t); // use initCause() to support Java 1.4
  824               throw ise;
  825           }
  826       }
  827   
  828       /**
  829        * Returns the SchemaType from a corresponding XmlObject subclass,
  830        * or null if none.
  831        */
  832       public static SchemaType typeForClass(Class c)
  833       {
  834           if (c == null || !XmlObject.class.isAssignableFrom(c))
  835               return null;
  836   
  837           try
  838           {
  839               Field typeField = c.getField("type");
  840   
  841               if (typeField == null)
  842                   return null;
  843   
  844               return (SchemaType)typeField.get(null);
  845           }
  846           catch (Exception e)
  847           {
  848               return null;
  849           }
  850       }
  851   
  852       private static SchemaType getNoType()
  853       {
  854           try
  855           {
  856               return (SchemaType)_getNoTypeMethod.invoke(null, null);
  857           }
  858           catch (IllegalAccessException e)
  859           {
  860               throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl.getContextTypeLoader(): verify that version of xbean.jar is correct"), e);
  861           }
  862           catch (InvocationTargetException e)
  863           {
  864               Throwable t = e.getCause();
  865               IllegalStateException ise = new IllegalStateException(t.getMessage());
  866               ise.initCause(t); // use initCause() to support Java 1.4
  867               throw ise;
  868           }
  869       }
  870   
  871       /**
  872        * The SchemaType object given to an XmlObject instance when
  873        * no type can be determined.
  874        * <p>
  875        * The NO_TYPE is the universal derived type.  That is, it is
  876        * derived from all other schema types, and no instances of the
  877        * NO_TYPE are valid. (It is not to be confused with the anyType,
  878        * which is the universal base type from which all other types
  879        * can be derived, and of which all instances are valid.)
  880        */
  881       public static SchemaType NO_TYPE = getNoType();
  882   
  883       private XmlBeans ( ) { }
  884   }

Home » xmlbeans-2.5.0-src » org.apache » xmlbeans » [javadoc | source]