开发者

How to read xml schema from jar file in a servlet context

开发者 https://www.devze.com 2023-02-15 17:46 出处:网络
I have a maven library project with some classes to deal xml messages. Whenever I receive one of those messages I validate it using an xml schema file I have written. The code that does the validation

I have a maven library project with some classes to deal xml messages. Whenever I receive one of those messages I validate it using an xml schema file I have written. The code that does the validation for me looks like this:

public static Document parseXML(final String xml) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", true);
    builder.setFeature("http://apache.org/xml/features/validation/schema", true);
    URL location = CMPMessage.getClass().getResource(XML_SCHEMA_LOCATION);
    if (null == location) {
        throw new IOException("Unable to load schema definition file.");
    }
    builder.se开发者_如何学PythontProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
            "http://www.mycompany.de/MyProtocol " + location);
    return builder.build(new StringReader(xml));
}

and XML_SCHEMA_LOCATION is like this:

private static final String XML_SCHEMA_LOCATION = "/ConvertMessageProtocol.xsd";

The .xsd file is in src/main/resources and, thanks to maven, everything works perfect: The .xsd file gets included in the .jar when tell maven to make a package. I made a simple test project to check whether the .xsd file will actually be found. The source looks like this:

import java.io.IOException;
import org.jdom.JDOMException;
import de.mycomp.MyMessage;


public class Main {
    public static void main(final String[] args) {
        try {
            MyMessage.parseXML(args[0]);
        }
        catch (JDOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

And yes, the xml will be validated using the schema file.

Now here it comes: I want to use my little library in a servlet (running in tomcat), but there, the .xsd file can not be found :(

Of course, I could store the .xsd file somewhere else like directly on the companys server and retrieve it via http, but I think including it in the .jar is the better solution to make sure that the libs and the schemas version fit.

Do you have any ideas what is wrong here?

Thanks in advance:

Jim


assign

private static final String XML_SCHEMA_LOCATION = getPath("/ConvertMessageProtocol.xsd");

public static String getPath(String path){
  return UtilityClass.class.getResource(path).toString();
}

The problem is your servlet app is looking for file at / where there is no file.

0

精彩评论

暂无评论...
验证码 换一张
取 消