From 0d9534095735cb75e06adfe42d902de1ac3d5662 Mon Sep 17 00:00:00 2001 From: Curtis Rueden Date: Tue, 27 Aug 2024 10:33:52 -0500 Subject: [PATCH] LocationService: fall back to FileLocation more 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. --- .../scijava/io/location/LocationService.java | 5 +++-- .../io/location/LocationServiceTest.java | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/scijava/io/location/LocationService.java b/src/main/java/org/scijava/io/location/LocationService.java index ff29ce6e0..08aa30759 100644 --- a/src/main/java/org/scijava/io/location/LocationService.java +++ b/src/main/java/org/scijava/io/location/LocationService.java @@ -56,14 +56,15 @@ public interface LocationService extends HandlerService, */ 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()); } /** diff --git a/src/test/java/org/scijava/io/location/LocationServiceTest.java b/src/test/java/org/scijava/io/location/LocationServiceTest.java index cede48501..fb917a694 100644 --- a/src/test/java/org/scijava/io/location/LocationServiceTest.java +++ b/src/test/java/org/scijava/io/location/LocationServiceTest.java @@ -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; @@ -43,6 +44,7 @@ * Tests {@link LocationService}. * * @author Gabriel Einsdorf + * @author Curtis Rueden */ public class LocationServiceTest { @@ -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);