11package com .mapzen .jpostal ;
22
3+ import java .io .*;
34import java .util .Objects ;
45
56public final class Config {
7+ private static boolean libLoaded = false ;
8+
69 private final String dataDir ;
710 private final String libraryFile ;
811
@@ -23,7 +26,7 @@ void loadLibrary() {
2326 if (this .libraryFile != null ) {
2427 System .load (this .libraryFile );
2528 } else {
26- System . loadLibrary ("jpostal" );
29+ loadLibraryFromJar ("jpostal" );
2730 }
2831 }
2932
@@ -72,4 +75,48 @@ public Builder libraryFile(final String libraryFile) {
7275 return this ;
7376 }
7477 }
78+
79+ public static synchronized void loadLibraryFromJar (String libraryName ) {
80+ if (libLoaded ) {
81+ return ;
82+ }
83+
84+ try {
85+ String osName = System .getProperty ("os.name" ).toLowerCase ();
86+ String nativeLibFileName ;
87+ String fullPathInJar ;
88+ if (osName .contains ("nix" ) || osName .contains ("nux" ) || osName .contains ("aix" )) {
89+ nativeLibFileName = "lib" + libraryName + ".so" ;
90+ } else if (osName .contains ("mac" )) {
91+ nativeLibFileName = "lib" + libraryName + ".dylib" ;
92+ } else {
93+ throw new UnsupportedOperationException ("Unsupported OS: " + osName );
94+ }
95+ fullPathInJar = "/" + nativeLibFileName ;
96+
97+ InputStream in = Config .class .getResourceAsStream (fullPathInJar );
98+ if (in == null ) {
99+ throw new UnsatisfiedLinkError ("Native library " + fullPathInJar + " not found in JAR." );
100+ }
101+
102+ File tempFile = File .createTempFile ("lib" , nativeLibFileName .substring (nativeLibFileName .lastIndexOf ('.' )));
103+ tempFile .deleteOnExit ();
104+
105+ try (OutputStream out = new FileOutputStream (tempFile )) {
106+ byte [] buffer = new byte [8192 ];
107+ int bytesRead ;
108+ while ((bytesRead = in .read (buffer )) != -1 ) {
109+ out .write (buffer , 0 , bytesRead );
110+ }
111+ } finally {
112+ in .close ();
113+ }
114+
115+ System .load (tempFile .getAbsolutePath ());
116+ libLoaded = true ;
117+
118+ } catch (IOException e ) {
119+ throw new UnsatisfiedLinkError ("Failed to load native library " + libraryName + ": " + e .getMessage ());
120+ }
121+ }
75122}
0 commit comments