/*
 * Class NativeUtils is published under the The MIT License:
 *
 * Copyright (c) 2012 Adam Heinrich <adam@adamh.cz>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package cz.adamh.utils;

import java.io.*;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.ProviderNotFoundException;

/**
 * A simple library class which helps with loading dynamic libraries stored in the
 * JAR archive. These libraries usualy contain implementation of some methods in
 * native code (using JNI - Java Native Interface).
 * 
 * @see http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar
 * @see https://github.com/adamheinrich/native-utils
 *
 */
public class NativeUtils {
 
    /**
     * Private constructor - this class will never be instanced
     */
    private NativeUtils() {
    }
 
    /**
     * Loads library from current JAR archive
     * 
     * The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after exiting.
     * Method uses String as filename because the pathname is "abstract", not system-dependent.
     * 
     * @param path The path of file inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext
     * @throws IOException If temporary file creation or read/write operation fails
     * @throws IllegalArgumentException If source file (param path) does not exist
     * @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters (restriction of {@see File#createTempFile(java.lang.String, java.lang.String)}).
     */
    public static void loadLibraryFromJar(String path) throws IOException {
 
        if (!path.startsWith("/")) {
            throw new IllegalArgumentException("The path has to be absolute (start with '/').");
        }
 
        // Obtain filename from path
        String[] parts = path.split("/");
        String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
 
        // Check if the filename is okay
        if (filename == null || filename.length() < 3) {
            throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
        }
 
        // Prepare temporary file
        File tempDir = createTempDirectory("nativeutils");
        File temp = new File(tempDir, filename);
        
        boolean tempFileIsPosix = false;
        try {
            if (FileSystems.getDefault()
                    .supportedFileAttributeViews()
                    .contains("posix")) {
                // Assume POSIX compliant file system, can be deleted after loading.
                tempFileIsPosix = true;
            }
        } catch (FileSystemNotFoundException
                | ProviderNotFoundException
                | SecurityException e) {
            // Assume non-POSIX, and don't delete until last file descriptor closed.
        }

        // Prepare buffer for data copying
        byte[] buffer = new byte[1024];
        int readBytes;

        // Open and check input stream
        InputStream is = NativeUtils.class.getResourceAsStream(path);
        if (is == null) {
        	tempDir.delete();
            throw new FileNotFoundException("File " + path + " was not found inside JAR.");
        }

        // Open output stream and copy data between source file in JAR and the temporary file
        OutputStream os = new FileOutputStream(temp);
        try {
            while ((readBytes = is.read(buffer)) != -1) {
                os.write(buffer, 0, readBytes);
            }
        } catch (Throwable e) {
        	temp.delete();
            tempDir.delete();
            throw e;
        } finally {
            // If read/write fails, close streams safely before throwing an exception
            os.close();
            is.close();
        }

        try {
            // Load the library
            System.load(temp.getAbsolutePath());
        } finally {
            if (tempFileIsPosix) {
                temp.delete();
                tempDir.delete();
            }
            else {
            	temp.deleteOnExit();
            	tempDir.deleteOnExit();
            }
        }
    }
    
    private static File createTempDirectory(String prefix) throws IOException
    {
    	String tempDir = System.getProperty("java.io.tmpdir");
    	File generatedDir = new File(tempDir, prefix + System.nanoTime());
    	
    	if (!generatedDir.mkdir())
    		throw new IOException("Failed to create temp directory " + generatedDir.getName());
    	
    	return generatedDir;
    }
}

@@ -1758,24 +1758,61 @@
 veUtils %7B%0A %0A
+%09private static File temporaryDir;%0A%09%0A
     /**%0A    
@@ -1911,24 +1911,29 @@
 ) %7B%0A    %7D%0A %0A
+    %0A
     /**%0A    
@@ -3338,25 +3338,62 @@
         
-File temp
+if (temporaryDir == null) %7B%0A        %09temporary
 Dir = cr
@@ -3422,24 +3422,72 @@
 iveutils%22);%0A
+        %09temporaryDir.deleteOnExit();%0A        %7D%0A
         File
@@ -3503,24 +3503,29 @@
 ew File(temp
+orary
 Dir, filenam
@@ -4334,37 +4334,8 @@
 ull)
- %7B%0A        %09tempDir.delete();
 %0A   
@@ -4422,26 +4422,16 @@
  JAR.%22);
-%0A        %7D
 %0A%0A      
@@ -4766,38 +4766,8 @@
 ();%0A
-            tempDir.delete();%0A
     
@@ -5095,18 +5095,16 @@
 IsPosix)
- %7B
 %0A       
@@ -5131,56 +5131,8 @@
 ();%0A
-                tempDir.delete();%0A            %7D%0A
     
@@ -5143,18 +5143,16 @@
     else
- %7B
 %0A       
@@ -5182,59 +5182,8 @@
 ();%0A
-            %09tempDir.deleteOnExit();%0A            %7D%0A
     

Create a single temporary directory instead of one for each file.