Commons XMLConfiguration和架构验证?

时间:2015-02-27 16:55:24

标签: java xml xsd-validation apache-commons-config

我使用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'.

“configuration”是config_default.xml的根元素。我认为这意味着,它无法找到xsd。

我的第一个问题,我必须放入resolver.registerEntityId(“configuration”,urlXsd)的第一个参数;? Waht是架构的公共ID? documentation仅显示DTD公共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的路径进行了测试。但这只适用于ony trail。

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从jar获取xsd:noNamespaceSchemaLocation =“config_schema.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()时直接进行异常处理。

致以最诚挚的问候,

2 个答案:

答案 0 :(得分:1)

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

假设您有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 Configuration 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的{​​{1}}来实现。

DocumentBuilder

答案 1 :(得分: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最后一个例子的绝对路径。