nemo
nemo

Reputation: 1584

Groovy: Classpath Resource Loading Not Working For Resources Inside Dependency Jars

I have two projects:

  1. Main: M
  2. Dependency: D

Project D has a subdirectory called 'xsd' where it has a few XSD files that it uses for validation.

This is the piece of code in project D that retrieves these XSD files:

private List<StreamSource> retrieveSchemaDefinitionsFromClasspath(String classpathXsdDir, String schemaDefinitionFilePattern) {
  ClasspathResourceManager resourceManager = new ClasspathResourceManager()
  List<String> schemaDefinitionFileNames = resourceManager.getReader(classpathXsdDir).text.split()
  schemaDefinitionFileNames.findAll { it ==~ schemaDefinitionFilePattern }.collect {
    new StreamSource(resourceManager.getReader("$classpathXsdDir/$it"))
  }
}

Now, this piece of code works well when I run my test cases.

However, when I use project D as a dependency inside project M, I get a NullPointerException on this line of the above method:

  List<String> schemaDefinitionFileNames = resourceManager.getReader(classpathXsdDir).text.split()

I've looked at this answer: Load jar file contained within another jar file not working which points to the JarClassLoader turorial: http://docs.oracle.com/javase/tutorial/deployment/jar/jarclassloader.html

However, from what I could gather from the JarClassLoader tutorial, it looks like I need to specify the name of the jar.

But, I want to be able to seamlessly use the dependency jar produced by project D in any project without having to worry about what project/jar D does to load it's reasources.

So, what is the best way to approach this problem?

Thanks!

Upvotes: 0

Views: 488

Answers (1)

danehammer
danehammer

Reputation: 416

You can use Class#getResource(String) to do exactly what I think you're going for. It's used in service lookup patterns a lot, like for finding implementations of an SPI.

Beware, the classpath lookup can get very slow in large classpaths. You want to cache the answer eternally, most likely. In some cases that might still be too slow (especially if it doesn't get primed by a bootstrapping area of your code).

Upvotes: 1

Related Questions