Search code examples
javaclassloaderexecutable-jarrunnabletruststore

Executable jar - loading truststore from projects resources


I am aware that are many similar problems, I think I have read and checked all possibilities and have no idea what I'm doing wrong...

I am loading to System properties two certificates files from project's resources package, and than connecting with them to JMS server. When running application in Eclipse mode everything works fine, problem occurres when trying to read resource from runnable JAR file, it causes an error:

FileNotFoundException: file:\path_to_my_jar!\resources\serverids.jks

The files are places inside jar (in main folder). This folder is placed in src/resources, but I have tried creating resources folder outside src and linking it to build path with the same result.

This is how I'm reading the file and setting properties for connectionManager:

    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    String keyStore =  currentClassLoader.getResource("resources/serverids.jks").getPath();
    String trustStore =  currentClassLoader.getResource("resources/server.truststore").getPath();

    System.setProperty("javax.net.ssl.keyStore", keyStore);
    System.setProperty("javax.net.ssl.keyStorePassword", "pass");
    System.setProperty("javax.net.ssl.trustStore", trustStore);
    System.setProperty("javax.net.ssl.trustStorePassword", "pass");

Solution

  • Get this resource as a InputStream and then read it to String to the property value you'd like to set. Also, in your case you should extract the resource this way:

    CurrentClass.class.getResourceAsStream("blah.jks")

    Please, don't forget to close the stream after processing.