14package com.google.ortools;
16import com.sun.jna.Platform;
17import java.io.IOException;
19import java.net.URISyntaxException;
21import java.nio.file.FileSystem;
22import java.nio.file.FileSystemAlreadyExistsException;
23import java.nio.file.FileSystems;
24import java.nio.file.FileVisitResult;
25import java.nio.file.Files;
26import java.nio.file.Path;
27import java.nio.file.SimpleFileVisitor;
28import java.nio.file.attribute.BasicFileAttributes;
29import java.util.Collections;
30import java.util.Objects;
34 private static final String RESOURCE_PATH =
"ortools-" + Platform.RESOURCE_PREFIX +
"/";
37 private static URI getNativeResourceURI() throws IOException {
38 ClassLoader loader = Loader.class.getClassLoader();
39 URL resourceURL = loader.getResource(RESOURCE_PATH);
40 Objects.requireNonNull(resourceURL,
41 String.format(
"Resource %s was not found in ClassLoader %s", RESOURCE_PATH, loader));
45 resourceURI = resourceURL.toURI();
46 }
catch (URISyntaxException e) {
47 throw new IOException(e);
53 private interface PathConsumer<T
extends IOException> {
62 private static Path unpackNativeResources(URI resourceURI)
throws IOException {
64 tempPath = Files.createTempDirectory(
"ortools-java");
65 tempPath.toFile().deleteOnExit();
68 visitor = (Path sourcePath) -> Files.walkFileTree(sourcePath,
new SimpleFileVisitor<Path>() {
70 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
71 Path newPath = tempPath.resolve(sourcePath.getParent().relativize(file).toString());
72 Files.copy(file, newPath);
73 newPath.toFile().deleteOnExit();
74 return FileVisitResult.CONTINUE;
78 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
80 Path newPath = tempPath.resolve(sourcePath.getParent().relativize(dir).toString());
81 Files.copy(dir, newPath);
82 newPath.toFile().deleteOnExit();
83 return FileVisitResult.CONTINUE;
89 fs = FileSystems.newFileSystem(resourceURI, Collections.emptyMap());
90 }
catch (FileSystemAlreadyExistsException e) {
91 fs = FileSystems.getFileSystem(resourceURI);
93 throw new IllegalArgumentException();
96 Path p = fs.provider().getPath(resourceURI);
102 private static boolean loaded =
false;
111 System.loadLibrary(
"jniortools");
114 }
catch (UnsatisfiedLinkError exception) {
118 URI resourceURI = getNativeResourceURI();
119 Path tempPath = unpackNativeResources(resourceURI);
121 System.load(tempPath.resolve(RESOURCE_PATH)
122 .resolve(System.mapLibraryName(
"jniortools"))
126 }
catch (IOException e) {
127 throw new RuntimeException(e);