Search code examples
groovyresourcesclassloader

Groovy resource from classpath not loaded


Good day everyone.

I am using spock framework for testing in my groovy project(IDE - Intellij Idea 12.6). My spock specification class pass filename to groovy object for processing (that file is in classpath for sure), but when i try to get that file this way

    def resource = getClass().getClassloader().getResourceAsStream(filepath)
    assert resource != null : "No input stream found for path ${filepath}"
    def rootNode = new XmlParser().parse(resource)

Then resource == null.

I tried debugging and in Expression Evaluation windows this code getClass().getResource(fileName) returns resource.

I tried to check which classloader used in first case (in class with the code) and in second case (Expression Evaluation window).

In first case classloader was sun.misc.Launcher$AppClassLoader@18dabf1, but in Expression Evaluation window classloader was groovy.lang.GroovyClassLoader$InnerLoader@1e69757 I suppose that's the reason my resource was null.

Can someone guide me about what I am doing wrong and how can I load that resource file ?

UPDATE:

Changed the way resource file was parsed. When filepath - full path to file this works, but if filepath is just file name and that file in classpath then resource == null

UPDATE2:

Change the way resource file loaded, clean up dependencies bit and all is working, I guess yesterday just wasn't my day.


Solution

  • The problem is very likely unrelated to Spock. It's hard to say from a distance what's causing it, but the safest way to read a resource is getClass().getClassLoader().getResourceAsStream() or Thread.currentThread().getContextClassLoader().getResourceAsStream(), depending on the environment.

    Not sure what Groovy does when you do new File(resource), as there is no File(URL) constructor (only a File(URI) constructor). In any case, getting a File from a class path should be avoided whenever possible.