Wednesday, November 30, 2016

Paths in a JAR file

Suppose a JAR file has the following contents:
$ jar -jar simple-service-1.0-SNAPSHOT.jar

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
   159 Mon Nov 28 09:22:20 EST 2016 META-INF/MANIFEST.MF
     0 Mon Nov 28 09:22:20 EST 2016 META-INF/
     0 Mon Nov 28 09:22:20 EST 2016 backup/
  2333 Mon Nov 28 09:22:20 EST 2016 backup/backupController.js
   231 Mon Nov 28 09:22:20 EST 2016 backup/backup.html
     0 Mon Nov 28 09:22:20 EST 2016 WEB-INF/
  1081 Mon Nov 28 09:22:20 EST 2016 WEB-INF/web.xml
     0 Mon Nov 28 09:22:20 EST 2016 com/
     0 Mon Nov 28 09:22:20 EST 2016 com/example/
  1727 Mon Nov 28 09:22:20 EST 2016 com/example/Main.class
   579 Mon Nov 28 09:22:20 EST 2016 com/example/MyResource.class
   556 Mon Nov 28 09:22:20 EST 2016 com/example/MyResource2.class
     0 Mon Nov 28 09:22:20 EST 2016 config/
  2117 Mon Nov 28 09:22:20 EST 2016 config/configController.js
   230 Mon Nov 28 09:22:20 EST 2016 config/config.html
     0 Mon Nov 28 09:22:20 EST 2016 restore/
  2137 Mon Nov 28 09:22:20 EST 2016 restore/restoreController.js
   232 Mon Nov 28 09:22:20 EST 2016 restore/restore.html
  2818 Mon Nov 28 09:22:20 EST 2016 index.html
  2821 Mon Nov 28 09:22:20 EST 2016 hdboost.js

1. Root of a JAR file:
1
2
3
4
5
// file:/home/fos/simple-service-1.0-SNAPSHOT.jar
String webdir = Main.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
// jar:file:/home/fos/simple-service-1.0-SNAPSHOT.jar!/ 
webdir = "jar:" + webdir + "!/";
webapp.setResourceBase(webdir);

2. Path of a resource in a JAR file:
take "index.html" for example:

1
2
// jar:file:/home/fos/simple-service-1.0-SNAPSHOT.jar!/index.html         
String webdir = Main.class.getClassLoader().getResource("index.html").toExternalForm();

Another example with "WEB-INF"

1
2
// WEB-INF: jar:file:/home/fos/simple-service-1.0-SNAPSHOT.jar!/WEB-INF/
String webdir = Main.class.getClassLoader().getResource("WEB-INF").toExternalForm(); 

No comments: