gpt4 book ai didi

java - Commons XMLConfiguration 和模式验证?

转载 作者:数据小太阳 更新时间:2023-10-29 02:10:26 37 4
gpt4 key购买 nike

我使用 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); 的第一个参数中输入什么?模式的公共(public) ID 是什么? documentation仅显示带有 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 文件中的路径是正确的,与第一次运行时相同。为什么第一次fun能找到xsd,第二次就找不到?

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

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

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

最好的问候,

最佳答案

resolver.registerEntityId() 的第一个参数是用于映射到特定实体 URL 的公共(public) 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 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();

注意: 以下事实证明与提问者的问题无关,但我将其留在这里以供引用。

如果您想以编程方式设置模式文件,您可以通过设置 XMLConfigurationDocumentBuilder 来实现。

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();
}
}
}

关于java - Commons XMLConfiguration 和模式验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770257/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com