Skip to content

Commit

Permalink
LocationService: fall back to FileLocation more
Browse files Browse the repository at this point in the history
Specifically: if the URI resolution returns null, rather than actually
returning null, let's wrap the string into a FileLocation as a fallback.

See imagej/pyimagej#285.
  • Loading branch information
ctrueden committed Aug 27, 2024
1 parent 055a449 commit 0d95340
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/main/java/org/scijava/io/location/LocationService.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,15 @@ public interface LocationService extends HandlerService<URI, LocationResolver>,
*/
default Location resolve(final String uriString) throws URISyntaxException {
try {
return resolve(new URI(uriString));
Location loc = resolve(new URI(uriString));
if (loc != null) return loc;
}
catch (final URISyntaxException exc) {
// In general, filenames are not valid URI strings.
// Particularly on Windows, there are backslashes, which are invalid in URIs.
// So we explicitly turn this string into a file if an error happens above.
return resolve(new File(uriString).toURI());
}
return resolve(new File(uriString).toURI());
}

/**
Expand Down
19 changes: 19 additions & 0 deletions src/test/java/org/scijava/io/location/LocationServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
package org.scijava.io.location;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
Expand All @@ -43,6 +44,7 @@
* Tests {@link LocationService}.
*
* @author Gabriel Einsdorf
* @author Curtis Rueden
*/
public class LocationServiceTest {

Expand All @@ -60,6 +62,23 @@ public void testResolve() throws URISyntaxException {
assertEquals(uri, loc.resolve(uri.toString()).getURI());
}

@Test
public void testResolveWindowsPath() throws URISyntaxException {
final Context ctx = new Context(LocationService.class);
final LocationService loc = ctx.getService(LocationService.class);

String pSlash = "C:/Windows/FilePath/image.tif";
final Location locSlash = loc.resolve(pSlash);
assertTrue(locSlash instanceof FileLocation);

String pBackslash = pSlash.replace('/', '\\');
final Location locBackslash = loc.resolve(pBackslash);
assertTrue(locBackslash instanceof FileLocation);

final Location locSlashURI = loc.resolve(new URI(pSlash));
assertNull(locSlashURI);
}

@Test
public void testFallBack() throws URISyntaxException {
final Context ctx = new Context(LocationService.class);
Expand Down

0 comments on commit 0d95340

Please sign in to comment.