0

I am able to run a java program from within my IDE (IntelliJ) properly; however, when I attempt to run the same program from the command line it fails. The error being thrown is:

RuntimeUnmarshallException: org.xml.sax.SAXParseException; schema_reference.4: Failed to read schema document 'file:/home/Experiments/file:/home/path/to/jar/my.jar!/configuration.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

The stack trace points out that the issue is here:

String SCHEMA_FILE_PATH = "configuration.xsd";
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(SCHEMA_FILE_PATH); // <- breaks here
return new File(resource.getFile());

I have the schema file that cannot be found stored in a directory that is marked as a resource root in my IDE. I am betting that when I run from the command line that since I am running from a different working directory that it does not know where to look. I have tried setting the classpath on the command line to be able to look in the directory that contains the schema, but this did not help. I imagine that I could set the working directory to what it is when I run from my IDE, but this seems like a horrible design choice.

Thanks for any help.

EDIT: I just confirmed that the configuration.xsd file is contained in the jar, but for whatever reason it seems to be looking for it in weird places...

mjnichol
  • 361
  • 1
  • 3
  • 11

1 Answers1

1

When running a .jar, its content is not unpacked, but read directly from the .jar. Therefore the resource you are loading can not be represented as a File (it is still nested inside the .jar). You can see that in the error message - the part after the exclamation mark is the path to the resource inside the jar.

I would recommend using Classloader.getResourceAsStream(..) instead. It handles the loading transparently.

Note that you can use new StreamSource(InputStream) to construct a reference to the schema document from the stream.

Here is some official information about resource loading, and this question may be of interest.

Community
  • 1
  • 1
Pyranja
  • 3,529
  • 22
  • 24