Skip to content
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
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;

Check warning on line 43 in microsphere-java-core/src/main/java/io/microsphere/event/AbstractEventDispatcher.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this unused import 'io.microsphere.util.ClassLoaderUtils.getDefaultClassLoader'.

See more on https://sonarcloud.io/project/issues?id=microsphere-projects_microsphere-java&issues=AaIyJYnUz9GJYIAwIy5O&open=AaIyJYnUz9GJYIAwIy5O&pullRequest=377
import static io.microsphere.util.ServiceLoaderUtils.loadServicesList;
import static java.util.Collections.sort;
import static java.util.Collections.unmodifiableList;
Expand Down Expand Up @@ -95,7 +96,9 @@

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<Class<? extends Event>, List<EventListener>> listenersCache = newConcurrentHashMap();

Expand Down Expand Up @@ -214,7 +217,7 @@
* @see ServiceLoader#load(Class)
*/
protected void loadEventListenerInstances() {
execute(() -> loadServicesList(EventListener.class, getDefaultClassLoader(), true)
execute(() -> loadServicesList(EventListener.class, getClassLoader(this.type), true)
.stream()
.sorted()
.forEach(this::addEventListener), e -> logger.trace(e.getMessage()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,18 @@ public boolean supports(@Nonnull URL url, @Nonnull List<String> subProtocols) {
@Nullable
public URLConnection create(@Nonnull URL url, @Nonnull List<String> 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<String> subProtocols) {
int index = selectFactoryIndex(url, subProtocols);
if (index < 0) {
return null;
}
return factories.get(index);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -291,18 +292,49 @@ 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<String> classPaths = getClassPaths();
File archiveDirectory = null;
for (String classPath : classPaths) {
if (resourcePath.contains(classPath)) {
if (isResourcePathOnClassPath(resourcePath, classPath)) {
Comment thread
Copilot marked this conversation as resolved.
Resolved
archiveDirectory = new File(classPath);
break;
}
}
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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -181,4 +188,86 @@
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<EchoEvent> failingListener = new EventListener<EchoEvent>() {

@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<Throwable> 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<EchoEvent> transientListener = new EventListener<EchoEvent>() {
@Override
public void onEvent(EchoEvent event) {

Check failure on line 241 in microsphere-java-core/src/test/java/io/microsphere/event/DirectEventDispatcherTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.

See more on https://sonarcloud.io/project/issues?id=microsphere-projects_microsphere-java&issues=AaIyJYpWz9GJYIAwIy5P&open=AaIyJYpWz9GJYIAwIy5P&pullRequest=377
}
};
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();
Comment on lines +259 to +260
}
} 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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -93,4 +95,55 @@
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;

Check warning on line 106 in microsphere-java-core/src/test/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactoryTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename "composite" which hides the field declared at line 46.

See more on https://sonarcloud.io/project/issues?id=microsphere-projects_microsphere-java&issues=AaItDXvVFb-UDZqIkpNS&open=AaItDXvVFb-UDZqIkpNS&pullRequest=377
URL url = new URL("ftp://...");
List<String> 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;

Check warning on line 121 in microsphere-java-core/src/test/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactoryTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename "composite" which hides the field declared at line 46.

See more on https://sonarcloud.io/project/issues?id=microsphere-projects_microsphere-java&issues=AaItDXvVFb-UDZqIkpNT&open=AaItDXvVFb-UDZqIkpNT&pullRequest=377
composite.add(new ConsoleSubProtocolURLConnectionFactory());

URL url = new URL("ftp://...");
List<String> subProtocols = emptyList();
URLConnection urlConnection = composite.create(url, subProtocols, NO_PROXY);
assertEquals(ConsoleURLConnection.class, urlConnection.getClass());
}

@Test
void testSelectFactory() throws MalformedURLException {
CompositeSubProtocolURLConnectionFactory composite = this.composite;

Check warning on line 132 in microsphere-java-core/src/test/java/io/microsphere/net/CompositeSubProtocolURLConnectionFactoryTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename "composite" which hides the field declared at line 46.

See more on https://sonarcloud.io/project/issues?id=microsphere-projects_microsphere-java&issues=AaItDXvVFb-UDZqIkpNU&open=AaItDXvVFb-UDZqIkpNU&pullRequest=377
URL url = new URL("ftp://...");
List<String> 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());
}
}
Loading
Loading