How to read XML schema from jar file in servlet context

I have a maven library project with some classes for handling xml messages. Whenever I receive one of these messages, I check it using the xml schema file I wrote. The code that performs the check for me is as follows:

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.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://www.mycompany.de/MyProtocol " + location); return builder.build(new StringReader(xml)); } 

and XML_SCHEMA_LOCATION as follows:

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

The .xsd file is located in src/main/resources , and thanks to maven everything works fine: the .xsd file is included in the .jar when maven is reported to make the package. I did a simple test project to check if a .xsd file would actually be found. The source is as follows:

 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, xml will be checked using a schema file.

Now here it is: I want to use my little library in the servlet (works in tomcat), but there the .xsd file cannot be found: (

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

Do you have any ideas what is wrong here?

Thank you in advance:

Jim

+4
source share
1 answer

to appoint

 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 that your servlet application is looking for a file in / where there is no file.

+4
source

Source: https://habr.com/ru/post/1342810/


All Articles