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;
35 private static URI getNativeResourceURI()
throws IOException {
36 ClassLoader loader =
Loader.class.getClassLoader();
37 String resource = Platform.RESOURCE_PREFIX +
"/";
38 URL resourceURL = loader.getResource(resource);
39 Objects.requireNonNull(resourceURL,
40 String.format(
"Resource %s was not found in ClassLoader %s", resource, loader));
44 resourceURI = resourceURL.toURI();
45 }
catch (URISyntaxException e) {
46 throw new IOException(e);
52 private interface PathConsumer<T
extends IOException> {
53 void accept(Path path)
throws T;
61 private static Path unpackNativeResources(URI resourceURI)
throws IOException {
63 tempPath = Files.createTempDirectory(
"ortools-java");
64 tempPath.toFile().deleteOnExit();
66 PathConsumer<?> visitor;
67 visitor = (Path sourcePath) -> Files.walkFileTree(sourcePath,
new SimpleFileVisitor<Path>() {
69 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
70 Path newPath = tempPath.resolve(sourcePath.getParent().relativize(file).toString());
71 Files.copy(file, newPath);
72 newPath.toFile().deleteOnExit();
73 return FileVisitResult.CONTINUE;
77 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
79 Path newPath = tempPath.resolve(sourcePath.getParent().relativize(dir).toString());
80 Files.copy(dir, newPath);
81 newPath.toFile().deleteOnExit();
82 return FileVisitResult.CONTINUE;
88 fs = FileSystems.newFileSystem(resourceURI, Collections.emptyMap());
89 }
catch (FileSystemAlreadyExistsException e) {
90 fs = FileSystems.getFileSystem(resourceURI);
92 throw new IllegalArgumentException();
95 Path p = fs.provider().getPath(resourceURI);
101 private static boolean loaded =
false;
105 URI resourceURI = getNativeResourceURI();
106 Path tempPath = unpackNativeResources(resourceURI);
108 System.load(tempPath.resolve(Platform.RESOURCE_PREFIX)
109 .resolve(System.mapLibraryName(
"jniortools"))
112 }
catch (IOException e) {
113 throw new RuntimeException(e);