小编典典

如何可靠地从类路径资源(在jar中)加载XMLCatalog?

java

以下是一些代码片段,这些片段指示我目前正在尝试什么,但是它不可靠。原则上,我认为因为您只能注册一次协议处理程序,偶尔其他库可能会先这样做。

import org.apache.xerces.util.XMLCatalogResolver;



public static synchronized XMLCatalogResolver getResolver() {
        String c[] = {"classpath:xml-catalog.xml"};
        if (cr==null) {

            log.debug("Registering new protcol handler for classpath");
            ConfigurableStreamHandlerFactory configurableStreamHandlerFactory = new ConfigurableStreamHandlerFactory("classpath", new org.fao.oek.protocols.classpath.Handler(XsdUtils.class.getClassLoader()));
            configurableStreamHandlerFactory.addHandler("http", new sun.net.www.protocol.http.Handler());


            URL.setURLStreamHandlerFactory(configurableStreamHandlerFactory);

            log.debug("Creating new catalog resolver");

        cr = new XMLCatalogResolver(c);

        }
        return cr;
    }

xml-catalog.xml包含:

<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<group  prefer="public"  xml:base="classpath:org/me/myapp/xsd/" >  
  <uri name="http://www.w3.org/XML/1998/namespace" uri="xml.xsd"/>
  <uri name="http://www.w3.org/1999/xlink" uri="xlink.xsd" />
  <uri name="http://www.w3.org/2001/XMLSchema" uri="XMLSchema.xsd" />
  <uri name="http://purl.org/dc/elements/1.1/" uri="dc.xsd" />
  <uri name="http://www.loc.gov/mods/v3"  uri="mods-3.3.xsd" />
 </group>
</catalog>

显然-xsd文件位于类路径中的正确位置。


阅读 212

收藏
2020-10-25

共1个答案

小编典典

解析器使用以下最小代码集来正常运行:

public class XsdUtils {
    static {
        System.setProperty("java.protocol.handler.pkgs", "org.fao.oek.protocols");
    }

    private static XMLCatalogResolver cr;

    public static synchronized XMLCatalogResolver getResolver() {
        if (cr == null) {
            cr = new XMLCatalogResolver(new String[] { "classpath:xml-catalog.xml" });
        }
        return cr;
    }

    public static void main(String[] args) throws MalformedURLException, IOException {
        XMLCatalogResolver resolver = getResolver();
        URL url0 = new URL("classpath:xml-catalog.xml");
        URL url1 = new URL(resolver.resolveURI("http://www.loc.gov/mods/v3"));
        url0.openConnection();
        url1.openConnection();
    }
}

您可以选择将其指定java.protocol.handler.pkgs为JVM参数:

java -Djava.protocol.handler.pkgs=org.fao.oek.protocols ...

Handler班是实现如下:

package org.fao.oek.protocols.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class Handler extends java.net.URLStreamHandler {
    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        String resource = u.getPath();
        if (!resource.startsWith("/")) resource = "/" + resource;
        System.out.println(getClass().getResource(resource));
        return getClass().getResource(resource).openConnection();
    }
}

"/"在请求资源时,使用正斜杠()很重要,这已由以下 堆栈溢出
问题回答:“在Java中使用相对路径打开资源”。

注意中的main方法XsdUtils。当xml-catalog.xmlmods-3.3.xsd位于类路径上但不在JAR中时,程序的输出为:

file:/workspace/8412798/target/classes/xml-catalog.xml
file:/workspace/8412798/target/classes/org/me/myapp/xsd/mods-3.3.xsd

当文件位于JAR中时,程序的输出为:

jar:file:/workspace/8412798/target/stackoverflow.jar!/xml-catalog.xml
jar:file:/workspace/8412798/target/stackoverflow.jar!/org/me/myapp/xsd/mods-3.3.xsd

关于原始问题中的此代码:

new org.fao.oek.protocols.classpath.Handler(XsdUtils.class.getClassLoader())

Handler并不需要一个特定的类加载器,除非你已经配置了您的应用程序使用一个特殊的类装载器,像一个从延长URLClassLoader


Java协议处理程序的新时代”
是有关协议处理程序的良好资源。

为了使一切顺利,下面的类用于XsdUtils.getResolver()解析XML。它根据中指定的架构进行验证XMLCatalogResolver

public class SampleParser {
    public static void main(String[] args) throws Exception {
        String xml = "<?xml version=\"1.0\"?>" + //
                "<mods ID=\"id\" version=\"3.3\" xmlns=\"http://www.loc.gov/mods/v3\">" + //
                "<titleInfo></titleInfo>" + //
                "</mods>";
        ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
        XMLReader parser = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName());
        parser.setFeature("http://xml.org/sax/features/validation", true);
        parser.setFeature("http://apache.org/xml/features/validation/schema", true);
        parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        parser.setProperty("http://apache.org/xml/properties/internal/entity-resolver", XsdUtils.getResolver());
        parser.setErrorHandler(new ErrorHandler() {
            @Override
            public void error(SAXParseException exception) throws SAXException {
                System.out.println("error: " + exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                System.out.println("fatalError: " + exception);
            }

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                System.out.println("warning: " + exception);
            }
        });
        parser.parse(new InputSource(is));
    }
}
2020-10-25