shbolise
shbolise

Reputation: 75

How to use files within a jar file?

I have seen other questions on accessing resource in jar topic but my question is a bit different. I need to use .jks files in my code for a client i am writing to access a webservice. This code works perfectly in my system even when i package it as a jar but when i send jar to another person it gets SSL error. I understood it was unable to access the files as I hardcoded in my code. This was the same even when I added the files in the jar.

Can anybody tell me how to access this file in jar. I do not need to use file reader or buffered reader here as i just need to give path of the file.

Thanks in advance

        SslConfigurator sslConfig = SslConfigurator.newInstance()
                .trustStoreFile("AAAWSKeyStore.jks")
                .trustStorePassword("password")
                .keyStoreFile("AAAWSKeyStore.jks")
                .keyPassword("password")
                .securityProtocol("TLS");

The error thrown here is

    jjava.lang.IllegalStateException: Cannot find key store file ".\AAAWSKeyStore.jks
   ".
    at org.glassfish.jersey.SslConfigurator.createSSLContext(SslConfigurator
 .java:679)
    at GuiAAAWS.sendPost(GuiAAAWS.java:220)
    at GuiAAAWS.OkActionPerformed(GuiAAAWS.java:198)
    at GuiAAAWS.access$2(GuiAAAWS.java:193)
    at GuiAAAWS$3.actionPerformed(GuiAAAWS.java:88)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener

Upvotes: 1

Views: 783

Answers (1)

Boann
Boann

Reputation: 50061

It is not as simple as giving a path to the file, because when it is packed in the jar it is not a real file. You can supply a KeyStore object to the SslConfigurator, however, and that is more flexible than specifying a path, as it can be initialized from any input source, including a resource in a jar:

KeyStore keyStore = KeyStore.getInstance("jks");
try (InputStream in = YourClassName.class.getResourceAsStream("AAAWSKeyStore.jks")) {
    keyStore.load(in, "password".toCharArray());
}

SslConfigurator sslConfig = SslConfigurator.newInstance()
    .trustStore(keyStore)
    .keyStore(keyStore)
    .securityProtocol("TLS");

Upvotes: 2

Related Questions