4

我使用 Apache Commons XMLConfiguration 进行配置。现在我需要一个基于模式的验证。但我无法将我的 xsd 添加到 XMLConfiguration。xsd 位于应用程序 jar 文件中。

如果我使用 Java SE 中的方法,验证运行不会出现问题:

private void checkSchema(final Path path) 
        throws SAXException, ParserConfigurationException, IOException
{
    final URL urlXsd = getClass().getResource(ConfigMain.SCHEMA_RESOURCE_PATH);
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = sf.newSchema(urlXsd);
    final Validator validator = schema.newValidator();
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    final DocumentBuilder db = dbf.newDocumentBuilder(); 
    final Document doc = db.parse(path.toFile());
    validator.validate(new DOMSource(doc));
}

但是,如果我将 XMLConfiguration 与 DefaultEntityResolver 一起使用,我就没有成功。

xmlConfig = new XMLConfiguration();
final URL urlXsd = getClass().getResource(SCHEMA_RESOURCE_PATH);
resolver.registerEntityId("configuration", urlXsd);
xmlConfig.setEntityResolver(resolver);
xmlConfig.setSchemaValidation(true);

我得到以下异常:

Caused by: org.xml.sax.SAXParseException; systemId: file:/C:/.../config_default.xml; lineNumber: 2; columnNumber: 16; cvc-elt.1: Cannot find the declaration of element 'configuration'.

“配置”是 config_default.xml 的根元素。我认为这意味着,它找不到 xsd。

我的第一个问题,我必须在 resolver.registerEntityId("configuration", urlXsd); 的第一个参数中输入什么?架构的公共 ID 是什么?该文档仅显示了一个带有 DTD public id 的示例。

这是简化的架构和 xml -> xml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
</configuration>

架构:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"
<xs:element name="configuration">
</xs:element>
</xs:schema>

更新:我的测试基于 dbank 的回答:

package de.company.xmlschematest;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class App
{
    private final XMLConfiguration xmlConfig = new XMLConfiguration();

    private static final Logger LOG = LoggerFactory.getLogger(App.class);
    private static final String CONFIG_FILENAME_DEFAULT = "config_default.xml";
    private static final String CONFIG_FILENAME_LOCAL = 
            "C:\\Data\\config_current.xml";
    private static final Path CONFIG_PATH_LOCAL = Paths.get(
            CONFIG_FILENAME_LOCAL);
    private static final String SCHEMA_FILENAME = "config_schema.xsd";
    /* package */ static final String SCHEMA_RESOURCE_PATH = "/" + SCHEMA_FILENAME;
    private static final String CONFIG_DEFAULT_RESOURCE_PATH = "/" + 
            CONFIG_FILENAME_DEFAULT;

    private static final org.apache.commons.logging.Log LOG_SEC = LogFactory.getLog(App.class);

    public App()
    {
        try
        {
            LOG_SEC.debug("JCL");

            xmlConfig.setLogger(LOG_SEC);

            final URL urlXsd = getClass().getResource(SCHEMA_RESOURCE_PATH);
            final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = sf.newSchema(urlXsd);
            final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setSchema(schema);
            final DocumentBuilder db = dbf.newDocumentBuilder();

            xmlConfig.setDocumentBuilder(db);
            xmlConfig.setSchemaValidation(true);
        }
        catch (SAXException | ParserConfigurationException ex)
        {
            LOG.error("Loading error", ex);
        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        System.out.println("XmlSchemaTest started");
            final App app = new App();
            app.loadConfig();
            System.out.println("Finished");
    }

    private void loadConfig()
    {
        if(Files.exists(CONFIG_PATH_LOCAL))
        {
            try
            {
                xmlConfig.clear();
                LOG.debug("Loading config {}", CONFIG_PATH_LOCAL);
                xmlConfig.setFile(CONFIG_PATH_LOCAL.toFile());
                xmlConfig.refresh();

                LOG.info("Current config loaded");
            }
            catch (final ConfigurationException ex)
            {
                LOG.error("Loading of current config file has failed", ex);
                loadDefault();
            }
        }
        else
        {
            LOG.info("Local configuration is not available");
            loadDefault();
        }
    }

    private void loadDefault()
    {
        try
        {
            xmlConfig.clear();

            LOG.debug("Loading config " + CONFIG_FILENAME_DEFAULT);
            final File oldConfig = xmlConfig.getFile();

            xmlConfig.setURL(getClass().getResource(
                    CONFIG_DEFAULT_RESOURCE_PATH));
            if(oldConfig != null && oldConfig.exists())
            {
                oldConfig.delete();
            }

            xmlConfig.refresh();
            xmlConfig.save(CONFIG_FILENAME_LOCAL);            
            LOG.info("Default config loaded");
        }
        catch (final ConfigurationException ex)
        {
            throw new IllegalStateException("The default config file is "
                    + "not available", ex);
        }
    }
}

现在我用无效的 xml 对其进行了测试,但我只看到输出错误。没有抛出异常。

XmlSchemaTest started
18:23:16.263 [main] DEBUG de.company.xmlschematest.App - JCL
18:23:16.325 [main] DEBUG de.company.xmlschematest.App - Loading config C:\Data\config_current.xml
18:23:16.327 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
18:23:16.328 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
18:23:16.331 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
18:23:16.332 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
18:23:16.332 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
18:23:16.332 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
[Error] config_current.xml:29:21: cvc-complex-type.2.4.a: Invalid content was found starting with element 'number'. One of '{name}' is expected
18:23:16.356 [main] INFO  de.company.xmlschematest.App - Current config loaded
Finished

更新 - xml 中 xsd 的路径: 我认为基于回调的处理不太好。根据您的第一个建议,我已经使用 xsd 的路径在 xml 中进行了测试。但这仅适用于任何路径。

package de.company.xmlschematest;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 *
 * @author RD3
 */
public class App
{
    private final XMLConfiguration xmlConfig = new XMLConfiguration();

    private static final Logger LOG = LoggerFactory.getLogger(App.class);
    private static final String CONFIG_FILENAME_DEFAULT = "config_default.xml";
    private static final String CONFIG_FILENAME_LOCAL = 
            "C:\\Data\\config_current.xml";
    private static final Path CONFIG_PATH_LOCAL = Paths.get(
            CONFIG_FILENAME_LOCAL);
    private static final String SCHEMA_FILENAME = "config_schema.xsd";
    /* package */ static final String SCHEMA_RESOURCE_PATH = "/" + SCHEMA_FILENAME;
    private static final String CONFIG_DEFAULT_RESOURCE_PATH = "/" + 
            CONFIG_FILENAME_DEFAULT;

    private static final org.apache.commons.logging.Log LOG_SEC = LogFactory.getLog(App.class);

    public App()
    {
        LOG_SEC.debug("JCL");

        xmlConfig.setLogger(LOG_SEC);
        xmlConfig.setSchemaValidation(true);
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        System.out.println("XmlSchemaTest started");
            final App app = new App();
            app.loadConfig();
            System.out.println("Finished");
    }

    private void loadConfig()
    {
        if(Files.exists(CONFIG_PATH_LOCAL))
        {
            try
            {
                xmlConfig.clear();
                LOG.debug("Loading config {}", CONFIG_PATH_LOCAL);
                xmlConfig.setFile(CONFIG_PATH_LOCAL.toFile());
                xmlConfig.refresh();

                LOG.info("Current config loaded");
            }
            catch (final ConfigurationException ex)
            {
                LOG.error("Loading of current config file has failed", ex);
                loadDefault();
            }
        }
        else
        {
            LOG.info("Local configuration is not available");
            loadDefault();
        }
    }

    private void loadDefault()
    {
        try
        {
            xmlConfig.clear();

            LOG.debug("Loading config " + CONFIG_FILENAME_DEFAULT);
            final File oldConfig = xmlConfig.getFile();

            xmlConfig.setURL(getClass().getResource(
                    CONFIG_DEFAULT_RESOURCE_PATH));
            if(oldConfig != null && oldConfig.exists())
            {
                oldConfig.delete();
            }

            xmlConfig.refresh();
            xmlConfig.save(CONFIG_FILENAME_LOCAL);            
            LOG.info("Default config loaded");
        }
        catch (final ConfigurationException ex)
        {
            throw new IllegalStateException("The default config file is "
                    + "not available", ex);
        }
    }
}

第一次运行确实处理正确。它从基于 xsi:noNamespaceSchemaLocation="config_schema.xsd" 的 jar 中获取 xsd。然后将从 jar 加载的默认配置写入本地文件系统。我检查了书面文件,找不到奇怪的想法。然后我再次运行示例应用程序,但现在出现以下错误:

XmlSchemaTest started
10:49:58.730 [main] DEBUG de.company.xmlschematest.App - JCL
10:49:58.738 [main] DEBUG de.company.xmlschematest.App - Loading config C:\Data\config_current.xml
10:49:58.740 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
10:49:58.741 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
10:49:58.744 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
10:49:58.745 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
10:49:58.745 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
10:49:58.746 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
10:49:58.795 [main] ERROR de.company.xmlschematest.App - Loading of current config file has failed
org.apache.commons.configuration.ConfigurationException: Error parsing file:/C:/Data/config_current.xml
    at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:1014) ~[commons-configuration-1.10.jar:1.10]
    at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:972) ~[commons-configuration-1.10.jar:1.10]
    at org.apache.commons.configuration.XMLConfiguration$XMLFileConfigurationDelegate.load(XMLConfiguration.java:1647) ~[commons-configuration-1.10.jar:1.10]
    at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:324) ~[commons-configuration-1.10.jar:1.10]
    at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:261) ~[commons-configuration-1.10.jar:1.10]
    at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:238) ~[commons-configuration-1.10.jar:1.10]
    at org.apache.commons.configuration.AbstractFileConfiguration.refresh(AbstractFileConfiguration.java:889) ~[commons-configuration-1.10.jar:1.10]
    at org.apache.commons.configuration.AbstractHierarchicalFileConfiguration.refresh(AbstractHierarchicalFileConfiguration.java:335) ~[commons-configuration-1.10.jar:1.10]
    at de.company.xmlschematest.App.loadConfig(App.java:110) [classes/:na]
    at de.company.xmlschematest.App.main(App.java:68) [classes/:na]
Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'configuration'.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1906) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:379) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:605) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3138) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243) ~[na:1.8.0_31]
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348) ~[na:1.8.0_31]
    at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:1006) ~[commons-configuration-1.10.jar:1.10]
    ... 9 common frames omitted
10:49:58.796 [main] DEBUG de.company.xmlschematest.App - Loading config config_default.xml
10:49:58.862 [main] INFO  de.company.xmlschematest.App - Default config loaded
Finished

他找不到xsd,但是xml文件中的路径是正确的,和第一次运行一样。为什么他在第一次玩的时候能找到 xsd,而在第二次运行时却找不到?

第二个问题,是 XMLConfiguration 的所有可能的日志输出吗?

更新 3:我再次测试并查看,如果我将 xsd 放入本地文件系统,那么第二次运行没有问题。我认为问题是在 xml 中定义路径时对 xsd 的相对搜索。

是否可以从本地文件系统加载 xml 并使用 jar 文件中的模式进行验证?我在调用 load() 或 refresh() 时搜索没有回调和直接异常处理的解决方案。

此致,

4

2 回答 2

1

的第一个参数resolver.registerEntityId()是用于映射到特定实体 URL 的公共 id。我怀疑“配置”是在这里使用的正确值。但是,我认为这里存在一些混淆,在您的情况下,您甚至不需要使用实体解析器。

假设您有一个 mySchema.xsd:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="configuration">
    </xs:element>
</xs:schema>

假设 mySchema.xml 在mypackage.stackoverflow包中的一个 jar 中,并且该 jar 位于C:\path\to\myJar.jar(因为您似乎使用的是 Windows)。使您的 config_default.xml 看起来像:

<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:noNamespaceSchemaLocation="jar:file:/C:/path/to/myJar.jar!/mypackage/stackoverflow/mySchema.xsd">
</configuration>

然后你应该能够只加载 config_default.xml 它将引用 mySchema.xsd 进行验证。

使用Commons 配置 v1.10

XMLConfiguration config = new XMLConfiguration();
config.setFileName("config_default.xml");
config.setSchemaValidation(true);

// This will throw a ConfigurationException if the XML document does not
// conform to its Schema.
config.load();

注意: 以下内容与提问者的问题无关,但我将其留在这里以供参考。

如果您想以编程方式设置架构文件,您可以通过设置XMLConfiguration.DocumentBuilder

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class CommonsConfigTester {

    public static void main(String[] args) {
        XMLConfiguration config = new XMLConfiguration();
        config.setFileName("config_default.xml");
        config.setSchemaValidation(true);

        try {        
            Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File("mySchema.xsd"));
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setSchema(schema);
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            //if you want an exception to be thrown when there is invalid xml document,
            //you need to set your own ErrorHandler because the default
            //behavior is to just print an error message.
            docBuilder.setErrorHandler(new ErrorHandler() {
                @Override
                public void warning(SAXParseException exception) throws SAXException {
                    throw exception;
                }

                @Override
                public void error(SAXParseException exception) throws SAXException {
                    throw exception;
                }

                @Override
                public void fatalError(SAXParseException exception)  throws SAXException {
                    throw exception;
                }  
            });
            config.setDocumentBuilder(docBuilder);
            config.load();
        } catch (ConfigurationException | ParserConfigurationException | SAXException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
于 2015-02-27T20:23:04.717 回答
1

解决方案- 对于我的情况:

我制作了一个扩展 DefaultEntityResolver 的自己的 EntityResolver:

private static class LocalSchemaResolver extends DefaultEntityResolver
    {
        @Override
        public InputSource resolveEntity(final String publicId
                , final String systemId) throws SAXException
        {
            if(systemId.endsWith(SCHEMA_FILENAME))
            {
                final InputStream stream = getClass().getResourceAsStream(SCHEMA_RESOURCE_PATH);
                if(stream != null)
                {
                    final InputSource source = new InputSource(stream);
                    source.setPublicId(publicId);
                    source.setSystemId(systemId);

                    return source;
                }
                else
                {
                    throw new SAXException("Schema '" + SCHEMA_FILENAME 
                            + "' is not available");
                }
            }
            return super.resolveEntity(publicId, systemId);
        }
    }

映射以下

xsi:noNamespaceSchemaLocation="config_schema.xsd"

到 JAR 文件中的相对路径。在我的例子中,我不能像 dbank 最后一个例子那样使用 JAR 的绝对路径。

于 2015-03-05T09:52:03.283 回答