Skip to content

Commit

Permalink
Moved methods to create paths in other filesystems to ResourceMgr (mi…
Browse files Browse the repository at this point in the history
…ght still not be the best place though).
  • Loading branch information
Aklakan committed Sep 22, 2024
1 parent 2113687 commit f29a1ee
Showing 1 changed file with 55 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
package org.aksw.commons.util.lifecycle;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import org.aksw.commons.util.exception.FinallyRunAll;
Expand Down Expand Up @@ -63,4 +74,48 @@ public void close() {
public boolean isClosed() {
return isClosed.get();
}

/** Create a path and register the filesystem with the resource manager. */
public static Path toPath(ResourceMgr resourceMgr, Class<?> clz, String classPath) throws IOException {
// GtfsMadridBench.class.getResource(name).toURI());
URL url = clz.getResource(classPath);
return toPath(resourceMgr, url);
}

/** Create a path and register the filesystem with the resource manager. */
public static Path toPath(ResourceMgr resourceMgr, URL url) throws IOException {
Objects.requireNonNull(url);
try {
return toPath(resourceMgr, url.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}

// https://stackoverflow.com/a/36021165/160790
/** Create a path and register the filesystem with the resource manager. */
public static Path toPath(ResourceMgr resourceMgr, URI uri) throws IOException {
Path result;
try {
Path rawPath = Paths.get(uri);
result = fixPath(rawPath);
}
catch(FileSystemNotFoundException ex) {
// TODO FileSystem needs to be closed
FileSystem fs = FileSystems.newFileSystem(uri, Collections.<String,Object>emptyMap());
resourceMgr.register(fs);
result = fs.provider().getPath(uri);
}
return result;
}

public static Path fixPath(Path path) {
Path result = path;
Path parentPath = path.getParent();
if(parentPath != null && !Files.exists(parentPath)) {
Path fixedCandidatePath = path.resolve("/modules").resolve(path.getRoot().relativize(path));
result = Files.exists(fixedCandidatePath) ? fixedCandidatePath : path;
}
return result;
}
}

0 comments on commit f29a1ee

Please sign in to comment.