xmlschemaloader.java

来自「JAVA 所有包」· Java 代码 · 共 1,324 行 · 第 1/4 页

JAVA
1,324
字号
    /**     * Returns the state of a feature.     *     * @param featureId The feature identifier.     *     * @throws XMLConfigurationException Thrown on configuration error.     */    public boolean getFeature(String featureId)    throws XMLConfigurationException {                        return fLoaderConfig.getFeature(featureId);            } // getFeature (String):  boolean        /**     * Sets the state of a feature.     *     * @param featureId The feature identifier.     * @param state     The state of the feature.     *     * @throws XMLConfigurationException Thrown when a feature is not     *                  recognized or cannot be set.     */    public void setFeature(String featureId,            boolean state) throws XMLConfigurationException {        fSettingsChanged = true;         if(featureId.equals(CONTINUE_AFTER_FATAL_ERROR)) {            fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, state);        }         else if(featureId.equals(GENERATE_SYNTHETIC_ANNOTATIONS)) {            fSchemaHandler.setGenerateSyntheticAnnotations(state);        }        fLoaderConfig.setFeature(featureId, state);    } // setFeature(String, boolean)        /**     * Returns a list of property identifiers that are recognized by     * this XMLGrammarLoader.  This method may return null if no properties     * are recognized.     */    public String[] getRecognizedProperties() {        return (String[])(RECOGNIZED_PROPERTIES.clone());    } // getRecognizedProperties():  String[]        /**     * Returns the state of a property.     *     * @param propertyId The property identifier.     *     * @throws XMLConfigurationException Thrown on configuration error.     */    public Object getProperty(String propertyId)    throws XMLConfigurationException {        return fLoaderConfig.getProperty(propertyId);    } // getProperty(String):  Object        /**     * Sets the state of a property.     *     * @param propertyId The property identifier.     * @param state     The state of the property.     *     * @throws XMLConfigurationException Thrown when a property is not     *                  recognized or cannot be set.     */    public void setProperty(String propertyId,            Object state) throws XMLConfigurationException {                           fSettingsChanged = true;        fLoaderConfig.setProperty(propertyId, state);            if(propertyId.equals( JAXP_SCHEMA_SOURCE)) {            fJAXPSource = state;            fJAXPProcessed = false;        }          else if(propertyId.equals( XMLGRAMMAR_POOL)) {            fGrammarPool = (XMLGrammarPool)state;        }         else if (propertyId.equals(SCHEMA_LOCATION)){            fExternalSchemas = (String)state;        }        else if (propertyId.equals(SCHEMA_NONS_LOCATION)){            fExternalNoNSSchema = (String) state;        }        else if (propertyId.equals(ENTITY_RESOLVER)){            fEntityManager.setProperty(ENTITY_RESOLVER, state);        }        else if (propertyId.equals(ERROR_REPORTER)){            fErrorReporter = (XMLErrorReporter)state;            if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) {                fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, new XSMessageFormatter());            }        }    } // setProperty(String, Object)        /**     * Set the locale to use for messages.     *     * @param locale The locale object to use for localization of messages.     *     * @exception XNIException Thrown if the parser does not support the     *                         specified locale.     */    public void setLocale(Locale locale) {        fLocale = locale;        fErrorReporter.setLocale(locale);    } // setLocale(Locale)        /** Return the Locale the XMLGrammarLoader is using. */    public Locale getLocale() {        return fLocale;    } // getLocale():  Locale        /**     * Sets the error handler.     *     * @param errorHandler The error handler.     */    public void setErrorHandler(XMLErrorHandler errorHandler) {        fErrorReporter.setProperty(ERROR_HANDLER, errorHandler);    } // setErrorHandler(XMLErrorHandler)        /** Returns the registered error handler.  */    public XMLErrorHandler getErrorHandler() {        return fErrorReporter.getErrorHandler();    } // getErrorHandler():  XMLErrorHandler        /**     * Sets the entity resolver.     *     * @param entityResolver The new entity resolver.     */    public void setEntityResolver(XMLEntityResolver entityResolver) {        fUserEntityResolver = entityResolver;        fLoaderConfig.setProperty(ENTITY_RESOLVER, entityResolver);        fEntityManager.setProperty(ENTITY_RESOLVER, entityResolver);    } // setEntityResolver(XMLEntityResolver)        /** Returns the registered entity resolver.  */    public XMLEntityResolver getEntityResolver() {        return fUserEntityResolver;    } // getEntityResolver():  XMLEntityResolver        /**     * Returns a Grammar object by parsing the contents of the     * entities pointed to by sources.     *      * @param source[]  the locations of the entity which forms      *                      the staring point of the grammars to be constructed     * @throws IOException  when a problem is encounted reading the entity     * @throws XNIException when a condition arises (such as a FatalError) that requires parsing     *                          of the entity be terminated     */    public void loadGrammar(XMLInputSource source[])     throws IOException, XNIException {        int numSource = source.length;        for (int i = 0; i < numSource; ++i) {            loadGrammar(source[i]);        }       }        /**     * Returns a Grammar object by parsing the contents of the     * entity pointed to by source.     *     * @param source        the location of the entity which forms     *                          the starting point of the grammar to be constructed.     * @throws IOException      When a problem is encountered reading the entity     *          XNIException    When a condition arises (such as a FatalError) that requires parsing     *                              of the entity be terminated.     */    public Grammar loadGrammar(XMLInputSource source)    throws IOException, XNIException {                // REVISIT: this method should have a namespace parameter specified by         // user. In this case we can easily detect if a schema asked to be loaded        // is already in the local cache.                reset(fLoaderConfig);        fSettingsChanged = false;        XSDDescription desc = new XSDDescription();        desc.fContextType = XSDDescription.CONTEXT_PREPARSE;        desc.setBaseSystemId(source.getBaseSystemId());        desc.setLiteralSystemId( source.getSystemId());        // none of the other fields make sense for preparsing        Hashtable locationPairs = new Hashtable();        // Process external schema location properties.        // We don't call tokenizeSchemaLocationStr here, because we also want        // to check whether the values are valid URI.        processExternalHints(fExternalSchemas, fExternalNoNSSchema,                locationPairs, fErrorReporter);        SchemaGrammar grammar = loadSchema(desc, source, locationPairs);                if(grammar != null && fGrammarPool != null) {            fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, fGrammarBucket.getGrammars());            // NOTE: we only need to verify full checking in case the schema was not provided via JAXP            // since full checking already verified for all JAXP schemas            if(fIsCheckedFully && fJAXPCache.get(grammar) != grammar) {                XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter);            }        }        return grammar;    } // loadGrammar(XMLInputSource):  Grammar        /**     * This method is called either from XMLGrammarLoader.loadGrammar or from XMLSchemaValidator.     * Note: in either case, the EntityManager (or EntityResolvers) are not going to be invoked     * to resolve the location of the schema in XSDDescription      * @param desc     * @param source     * @param locationPairs     * @return An XML Schema grammar     * @throws IOException     * @throws XNIException     */    SchemaGrammar loadSchema(XSDDescription desc,            XMLInputSource source,            Hashtable locationPairs) throws IOException, XNIException {                // this should only be done once per invocation of this object;        // unless application alters JAXPSource in the mean time.        if(!fJAXPProcessed) {            processJAXPSchemaSource(locationPairs);        }        SchemaGrammar grammar = fSchemaHandler.parseSchema(source, desc, locationPairs);                return grammar;    } // loadSchema(XSDDescription, XMLInputSource):  SchemaGrammar        /** This method tries to resolve location of the given schema.     * The loader stores the namespace/location pairs in a hashtable (use "" as the     * namespace of absent namespace). When resolving an entity, loader first tries     * to find in the hashtable whether there is a value for that namespace,     * if so, pass that location value to the user-defined entity resolver.     *     * @param desc     * @param locationPairs     * @param entityResolver     * @return     * @throws IOException     */    public static XMLInputSource resolveDocument(XSDDescription desc, Hashtable locationPairs,            XMLEntityResolver entityResolver) throws IOException {        String loc = null;        // we consider the schema location properties for import        if (desc.getContextType() == XSDDescription.CONTEXT_IMPORT ||                desc.fromInstance()) {            // use empty string as the key for absent namespace            String namespace = desc.getTargetNamespace();            String ns = namespace == null ? XMLSymbols.EMPTY_STRING : namespace;            // get the location hint for that namespace            LocationArray tempLA = (LocationArray)locationPairs.get(ns);            if(tempLA != null)                loc = tempLA.getFirstLocation();        }                // if it's not import, or if the target namespace is not set        // in the schema location properties, use location hint        if (loc == null) {            String[] hints = desc.getLocationHints();            if (hints != null && hints.length > 0)                loc = hints[0];        }                String expandedLoc = XMLEntityManager.expandSystemId(loc, desc.getBaseSystemId(), false);        desc.setLiteralSystemId(loc);        desc.setExpandedSystemId(expandedLoc);        return entityResolver.resolveEntity(desc);    }        // add external schema locations to the location pairs    public static void processExternalHints(String sl, String nsl,            Hashtable locations,            XMLErrorReporter er) {        if (sl != null) {            try {                // get the attribute decl for xsi:schemaLocation                // because external schema location property has the same syntax                // as xsi:schemaLocation                XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION);                // validation the string value to get the list of URI's                attrDecl.fType.validate(sl, null, null);                if (!tokenizeSchemaLocationStr(sl, locations)) {                    // report warning (odd number of items)                    er.reportError(XSMessageFormatter.SCHEMA_DOMAIN,                            "SchemaLocation",                            new Object[]{sl},                            XMLErrorReporter.SEVERITY_WARNING);                }            }            catch (InvalidDatatypeValueException ex) {                // report warning (not list of URI's)                er.reportError(XSMessageFormatter.SCHEMA_DOMAIN,                        ex.getKey(), ex.getArgs(),                        XMLErrorReporter.SEVERITY_WARNING);            }        }                if (nsl != null) {            try {                // similarly for no ns schema location property                XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);                attrDecl.fType.validate(nsl, null, null);                LocationArray la = ((LocationArray)locations.get(XMLSymbols.EMPTY_STRING));                if(la == null) {                    la = new LocationArray();                    locations.put(XMLSymbols.EMPTY_STRING, la);                }                la.addLocation(nsl);            }            catch (InvalidDatatypeValueException ex) {                // report warning (not a URI)                er.reportError(XSMessageFormatter.SCHEMA_DOMAIN,                        ex.getKey(), ex.getArgs(),                        XMLErrorReporter.SEVERITY_WARNING);            }        }    }    // this method takes a SchemaLocation string.    // If an error is encountered, false is returned;    // otherwise, true is returned.  In either case, locations    // is augmented to include as many tokens as possible.    // @param schemaStr     The schemaLocation string to tokenize    // @param locations     Hashtable mapping namespaces to LocationArray objects holding lists of locaitons    // @return true if no problems; false if string could not be tokenized    public static boolean tokenizeSchemaLocationStr(String schemaStr, Hashtable locations) {        if (schemaStr!= null) {            StringTokenizer t = new StringTokenizer(schemaStr, " \n\t\r");            String namespace, location;            while (t.hasMoreTokens()) {                namespace = t.nextToken ();                if (!t.hasMoreTokens()) {                    return false; // error!                }                location = t.nextToken();

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?