1 package com.google.ortools;
3 import com.sun.jna.Platform;
4 import java.io.IOException;
6 import java.net.URISyntaxException;
8 import java.nio.file.FileSystem;
9 import java.nio.file.FileSystems;
10 import java.nio.file.FileSystemAlreadyExistsException;
11 import java.nio.file.FileVisitResult;
12 import java.nio.file.Files;
13 import java.nio.file.Path;
14 import java.nio.file.SimpleFileVisitor;
15 import java.nio.file.attribute.BasicFileAttributes;
16 import java.util.Collections;
17 import java.util.Objects;
22 private static URI getNativeResourceURI()
throws IOException {
23 ClassLoader loader =
Loader.class.getClassLoader();
24 String resource = Platform.RESOURCE_PREFIX +
"/";
25 URL resourceURL = loader.getResource(resource);
26 Objects.requireNonNull(resourceURL,
27 String.format(
"Resource %s was not found in ClassLoader %s", resource, loader));
31 resourceURI = resourceURL.toURI();
32 }
catch (URISyntaxException e) {
33 throw new IOException(e);
39 private interface PathConsumer<T
extends IOException> {
40 void accept(Path path)
throws T;
48 private static Path unpackNativeResources(URI resourceURI)
throws IOException {
50 tempPath = Files.createTempDirectory(
"ortools-java");
51 tempPath.toFile().deleteOnExit();
53 PathConsumer<?> visitor;
54 visitor = (Path sourcePath) -> Files.walkFileTree(sourcePath,
new SimpleFileVisitor<Path>() {
56 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
57 Path newPath = tempPath.resolve(sourcePath.getParent().relativize(file).toString());
58 Files.copy(file, newPath);
59 newPath.toFile().deleteOnExit();
60 return FileVisitResult.CONTINUE;
64 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
66 Path newPath = tempPath.resolve(sourcePath.getParent().relativize(dir).toString());
67 Files.copy(dir, newPath);
68 newPath.toFile().deleteOnExit();
69 return FileVisitResult.CONTINUE;
75 fs = FileSystems.newFileSystem(resourceURI, Collections.emptyMap());
76 }
catch (FileSystemAlreadyExistsException e) {
77 fs = FileSystems.getFileSystem(resourceURI);
79 throw new IllegalArgumentException();
82 Path p = fs.provider().getPath(resourceURI);
88 private static boolean loaded =
false;
92 URI resourceURI = getNativeResourceURI();
93 Path tempPath = unpackNativeResources(resourceURI);
95 System.load(tempPath.resolve(Platform.RESOURCE_PREFIX)
96 .resolve(System.mapLibraryName(
"jniortools"))
99 }
catch (IOException e) {
100 throw new RuntimeException(e);