diff --git a/microsphere-java-core/src/main/java/io/microsphere/event/AbstractEventDispatcher.java b/microsphere-java-core/src/main/java/io/microsphere/event/AbstractEventDispatcher.java index 351371744..0ddae0da3 100644 --- a/microsphere-java-core/src/main/java/io/microsphere/event/AbstractEventDispatcher.java +++ b/microsphere-java-core/src/main/java/io/microsphere/event/AbstractEventDispatcher.java @@ -39,6 +39,7 @@ import static io.microsphere.lang.function.ThrowableAction.execute; import static io.microsphere.logging.LoggerFactory.getLogger; import static io.microsphere.util.Assert.assertNotNull; +import static io.microsphere.util.ClassLoaderUtils.getClassLoader; import static io.microsphere.util.ClassLoaderUtils.getDefaultClassLoader; import static io.microsphere.util.ServiceLoaderUtils.loadServicesList; import static java.util.Collections.sort; @@ -95,7 +96,9 @@ public abstract class AbstractEventDispatcher implements EventDispatcher { private final Object mutex = new Object(); - protected final Logger logger = getLogger(this.getClass()); + private final Class type = this.getClass(); + + protected final Logger logger = getLogger(type); private final ConcurrentMap, List> listenersCache = newConcurrentHashMap(); @@ -214,7 +217,7 @@ void doInListener(Class eventType, Consumer loadServicesList(EventListener.class, getDefaultClassLoader(), true) + execute(() -> loadServicesList(EventListener.class, getClassLoader(this.type), true) .stream() .sorted() .forEach(this::addEventListener), e -> logger.trace(e.getMessage())); diff --git a/microsphere-java-core/src/main/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactory.java b/microsphere-java-core/src/main/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactory.java index c0c397855..5ecc8a5d8 100644 --- a/microsphere-java-core/src/main/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactory.java +++ b/microsphere-java-core/src/main/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactory.java @@ -134,11 +134,18 @@ public boolean supports(@Nonnull URL url, @Nonnull List subProtocols) { @Nullable public URLConnection create(@Nonnull URL url, @Nonnull List subProtocols, @Nonnull Proxy proxy) throws IOException { SubProtocolURLConnectionFactory factory = selectFactory(url, subProtocols); + if (factory == null) { + throw new IOException("No SubProtocolURLConnectionFactory supports : " + url); + } return factory.create(url, subProtocols, proxy); } + @Nullable SubProtocolURLConnectionFactory selectFactory(URL url, List subProtocols) { int index = selectFactoryIndex(url, subProtocols); + if (index < 0) { + return null; + } return factories.get(index); } diff --git a/microsphere-java-core/src/main/java/io/microsphere/net/URLUtils.java b/microsphere-java-core/src/main/java/io/microsphere/net/URLUtils.java index f2f9ecc02..4f254e308 100644 --- a/microsphere-java-core/src/main/java/io/microsphere/net/URLUtils.java +++ b/microsphere-java-core/src/main/java/io/microsphere/net/URLUtils.java @@ -13,6 +13,7 @@ import io.microsphere.util.Utils; import java.io.File; +import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; @@ -291,11 +292,11 @@ protected static File doResolveArchiveFile(@Nonnull URL url) throws NullPointerE @Nullable protected static File resolveArchiveDirectory(@Nonnull URL resourceURL) { - String resourcePath = buildPath(resourceURL); + String resourcePath = resolvePathFromFile(resourceURL); Set classPaths = getClassPaths(); File archiveDirectory = null; for (String classPath : classPaths) { - if (resourcePath.contains(classPath)) { + if (isResourcePathOnClassPath(resourcePath, classPath)) { archiveDirectory = new File(classPath); break; } @@ -303,6 +304,37 @@ protected static File resolveArchiveDirectory(@Nonnull URL resourceURL) { return archiveDirectory; } + /** + * Tests whether the resource path is located under the specified class path, based on + * their canonical paths and a path-separator boundary, instead of substring matching : + * {@code "/opt/app/classes/Foo.class"} matches the class path {@code "/opt/app"} while + * {@code "/opt/application/Foo.class"} does not, which substring matching would wrongly accept. + * + * @param resourcePath the path of the resource resolved from {@link URL} + * @param classPath the class path entry from the "java.class.path" property + * @return {@code true} if the resource path is the class path itself or located under it + */ + static boolean isResourcePathOnClassPath(@Nullable String resourcePath, @Nullable String classPath) { + if (isBlank(resourcePath) || isBlank(classPath)) { + return false; + } + String resourceCanonicalPath = resolveCanonicalPath(resourcePath); + String classCanonicalPath = resolveCanonicalPath(classPath); + return resourceCanonicalPath.equals(classCanonicalPath) + || resourceCanonicalPath.startsWith(classCanonicalPath.endsWith(File.separator) + ? classCanonicalPath : classCanonicalPath + File.separatorChar); + } + + @Nonnull + private static String resolveCanonicalPath(@Nonnull String path) { + File file = new File(path); + try { + return file.getCanonicalPath(); + } catch (IOException e) { + return file.getAbsolutePath(); + } + } + /** * Resolve the query parameters {@link Map} from specified URL. The parameter name is used as the key, and the list of parameter values is used as the value. * diff --git a/microsphere-java-core/src/main/java/io/microsphere/text/FormatUtils.java b/microsphere-java-core/src/main/java/io/microsphere/text/FormatUtils.java index 2efd9aa5d..3fc47d784 100644 --- a/microsphere-java-core/src/main/java/io/microsphere/text/FormatUtils.java +++ b/microsphere-java-core/src/main/java/io/microsphere/text/FormatUtils.java @@ -73,14 +73,18 @@ public static String formatWithPlaceholder(@Nullable String pattern, @Nonnull St } int offset = placeholder.length(); StringBuilder stringBuilder = new StringBuilder(pattern); - int index = -1; + // The search cursor tracks the position right after the replacement result, + // so that an argument value containing the placeholder itself (e.g. user input "a{}b") + // won't be corrupted by subsequent argument replacements. + int searchFrom = 0; for (int i = 0; i < argsLength; i++) { - index = stringBuilder.indexOf(placeholder); + int index = stringBuilder.indexOf(placeholder, searchFrom); if (index == -1) { break; } String value = valueOf(args[i]); stringBuilder.replace(index, index + offset, value); + searchFrom = index + value.length(); } return stringBuilder.toString(); } diff --git a/microsphere-java-core/src/test/java/io/microsphere/event/DirectEventDispatcherTest.java b/microsphere-java-core/src/test/java/io/microsphere/event/DirectEventDispatcherTest.java index f2a388621..a755ee41a 100644 --- a/microsphere-java-core/src/test/java/io/microsphere/event/DirectEventDispatcherTest.java +++ b/microsphere-java-core/src/test/java/io/microsphere/event/DirectEventDispatcherTest.java @@ -21,9 +21,16 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + import static io.microsphere.collection.Lists.ofList; +import static io.microsphere.lang.Prioritized.MAX_PRIORITY; import static io.microsphere.util.ValueHolder.of; import static java.util.Collections.emptyList; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -181,4 +188,86 @@ void testAddEventListenerOnLambdaForm() { assertSame(eventHolder.getValue(), event); assertEquals(3, counter.get()); } + + /** + * Regression test for issue #320 : a listener exception must not break the dispatch + * chain — the remaining listeners still receive the event, and the failure is logged + * instead of being swallowed. + */ + @Test + void testDispatchOnListenerException() { + EventListener failingListener = new EventListener() { + + @Override + public void onEvent(EchoEvent event) { + throw new IllegalStateException("intentional failure"); + } + + @Override + public int getPriority() { + return MAX_PRIORITY; // dispatched first + } + }; + + // The failing listener is dispatched first + this.dispatcher.addEventListeners(failingListener, echoEventListener, echoEventListener2); + + assertDoesNotThrow(() -> this.dispatcher.dispatch(new EchoEvent("Hello,World"))); + + // The listeners after the failing one still received the event + assertEquals(1, echoEventListener.getEventOccurs()); + assertEquals(1, echoEventListener2.getEventOccurs()); + } + + /** + * Regression test for issue #320 : dispatching (read) while registering/unregistering + * listeners (write) must not throw ConcurrentModificationException or corrupt the + * listener lists. + */ + @Test + void testConcurrentDispatchAndRegistration() throws InterruptedException { + this.dispatcher.addEventListeners(echoEventListener, echoEventListener2); + + final int writerThreads = 2, readerThreads = 2, iterations = 200; + Queue errors = new ConcurrentLinkedQueue<>(); + CountDownLatch done = new CountDownLatch(writerThreads + readerThreads); + + for (int i = 0; i < writerThreads; i++) { + new Thread(() -> { + try { + for (int j = 0; j < iterations; j++) { + EventListener transientListener = new EventListener() { + @Override + public void onEvent(EchoEvent event) { + } + }; + this.dispatcher.addEventListener(transientListener); + this.dispatcher.removeEventListener(transientListener); + } + } catch (Throwable t) { + errors.add(t); + } finally { + done.countDown(); + } + }, "event-writer-" + i).start(); + } + + for (int i = 0; i < readerThreads; i++) { + new Thread(() -> { + try { + for (int j = 0; j < iterations; j++) { + this.dispatcher.dispatch(new EchoEvent("concurrent-" + j)); + this.dispatcher.getAllEventListeners(); + } + } catch (Throwable t) { + errors.add(t); + } finally { + done.countDown(); + } + }, "event-reader-" + i).start(); + } + + assertTrue(done.await(30, TimeUnit.SECONDS)); + assertTrue(errors.isEmpty(), "Concurrent dispatch/registration failures : " + errors); + } } diff --git a/microsphere-java-core/src/test/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactoryTest.java b/microsphere-java-core/src/test/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactoryTest.java index d36e8723e..b73caaa34 100644 --- a/microsphere-java-core/src/test/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactoryTest.java +++ b/microsphere-java-core/src/test/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactoryTest.java @@ -31,6 +31,8 @@ import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -93,4 +95,55 @@ void testSupports() throws MalformedURLException { composite.addInternal(factory); assertFalse(composite.supports(url, ofList("test"))); } + + /** + * Regression test for issue #317 : create() must throw a contextual {@link IOException} + * when no factory supports the URL, instead of an obscure IndexOutOfBoundsException + * caused by {@code factories.get(-1)}. + */ + @Test + void testCreateOnNoFactorySupports() throws MalformedURLException { + CompositeSubProtocolURLConnectionFactory composite = this.composite; + URL url = new URL("ftp://..."); + List subProtocols = emptyList(); + + // Empty composite + IOException thrown = assertThrows(IOException.class, () -> composite.create(url, subProtocols, NO_PROXY)); + assertTrue(thrown.getMessage().contains(String.valueOf(url))); + + // A factory exists but does not support the URL + composite.addInternal(new FalseSubProtocolURLConnectionFactory()); + assertThrows(IOException.class, () -> composite.create(url, subProtocols, NO_PROXY)); + } + + @Test + void testCreate() throws IOException { + CompositeSubProtocolURLConnectionFactory composite = this.composite; + composite.add(new ConsoleSubProtocolURLConnectionFactory()); + + URL url = new URL("ftp://..."); + List subProtocols = emptyList(); + URLConnection urlConnection = composite.create(url, subProtocols, NO_PROXY); + assertEquals(ConsoleURLConnection.class, urlConnection.getClass()); + } + + @Test + void testSelectFactory() throws MalformedURLException { + CompositeSubProtocolURLConnectionFactory composite = this.composite; + URL url = new URL("ftp://..."); + List subProtocols = ofList("test"); + + // No factories at all + assertNull(composite.selectFactory(url, subProtocols)); + + // Only a non-supporting factory + FalseSubProtocolURLConnectionFactory factory = new FalseSubProtocolURLConnectionFactory(); + composite.addInternal(factory); + assertNull(composite.selectFactory(url, subProtocols)); + + // A supporting factory is selected (sorted after the non-supporting one) + composite.add(new ConsoleSubProtocolURLConnectionFactory()); + SubProtocolURLConnectionFactory selected = composite.selectFactory(url, subProtocols); + assertEquals(ConsoleSubProtocolURLConnectionFactory.class, selected.getClass()); + } } diff --git a/microsphere-java-core/src/test/java/io/microsphere/net/URLUtilsTest.java b/microsphere-java-core/src/test/java/io/microsphere/net/URLUtilsTest.java index 3793cb37a..a439f9737 100644 --- a/microsphere-java-core/src/test/java/io/microsphere/net/URLUtilsTest.java +++ b/microsphere-java-core/src/test/java/io/microsphere/net/URLUtilsTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import javax.annotation.Nonnull; import java.io.File; @@ -59,10 +60,12 @@ import static io.microsphere.net.URLUtils.isArchiveURL; import static io.microsphere.net.URLUtils.isDirectoryURL; import static io.microsphere.net.URLUtils.isJarURL; +import static io.microsphere.net.URLUtils.isResourcePathOnClassPath; import static io.microsphere.net.URLUtils.normalizePath; import static io.microsphere.net.URLUtils.ofURL; import static io.microsphere.net.URLUtils.registerURLStreamHandler; import static io.microsphere.net.URLUtils.resolveArchiveEntryPath; +import static io.microsphere.net.URLUtils.resolveArchiveDirectory; import static io.microsphere.net.URLUtils.resolveArchiveFile; import static io.microsphere.net.URLUtils.resolveBasePath; import static io.microsphere.net.URLUtils.resolveMatrixParameters; @@ -204,6 +207,70 @@ void testResolveArchiveFileOnNotFoundJar() { assertNull(resolveArchiveFile(url)); } + /** + * Regression test for issue #318 : the class path prefix must be matched on the + * canonical paths with a path-separator boundary, so that "/opt/app" will NOT + * match "/opt/application" (which substring matching would wrongly accept). + */ + @Test + void testIsResourcePathOnClassPath() { + // The resource is the class path entry itself + assertTrue(isResourcePathOnClassPath("/opt/app", "/opt/app")); + + // The resource is located under the class path + assertTrue(isResourcePathOnClassPath("/opt/app/classes/Foo.class", "/opt/app")); + + // '.' and '..' segments are resolved by the canonical paths + assertTrue(isResourcePathOnClassPath("/opt/app/./classes/Foo.class", "/opt/app")); + assertTrue(isResourcePathOnClassPath("/opt/app/classes/../classes/Foo.class", "/opt/app")); + + // A trailing separator on the class path does not break the boundary check + assertTrue(isResourcePathOnClassPath("/opt/app/classes/Foo.class", "/opt/app/")); + + // False prefix match : "/opt/app" must NOT match "/opt/application" + assertFalse(isResourcePathOnClassPath("/opt/application/Foo.class", "/opt/app")); + assertFalse(isResourcePathOnClassPath("/opt/app2/classes/Foo.class", "/opt/app")); + + // The class path is not a prefix of the resource path at all + assertFalse(isResourcePathOnClassPath("/classes/Foo.class", "/opt/app")); + assertFalse(isResourcePathOnClassPath("/opt/app/Foo.class", "/application")); + + // Blank inputs + assertFalse(isResourcePathOnClassPath(null, "/opt/app")); + assertFalse(isResourcePathOnClassPath("/opt/app/Foo.class", null)); + assertFalse(isResourcePathOnClassPath(StringUtils.EMPTY_STRING, StringUtils.EMPTY_STRING)); + assertFalse(isResourcePathOnClassPath(" ", " ")); + } + + @Test + void testIsResourcePathOnClassPathWithRealPaths(@TempDir File tempDir) throws IOException { + File appDir = new File(tempDir, "app"); + File applicationDir = new File(tempDir, "application"); + assertTrue(appDir.mkdir()); + assertTrue(applicationDir.mkdir()); + File resourceFile = new File(appDir, "Foo.class"); + + assertTrue(isResourcePathOnClassPath(resourceFile.getPath(), appDir.getPath())); + // A sibling directory whose name merely starts with the class path's last segment + assertFalse(isResourcePathOnClassPath(new File(applicationDir, "Foo.class").getPath(), appDir.getPath())); + } + + @Test + void testResolveArchiveDirectory() { + // The class file is under a class path directory (target/classes or a JAR) + File archiveDirectory = resolveArchiveDirectory(classFileURL); + assertNotNull(archiveDirectory); + assertTrue(archiveDirectory.exists()); + } + + @Test + void testResolveArchiveDirectoryOnNonClassPathResource(@TempDir File tempDir) throws IOException { + // A resource outside any class path entry resolves to null (no false prefix matches) + File resourceFile = new File(tempDir, "Foo.class"); + URL resourceURL = resourceFile.toURI().toURL(); + assertNull(resolveArchiveDirectory(resourceURL)); + } + @Test void testResolveQueryParameters() { String url = TEST_HTTP_WITH_QUERY_STRING; @@ -684,6 +751,14 @@ void testResolvePathFromFile() { assertEquals("/D:/test", resolvePathFromFile(url, false)); } + @Test + void testResolveWindowsFileURLOnClassPath() { + URL url = ofURL("file:/D:/app/classes/Foo.class"); + String resourcePath = resolvePathFromFile(url, true); + + assertTrue(isResourcePathOnClassPath(resourcePath, "D:/app/classes")); + } + @Test void testTruncateMatrixString() { assertEquals(TEST_HTTP_BASE, truncateMatrixString(TEST_HTTP_WITH_SP_MATRIX)); diff --git a/microsphere-java-core/src/test/java/io/microsphere/text/FormatUtilsTest.java b/microsphere-java-core/src/test/java/io/microsphere/text/FormatUtilsTest.java index 13c1a64f8..55e862257 100644 --- a/microsphere-java-core/src/test/java/io/microsphere/text/FormatUtilsTest.java +++ b/microsphere-java-core/src/test/java/io/microsphere/text/FormatUtilsTest.java @@ -51,4 +51,34 @@ void testFormat() { message = format("A,{},C,{},E", 1, 2, 3); assertEquals("A,1,C,2,E", message); } + + /** + * Regression test for issue #316 : an argument value containing the placeholder "{}" + * must not be corrupted by subsequent argument replacements. + */ + @Test + void testFormatWithPlaceholderInArgumentValue() { + String message = format("a={}, b={}", "x{}y", "z"); + assertEquals("a=x{}y, b=z", message); + + message = format("a={}, b={}", "{}", "z"); + assertEquals("a={}, b=z", message); + + message = format("{}-{}-{}", "1{}", "2{}", "3{}"); + assertEquals("1{}-2{}-3{}", message); + } + + @Test + void testFormatWithPlaceholderInArgumentValueAndMorePlaceholders() { + // The first argument's value contains the placeholder, and there are more + // placeholders than arguments : the remaining placeholders stay unchanged + String message = format("a={}, b={}, c={}", "x{}y", "z"); + assertEquals("a=x{}y, b=z, c={}", message); + } + + @Test + void testFormatWithPlaceholderInArgumentValueForCustomPlaceholder() { + String message = FormatUtils.formatWithPlaceholder("a=[p], b=[p]", "[p]", "x[p]y", "z"); + assertEquals("a=x[p]y, b=z", message); + } }