Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make the getParent(URI) helper more robust #10

Merged
merged 1 commit into from
Oct 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions src/main/java/mpicbg/spim/data/generic/XmlIoAbstractSpimData.java
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,44 @@ protected URI loadBasePathURI( final Element root, final URI xmlURI ) throws Spi
return XmlHelpers.loadPathURI( root, BASEPATH_TAG, ".", parent );
}

/**
* Gets a URI's parent, e.g. the containing directory of a file.
* <p>
* This function behaves differently than the invocation
* {@code uri.resolve("..")} when the URI ends in a trailing slash:
* </p>
* <pre>{@code
* jshell> new URI("file:/foo/bar/").resolve("..")
* $1 ==> file:/foo/
*
* jshell> new URI("file:/foo/bar").resolve("..")
* $2 ==> file:/
* }</pre>
* <p>
* Whereas this function returns "file:/foo/" in both cases.
*/
private static URI getParent( final URI uri ) throws SpimDataIOException
{
try
{
final String parent = Paths.get( uri.getPath() ).getParent().toString() + "/";
return new URI( uri.getScheme(), uri.getAuthority(), parent, uri.getQuery(), uri.getFragment() );
final String uriPath = uri.getPath();
final int parentSlash = uriPath.lastIndexOf( "/", uriPath.length() - 2 );
if ( parentSlash < 0 )
{
throw new SpimDataIOException( "URI is already at the root" );
}
// NB: The "+ 1" below is *very important*, so that the resultant URI
// ends in a trailing slash. The behaviour of URI differs depending on
// whether this trailing slash is present; specifically:
//
// * new URI("file:/foo/bar/").resolve(".") -> "file:/foo/bar/"
// * new URI("file:/foo/bar").resolve(".") -> "file:/foo/"
//
// That is: /foo/bar/ is considered to be in the directory /foo/bar,
// whereas /foo/bar is considered to be in the directory /foo.
final String parentPath = uriPath.substring( 0, parentSlash + 1 );
return new URI( uri.getScheme(), uri.getUserInfo(), uri.getHost(),
uri.getPort(), parentPath, uri.getQuery(), uri.getFragment() );
}
catch ( URISyntaxException e )
{
Expand Down
Loading