tribbloid
tribbloid

Reputation: 3858

$Class.getResource failed from fat jar packed by maven shade plugin

My java/scala program requires support from a javescript code snippet. So I put it in my resource folder:

resources
|- sizzle.js

And in my pom.xml to explicitly include it in the fat/uber jar compiled by maven shade plugin:

                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.IncludeResourceTransformer">
                            <resource>resources</resource>
                            <file>sizzle.js</file>
                        </transformer>
                    </transformers>

(I know this is unnecessary, but either way it will fail me)

When I try to read the javascript snippet from my source code:

sizzleSource = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResource("sizzle.js"));

it works perfectly when running in IDE, but I get null pointer exception when executing the fat jar:

...
java.lang.NullPointerException
at org.apache.commons.io.IOUtils.toString(IOUtils.java:894)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:879)
...

So why maven shade plugin fail in this case? I'm able to see sizzle.js in the root dir of the fat jar, but it doesn't make a difference.

Upvotes: 0

Views: 2662

Answers (1)

Tunaki
Tunaki

Reputation: 137209

The file sizzle.js ends up at the root of your final jar, so you need to access it via :

Thread.currentThread().getContextClassLoader().getResource("/sizzle.js"));

The method ClassLoader.getResource(name) needs an absolute path to look for a resource.

Upvotes: 1

Related Questions