nemo
nemo

Reputation: 1584

Groovy: Preferred Way to Handle Classpath Resource Loading

From my initial research I've found that I can load classpath resources in groovy by the following approaches:

  1. this.getClass().getClassLoader.getResourceAsStream(resourceName)
  2. ClasspathResourceManager (for which I couldn't find any examples)

So, I wanted to seek opinions on what is the most 'groovy' way of handling classpath resources?

Further more, I have a list of '*.xsd' files under and 'xsd' directory inside my jar. Is there anyway I can do something similar to this, but with classpath resources?

List<StreamSource> schemaDefinitions = new File('src/main/resources/xsd')
  .listFiles( { dir, file -> file ==~ /.*\.xsd/ } as FilenameFilter )
  .collect { new StreamSource(it) }

// Looking for something like this:
List<StreamSource> schemaDefinitions = this.getClass().getResource('src/main/resources/xsd')
  .listFiles( { dir, file -> file ==~ /.*\.xsd/ } as FilenameFilter )
  .collect { new StreamSource(it) }

Thanks!

Upvotes: 3

Views: 4205

Answers (2)

nemo
nemo

Reputation: 1584

Thank you @tim_yates for the quick reply.

Since the library I'm writing is pretty thin, I'm hesitant to introduce a dependency like reflections at the moment, so for now I went with this solution:

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

I will take a look at reflections soon and see how I can apply the same. In the meanwhile, could you please comment on my approach vs. using reflections?

Thanks!

Upvotes: 1

tim_yates
tim_yates

Reputation: 171054

Answers in turn;

1:

String xsd = this.getClass().getResource('/xsd/file.xsd').text

And 2:

No. But there's a library that makes it easy

Upvotes: 3

Related Questions