Add register listener methods annotated with @OnMain and @OnModThread; validate methods before mod loading.

This commit is contained in:
Overlord committed 2026-10-07 11:58:02 +02:00
1 parent 7ac442c4f6
commit b4d70c3d3a
15 files changed
+605 -13

No files matched your search

+24 -2
View File
@@ -21,7 +21,7 @@ pluginManagement {
dependencyResolutionManagement {
repositories {
maven("https://git.security-command.org/api/packages/overlord/maven")
mavenCentral()
mavenCentral() // the API depends on org.jetbrains:annotations
}
}
@@ -218,6 +218,28 @@ Listeners are matched by the event's exact class. Events that carry live game ob
removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove
it earlier.
The same listeners as annotated methods (`dev.overlord.zomboidforge.api.annotations`):
```java
@OnMain
void onTick(TickEvent event) { ... }
@OnModThread
void onGreeting(SomeEvent event) { ... }
```
- **The entry point's methods** are registered after its constructor and before `onLoad()`, so
they run before the listeners that `onLoad()` registers for the same event. Other objects
opt in with `this.events().register(object)`, which returns one `Subscription` for all of
their methods. Registering an object twice throws; the entry point is registered already.
- **A listener method** returns `void` and has one parameter: the event class, not an
interface or an abstract class. It may be static or private, and may be declared in a
superclass. An override listens only when it carries the annotation itself.
- **Order:** superclass methods first, the methods of one class by name. When two listeners of
one event need a specific order, register them with `onMain` instead.
- A method that breaks these rules stops the server with every problem in the log;
`register` throws an `IllegalArgumentException` instead.
## Commands
Admin commands work wherever Project Zomboid's own commands work: in the in-game chat
@@ -413,4 +435,4 @@ file system it can reach anything the server can, including other mods' data in
Main-thread tasks and event listener calls appear in JFR recordings as the event
`zomboidforge.ModTask`, with the mod's id and the kind of work (`task`, or `listener` and the
event class).
event class, followed by `#<method>` for a listener method).
@@ -1,5 +1,8 @@
package dev.overlord.zomboidforge.api;
import dev.overlord.zomboidforge.api.annotations.OnMain;
import dev.overlord.zomboidforge.api.annotations.OnModThread;
import org.jetbrains.annotations.ApiStatus;
import java.util.function.Consumer;
@@ -24,4 +27,33 @@ public interface Events
* @throws IllegalArgumentException when {@code type} is a {@link MainThreadEvent}
*/
<E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener);
/**
* Registers the methods of {@code listener} annotated with {@link OnMain} or
* {@link OnModThread}, as {@link #onMain} and {@link #onModThread} do. ZomboidForge registers
* the mod's entry point this way after its constructor and before {@link Mod#onLoad()}; other
* objects opt in through this method.
*
* <p>Each annotated method:
* <ul>
* <li>returns {@code void} and has one parameter, a class that implements {@link Event}
* and is neither abstract nor an interface, because listeners are matched by the
* event's exact class;</li>
* <li>carries one of the two annotations; {@link OnModThread} not for a
* {@link MainThreadEvent};</li>
* <li>may be static, private, and declared in a superclass of {@code listener}'s class.
* An instance method that a subclass overrides listens only when the override carries
* the annotation itself.</li>
* </ul>
*
* Superclass methods are registered before subclass methods, and the methods of one class
* sorted by name, then by parameter type.
*
* @return one subscription for every listener method of {@code listener}; cancelling it
* allows registering {@code listener} again
* @throws IllegalArgumentException listing every method that breaks a rule, when a class
* the methods name cannot be loaded, or when
* {@code listener} is registered already
*/
Subscription register(Object listener);
}
@@ -18,12 +18,17 @@ import java.nio.file.Path;
*
* <p>Lifecycle, in this order:
* <ol>
* <li>Listener methods: the methods annotated with
* {@link dev.overlord.zomboidforge.api.annotations.OnMain} or
* {@link dev.overlord.zomboidforge.api.annotations.OnModThread} are registered (see
* {@link Events#register(Object)}).</li>
* <li>{@link #onLoad()}: registration and setup. The server database, Lua, and the world do
* not exist yet.</li>
* <li>{@link #onServerStarted()}: the world is loaded and the network port is open.</li>
* <li>{@link #onStopping()}: the server stops; the world has not been saved yet.</li>
* </ol>
* An exception thrown by the constructor or {@link #onLoad()} stops the server.
* An exception thrown by the constructor or {@link #onLoad()}, or a listener method that breaks
* the rules, stops the server.
*/
public abstract class Mod
{
@@ -0,0 +1,19 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.Events;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Registers the method with {@link Events#onMain} for the event type of its only parameter. Read
* on the entry point before {@code onLoad()}, and on objects passed to
* {@link Events#register(Object)}, which lists the rules for the method.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnMain {}
@@ -0,0 +1,19 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.Events;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Registers the method with {@link Events#onModThread} for the event type of its only parameter.
* Read on the entry point before {@code onLoad()}, and on objects passed to
* {@link Events#register(Object)}, which lists the rules for the method.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnModThread {}
@@ -0,0 +1,10 @@
/**
* Annotations that stand for calls a mod can also make through the services of
* {@link dev.overlord.zomboidforge.api.Mod}.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.api.annotations;
import org.jetbrains.annotations.NotNullByDefault;
@@ -29,8 +29,8 @@ import java.util.Map;
import java.util.Objects;
/**
* Creates the class loaders and entry points of resolved mods, in order, and calls
* {@link Mod#onLoad()} on each. Stops at the first mod that fails.
* Creates the class loaders and entry points of resolved mods, in order, registers each entry
* point's listener methods, and calls {@link Mod#onLoad()}. Stops at the first mod that fails.
*/
public final class ModLoader
{
@@ -135,6 +135,10 @@ public final class ModLoader
throw new ModLoadException(ModLoader.sentence("'" + id + "': cannot create '" + descriptor.entrypoint() + "': " + e), e);
}
// Listener methods of the entry point; a mistake stops the server before onLoad() has side effects.
try { context.events().register(mod); }
catch (IllegalArgumentException e) { throw new ModLoadException("'" + id + "': " + e.getMessage(), e); }
try { mod.onLoad(); }
catch (Exception e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() threw " + e), e); }
catch (LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() failed with " + e), e); }
@@ -8,11 +8,16 @@ import dev.overlord.zomboidforge.api.Subscription;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
@@ -80,6 +85,9 @@ public final class EventBus
private final Executor modThread;
private final System.Logger logger;
/** Objects registered with {@link #register(Object)} whose subscription is active; guarded by itself. */
private final Set<Object> registered = Collections.newSetFromMap(new IdentityHashMap<>());
private ModEvents(String id, Executor modThread, System.Logger logger)
{
this.id = id;
@@ -99,15 +107,47 @@ public final class EventBus
return this.register(type, listener, this.modThread);
}
@Override
public Subscription register(Object listener)
{
Objects.requireNonNull(listener, "listener");
List<ListenerScanner.ListenerMethod> methods = ListenerScanner.scan(listener);
synchronized (this.registered)
{
if (!this.registered.add(listener)) throw new IllegalArgumentException("This '" + listener.getClass().getName() + "' is already registered.");
}
List<Listener> listeners = methods.stream()
.map(method -> this.add(method.type(), method.action(), method.main() ? null : this.modThread, method.name()))
.toList();
AtomicBoolean active = new AtomicBoolean(true);
return () -> {
if (!active.getAndSet(false)) return;
listeners.forEach(Listener::cancel);
synchronized (this.registered) { this.registered.remove(listener); }
};
}
private <E extends Event> Subscription register(Class<E> type, Consumer<? super E> listener, @Nullable Executor executor)
{
Objects.requireNonNull(type, "type");
Objects.requireNonNull(listener, "listener");
Listener registered = new Listener(this.id, type, event -> listener.accept(type.cast(event)), executor, this.logger);
EventBus.this.add(registered);
return this.add(type, event -> listener.accept(type.cast(event)), executor, null);
}
return registered;
/** @param method the name of the listener method, or {@code null} for a lambda */
private Listener add(Class<?> type, Consumer<Object> action, @Nullable Executor executor, @Nullable String method)
{
Listener listener = new Listener(this.id, type, method, action, executor, this.logger);
EventBus.this.add(listener);
return listener;
}
}
@@ -116,6 +156,7 @@ public final class EventBus
private final String mod;
private final Class<?> type;
private final String kind;
private final String name;
private final Consumer<Object> action;
private final @Nullable Executor executor;
private final System.Logger logger;
@@ -123,11 +164,13 @@ public final class EventBus
private volatile boolean active = true;
private Listener(String mod, Class<?> type, Consumer<Object> action, @Nullable Executor executor, System.Logger logger)
/** @param method the name of the listener method, or {@code null} for a lambda */
private Listener(String mod, Class<?> type, @Nullable String method, Consumer<Object> action, @Nullable Executor executor, System.Logger logger)
{
this.mod = mod;
this.type = type;
this.kind = "listener " + type.getSimpleName();
this.kind = "listener " + type.getSimpleName() + (method == null ? "" : "#" + method);
this.name = method == null ? "Listener for '" + type.getSimpleName() + "'" : "Listener '" + method + "' for '" + type.getSimpleName() + "'";
this.action = action;
this.executor = executor;
this.logger = logger;
@@ -161,12 +204,12 @@ public final class EventBus
if (failure == null) return;
int count = this.failures.incrementAndGet();
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure);
this.logger.log(System.Logger.Level.ERROR, this.name + " threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure);
if (count >= EventBus.MAX_FAILURES)
{
this.cancel();
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' removed after " + EventBus.MAX_FAILURES + " failures.");
this.logger.log(System.Logger.Level.ERROR, this.name + " removed after " + EventBus.MAX_FAILURES + " failures.");
}
}
}
@@ -0,0 +1,187 @@
package dev.overlord.zomboidforge.core.runtime;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.MainThreadEvent;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.annotations.OnMain;
import dev.overlord.zomboidforge.api.annotations.OnModThread;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* Finds the listener methods of an object for {@code Events.register(Object)}: methods annotated
* with {@link OnMain} or {@link OnModThread} in its class and superclasses, up to {@link Mod} or
* {@code Object}. Methods do not have to be public; they are called through method handles from
* a private lookup, as {@code RecordCodec} reads records.
*/
final class ListenerScanner
{
/**
* One listener method, bound to its object.
*
* @param type the event class, the method's parameter type
* @param main {@code true} for {@link OnMain}, {@code false} for {@link OnModThread}
* @param action calls the method; rethrows what the method throws, unchanged
*/
record ListenerMethod(Class<?> type, boolean main, String name, Consumer<Object> action) {}
private static final Comparator<Method> ORDER = Comparator
.comparing(Method::getName)
.thenComparing(method -> Arrays.toString(method.getParameterTypes()));
private ListenerScanner() {}
/**
* @return the listener methods of {@code target}, in registration order: superclass methods
* first, the methods of one class sorted by name, then by parameter type
* @throws IllegalArgumentException listing every problem, including classes whose methods
* cannot be read because a type they name is missing
*/
static List<ListenerMethod> scan(Object target)
{
Map<Class<?>, Method[]> hierarchy = ListenerScanner.declaredMethods(target.getClass());
List<Class<?>> types = List.copyOf(hierarchy.keySet());
List<ListenerMethod> found = new ArrayList<>();
List<String> problems = new ArrayList<>();
for (int i = 0; i < types.size(); i++)
{
List<Class<?>> subclasses = types.subList(i + 1, types.size());
for (Method method : hierarchy.get(types.get(i)))
{
boolean main = method.isAnnotationPresent(OnMain.class);
boolean modThread = method.isAnnotationPresent(OnModThread.class);
// javac copies method annotations to bridge methods.
if ((!main && !modThread) || method.isBridge() || method.isSynthetic()) continue;
if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue;
ListenerMethod listener = ListenerScanner.listener(target, method, main, modThread, problems);
if (listener != null) found.add(listener);
}
}
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
return List.copyOf(found);
}
/**
* The declared methods of {@code type} and its superclasses up to {@link Mod} or
* {@code Object}, superclass first, each sorted by {@link #ORDER}.
*
* @throws IllegalArgumentException when the methods of a class cannot be read
*/
private static Map<Class<?>, Method[]> declaredMethods(Class<?> type)
{
List<Class<?>> classes = new ArrayList<>();
for (Class<?> current = type; current != null && current != Object.class && current != Mod.class; current = current.getSuperclass()) classes.addFirst(current);
Map<Class<?>, Method[]> hierarchy = new LinkedHashMap<>();
List<String> problems = new ArrayList<>();
for (Class<?> current : classes)
{
// Reading the methods loads every parameter and return type they name.
try
{
Method[] methods = current.getDeclaredMethods();
Arrays.sort(methods, ListenerScanner.ORDER);
hierarchy.put(current, methods);
}
catch (LinkageError e) { problems.add("Cannot read the methods of '" + current.getName() + "': " + e + "."); }
}
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
return hierarchy;
}
/** Whether one of {@code subclasses} declares a method that overrides {@code method}. */
private static boolean isOverridden(Method method, List<Class<?>> subclasses, Map<Class<?>, Method[]> hierarchy)
{
int modifiers = method.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers)) return false;
Class<?> owner = method.getDeclaringClass();
boolean packagePrivate = !Modifier.isPublic(modifiers) && !Modifier.isProtected(modifiers);
for (Class<?> subclass : subclasses)
{
// A package-private method is only overridden in the same runtime package.
if (packagePrivate && (subclass.getClassLoader() != owner.getClassLoader() || !subclass.getPackageName().equals(owner.getPackageName()))) continue;
for (Method candidate : hierarchy.get(subclass))
{
if (Modifier.isStatic(candidate.getModifiers()) || Modifier.isPrivate(candidate.getModifiers())) continue;
if (candidate.getName().equals(method.getName()) && Arrays.equals(candidate.getParameterTypes(), method.getParameterTypes())) return true;
}
}
return false;
}
/** The listener for {@code method}, or {@code null} after adding its problems to {@code problems}. */
private static @Nullable ListenerMethod listener(Object target, Method method, boolean main, boolean modThread, List<String> problems)
{
String where = "'" + method.getDeclaringClass().getName() + "." + method.getName() + "'";
Class<?>[] parameters = method.getParameterTypes();
int before = problems.size();
if (main && modThread) problems.add(where + " carries both @OnMain and @OnModThread.");
if (method.getReturnType() != void.class) problems.add(where + " must return void.");
if (parameters.length != 1)
{
problems.add(where + " must have one parameter, the event; found " + parameters.length + ".");
return null;
}
Class<?> type = parameters[0];
if (!Event.class.isAssignableFrom(type))
problems.add(where + ": the parameter type '" + type.getName() + "' does not implement Event.");
else if (type.isInterface() || Modifier.isAbstract(type.getModifiers()))
problems.add(where + ": the parameter type '" + type.getName() + "' is " + (type.isInterface() ? "an interface" : "abstract") + "; listeners are matched by the event's exact class.");
else if (modThread && MainThreadEvent.class.isAssignableFrom(type))
problems.add(where + ": '" + type.getName() + "' is a main-thread event; annotate the method with @OnMain.");
if (problems.size() > before) return null;
try
{
MethodHandle handle = MethodHandles.privateLookupIn(method.getDeclaringClass(), MethodHandles.lookup()).unreflect(method);
if (!Modifier.isStatic(method.getModifiers())) handle = handle.bindTo(target);
MethodHandle invoker = handle.asType(MethodType.methodType(void.class, Object.class));
return new ListenerMethod(type, main, method.getName(), event -> {
try { invoker.invokeExact(event); }
catch (Throwable t) { throw ListenerScanner.<RuntimeException>rethrow(t); }
});
}
catch (IllegalAccessException e)
{
problems.add(where + " cannot be accessed: " + e.getMessage());
return null;
}
}
/** Throws {@code t} unchanged, also a checked exception; the listener's caller logs every {@code Throwable}. */
@SuppressWarnings("unchecked")
private static <T extends Throwable> RuntimeException rethrow(Throwable t) throws T { throw (T) t; }
}
@@ -19,7 +19,7 @@ final class ModTaskEvent extends jdk.jfr.Event
@Label("Mod")
String mod = "";
/** {@code task}, or {@code listener <event class>}. */
/** {@code task}, {@code listener <event class>}, or {@code listener <event class>#<method>} for a listener method. */
@Label("Kind")
String kind = "";
@@ -14,6 +14,8 @@ import org.junit.jupiter.api.io.TempDir;
import testmods.CommandMod;
import testmods.ContextMod;
import testmods.ErrorMod;
import testmods.InvalidListenerMod;
import testmods.ListenerMod;
import testmods.Recorder;
import testmods.ThreadMod;
@@ -329,6 +331,58 @@ class ForgeTest
assertEquals(Lifecycle.Phase.STOPPING, forge.phase());
}
@Test
void registersListenerMethodsOfTheEntryPointBeforeOnLoad() throws Exception
{
TestMods.folder(this.mods, "listener", TestMods.toml("listener", ListenerMod.class.getName(), ""), Map.of(
"testmods/ListenerMod", TestMods.classFile(ListenerMod.class)
));
Forge forge = this.load();
Object mod = forge.mods().getFirst().mod();
forge.started();
forge.tick();
assertEquals(List.of("method 1", "lambda 1"), ForgeTest.field(mod, "log"), "annotated listeners come before those of onLoad()");
IllegalArgumentException second = assertInstanceOf(IllegalArgumentException.class, ForgeTest.field(mod, "secondRegistration"));
assertTrue(second.getMessage().contains("testmods.ListenerMod"), second.getMessage());
}
@Test
void failsBeforeOnLoadWhenAListenerMethodBreaksTheRules() throws IOException
{
TestMods.folder(this.mods, "invalid", TestMods.toml("invalid", InvalidListenerMod.class.getName(), ForgeTest.USES_GAME), Map.of(
"testmods/InvalidListenerMod", TestMods.classFile(InvalidListenerMod.class)
));
ModLoadException e = assertThrows(ModLoadException.class, this::load);
assertEquals(1, e.problems().size());
ForgeTest.assertContainsAll(e.problems().getFirst(), "'invalid'", "testmods.InvalidListenerMod.onTick", "java.lang.String");
assertTrue(Recorder.EVENTS.isEmpty(), "onLoad() does not run");
}
@Test
void failsWhenTheEntryPointNamesAMissingClassInAMethod() throws IOException
{
// ModVerifier reports missing classes only in the game's packages, so only the scan finds this one.
TestMods.folder(this.mods, "missing", TestMods.toml("missing", "missing.MissingMod", ""), Map.of(
"missing/MissingMod", TestMods.type("missing/MissingMod", "dev/overlord/zomboidforge/api/Mod", null, "helper:(Lgone/Type;)V")
));
ModLoadException e = assertThrows(ModLoadException.class, this::load);
assertEquals(1, e.problems().size());
ForgeTest.assertContainsAll(e.problems().getFirst(), "'missing'", "missing.MissingMod", "NoClassDefFoundError", "gone/Type");
}
private static void assertContainsAll(String message, String... parts)
{
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
}
private static void await(BooleanSupplier condition) throws InterruptedException
{
long deadline = System.nanoTime() + 5_000_000_000L;
@@ -4,10 +4,13 @@ import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.Subscription;
import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.annotations.OnMain;
import dev.overlord.zomboidforge.api.annotations.OnModThread;
import dev.overlord.zomboidforge.core.RecordingLogger;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
@@ -21,6 +24,81 @@ class EventBusTest
{
private record Joined(String player) implements Event {}
private record Left(String player) implements Event {}
private abstract static class AbstractEvent implements Event {}
/** Listener methods in a superclass of {@link Listeners}. */
private static class BaseListeners
{
static final List<String> LOG = new ArrayList<>();
@OnMain
void base(Joined event) { BaseListeners.LOG.add("base " + event.player()); }
/** Overridden without the annotation, so it does not listen. */
@OnMain
void replaced(Joined event) { BaseListeners.LOG.add("base replaced"); }
/** Overridden with the annotation, so the override listens once. */
@OnMain
void kept(Joined event) { BaseListeners.LOG.add("base kept"); }
}
private static final class Listeners extends BaseListeners
{
@OnMain
static void a(Joined event) { BaseListeners.LOG.add("static a " + event.player()); }
@OnMain
private void b(Joined event) { BaseListeners.LOG.add("private b " + event.player()); }
@Override
void replaced(Joined event) { BaseListeners.LOG.add("override replaced"); }
@OnMain
@Override
void kept(Joined event) { BaseListeners.LOG.add("override kept"); }
@OnModThread
void left(Left event) { BaseListeners.LOG.add("left " + event.player()); }
@SuppressWarnings("unused")
void notAListener(Joined event) { BaseListeners.LOG.add("not a listener"); }
}
@SuppressWarnings("unused")
private static final class InvalidListeners
{
@OnMain
@OnModThread
void both(Joined event) {}
@OnMain
String returns(Joined event) { return ""; }
@OnMain
void two(Joined first, Joined second) {}
@OnMain
void notEvent(String text) {}
@OnMain
void anInterface(Event event) {}
@OnMain
void anAbstract(AbstractEvent event) {}
@OnModThread
void mainOnly(TickEvent event) {}
}
private static final class FailingListener
{
@OnMain
void fail(Joined event) throws IOException { throw new IOException("broken"); }
}
private final EventBus bus = new EventBus();
private final RecordingLogger logger = new RecordingLogger();
private final List<String> received = new ArrayList<>();
@@ -102,4 +180,74 @@ class EventBusTest
assertTrue(this.received.isEmpty());
}
@Test
void registersAnnotatedMethodsOfAnObjectAndItsSuperclasses()
{
Events a = this.bus.forMod("a", this.modThread, this.logger);
BaseListeners.LOG.clear();
a.register(new Listeners());
this.bus.post(new Joined("bob"));
this.bus.post(new Left("eve"));
assertEquals(List.of("base bob", "static a bob", "private b bob", "override kept"), BaseListeners.LOG, "superclass first, then by name; overridden methods once");
assertEquals(1, this.modTasks.size());
this.modTasks.getFirst().run();
assertEquals("left eve", BaseListeners.LOG.getLast());
}
@Test
void registersAnObjectOnceUntilItsSubscriptionIsCancelled()
{
Events a = this.bus.forMod("a", this.modThread, this.logger);
Listeners listeners = new Listeners();
Subscription subscription = a.register(listeners);
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.register(listeners));
assertTrue(e.getMessage().contains(Listeners.class.getName()), e.getMessage());
subscription.cancel();
assertFalse(this.bus.hasListeners(Joined.class));
assertFalse(this.bus.hasListeners(Left.class));
Subscription again = a.register(listeners);
subscription.cancel();
assertTrue(this.bus.hasListeners(Joined.class), "cancelling the old subscription again leaves the new one");
again.cancel();
assertFalse(this.bus.hasListeners(Joined.class));
}
@Test
void rejectsInvalidListenerMethodsWithEveryProblem()
{
Events a = this.bus.forMod("a", this.modThread, this.logger);
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.register(new InvalidListeners()));
// Every method, and the parameter types that break a rule.
for (String method : List.of("anAbstract", "anInterface", "both", "mainOnly", "notEvent", "returns", "two"))
EventBusTest.assertContainsAll(e.getMessage(), InvalidListeners.class.getName() + "." + method);
EventBusTest.assertContainsAll(e.getMessage(), AbstractEvent.class.getName(), Event.class.getName(), TickEvent.class.getName(), "java.lang.String");
assertFalse(this.bus.hasListeners(Joined.class), "nothing is registered");
}
@Test
void logsWhatListenerMethodsThrowWithTheirName()
{
this.bus.forMod("a", this.modThread, this.logger).register(new FailingListener());
this.bus.post(new Joined("bob"));
assertEquals(1, this.logger.messages.size());
EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "ERROR", "'fail'", "Joined", "java.io.IOException: broken");
}
private static void assertContainsAll(String message, String... parts)
{
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
}
}
@@ -0,0 +1,15 @@
package testmods;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.annotations.OnMain;
/** Entry point that tests package into a mod jar. Its listener method takes no event. */
public final class InvalidListenerMod extends Mod
{
@Override
public void onLoad() { Recorder.record("invalid:onLoad"); }
@OnMain
@SuppressWarnings("unused")
void onTick(String text) {}
}
@@ -0,0 +1,33 @@
package testmods;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.annotations.OnMain;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Entry point that tests package into a mod jar. Listens for ticks with an annotated method and
* with a listener from {@code onLoad()}, and tries to register itself again there.
*/
public final class ListenerMod extends Mod
{
public final List<String> log = new CopyOnWriteArrayList<>();
public volatile @Nullable RuntimeException secondRegistration;
@Override
public void onLoad()
{
this.events().onMain(TickEvent.class, event -> this.log.add("lambda " + event.tick()));
try { this.events().register(this); }
catch (RuntimeException e) { this.secondRegistration = e; }
}
@OnMain
void onTick(TickEvent event) { this.log.add("method " + event.tick()); }
}
@@ -61,6 +61,7 @@ class ZomboidForgeModPluginTest
dependencyResolutionManagement {
repositories {
maven { url = uri("%s") }
mavenCentral()
}
}
""".formatted(Path.of(ZomboidForgeModPluginTest.REPOSITORY).toUri()));