Created
July 4, 2018 14:03
-
-
Save N0NamedGuy/b773a98cbf20f17e5234a83bc78c61b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.net.MalformedURLException; | |
| import java.net.URI; | |
| import java.net.URISyntaxException; | |
| import java.net.URL; | |
| public class URIUtils { | |
| private static final String FAKE_ROOT = "/fakeroot/"; | |
| public URIUtils() { | |
| throw new IllegalAccessError("Utility class"); | |
| } | |
| public static URI resolveJarUri(String relative, URI baseURI) throws URISyntaxException, MalformedURLException { | |
| // JAR URIs are opaque, so they are considered absolute. | |
| // Java by itself won't normalise opaque/absolute URIs. | |
| // We need to "relativise" the jar resource part, that comes | |
| // after the '!' symbol. Let's hack it! | |
| String schemeSpecificPart = baseURI.getSchemeSpecificPart(); | |
| String jarPathSplit[] = schemeSpecificPart.split("!"); | |
| String jarFilePath = jarPathSplit[0]; | |
| String jarResourcePath = jarPathSplit[1]; | |
| // Let's pretend for a moment that jarResourcePath is a file | |
| // And normalise its path | |
| URI fakeFileResourceURI = new URI("file", FAKE_ROOT + jarResourcePath, null); | |
| URL fakeFileURL = new URL(fakeFileResourceURI.toURL(), relative); | |
| URI fakeFileURI = fakeFileURL.toURI(); | |
| URI normalizedFakeFileUri = fakeFileURI.normalize(); | |
| String normalizedResourcePath = normalizedFakeFileUri.getSchemeSpecificPart().replaceFirst(FAKE_ROOT, ""); | |
| URI normalizedJarResourceURI = new URI("jar", jarFilePath + "!/" + normalizedResourcePath, null); | |
| return normalizedJarResourceURI; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment