From f66c66fc57ad1ce6a49d3796f54a313eda99d7dc Mon Sep 17 00:00:00 2001 From: Progwml6 Date: Tue, 29 Dec 2015 17:19:49 -0500 Subject: [PATCH] update to latest pulsar, add its dep flightpath --- build.properties | 4 +- .../mantle/pulsar/config/IConfiguration.java | 6 +- .../mantle/pulsar/control/PulseManager.java | 203 ++++++++--------- .../mantle/pulsar/debug/EventSpy.java | 13 +- .../mantle/pulsar/flightpath/Airdrop.java | 15 ++ .../mantle/pulsar/flightpath/Flightpath.java | 101 +++++++++ .../pulsar/flightpath/IExceptionHandler.java | 25 +++ .../pulsar/flightpath/ISubscriberLocator.java | 18 ++ .../flightpath/lib/AnnotationLocator.java | 38 ++++ .../lib/BlackholeExceptionHandler.java | 25 +++ .../pulsar/internal/BusExceptionHandler.java | 34 +-- .../mantle/pulsar/internal/Configuration.java | 204 +++++++----------- .../mantle/pulsar/internal/CrashHandler.java | 37 ++-- .../pulsar/internal/logging/ILogger.java | 3 +- .../pulsar/internal/logging/JULLogger.java | 38 ++-- .../pulsar/internal/logging/Log4jLogger.java | 38 ++-- .../pulsar/internal/logging/LogManager.java | 32 +-- .../mantle/pulsar/pulse/PulseMeta.java | 49 ++--- 18 files changed, 498 insertions(+), 385 deletions(-) create mode 100755 src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java create mode 100755 src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java create mode 100755 src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java create mode 100755 src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java create mode 100755 src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java create mode 100755 src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java diff --git a/build.properties b/build.properties index 14fd54e..99a72fc 100644 --- a/build.properties +++ b/build.properties @@ -1,9 +1,9 @@ mod_version=0.6 minecraft_version=1.8.8 -forge_version=11.15.0.1641-1.8.8 +forge_version=11.15.0.1650-1.8.8 mappings=snapshot_20151212 CCLIB_version=1.1.2.133 ccc_version=1.0.5.36 NEI_version=1.0.5.104 -configurate_version=2.0 \ No newline at end of file +configurate_version=2.0 diff --git a/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java b/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java index 3cc4378..9f40530 100644 --- a/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java +++ b/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java @@ -2,13 +2,15 @@ package slimeknights.mantle.pulsar.config; import slimeknights.mantle.pulsar.pulse.PulseMeta; +import javax.annotation.ParametersAreNonnullByDefault; + /** * Interface for config handlers. * * @author Arkan */ -public interface IConfiguration -{ +@ParametersAreNonnullByDefault +public interface IConfiguration { /** * Perform any configuration loading required. diff --git a/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java b/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java index bbad14b..bace851 100644 --- a/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java +++ b/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java @@ -1,8 +1,15 @@ package slimeknights.mantle.pulsar.control; +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; - +import slimeknights.mantle.pulsar.flightpath.Flightpath; +import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; +import slimeknights.mantle.pulsar.flightpath.lib.AnnotationLocator; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.FMLModContainer; import net.minecraftforge.fml.common.Loader; @@ -10,19 +17,16 @@ import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import java.lang.reflect.Field; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map; - import slimeknights.mantle.pulsar.config.IConfiguration; import slimeknights.mantle.pulsar.internal.BusExceptionHandler; import slimeknights.mantle.pulsar.internal.Configuration; import slimeknights.mantle.pulsar.internal.CrashHandler; +import slimeknights.mantle.pulsar.pulse.PulseMeta; import slimeknights.mantle.pulsar.internal.logging.ILogger; import slimeknights.mantle.pulsar.internal.logging.LogManager; import slimeknights.mantle.pulsar.pulse.Pulse; -import slimeknights.mantle.pulsar.pulse.PulseMeta; + +import javax.annotation.ParametersAreNonnullByDefault; /** * Manager class for a given mods Pulses. @@ -36,23 +40,19 @@ import slimeknights.mantle.pulsar.pulse.PulseMeta; * @author Arkan */ @SuppressWarnings("unused") -public class PulseManager -{ +@ParametersAreNonnullByDefault +public class PulseManager { private ILogger log; - private final boolean useConfig; private final LinkedHashMap pulses = new LinkedHashMap(); + // Use the Google @Subscribe to avoid confusion/breaking changes. + private final Flightpath flightpath = new Flightpath(new AnnotationLocator(Subscribe.class)); private boolean blockNewRegistrations = false; - private boolean configLoaded = false; - private IConfiguration conf; - - private EventBus bus; - private String id; /** @@ -62,67 +62,67 @@ public class PulseManager * * @param configName The config file name. */ - public PulseManager(String configName) - { - this.init(); - this.useConfig = true; - this.conf = new Configuration(configName, this.log); + public PulseManager(String configName) { + init(); + useConfig = true; + conf = new Configuration(configName, log); } /** * Custom configuration-using constructor. * * Don't like JSON? Heathen. Lets you handle configuration, to whatever media you like - File, database, death star. - * Whatever really. See {@link IConfiguration}. + * Whatever really. See {@link slimeknights.mantle.pulsar.config.IConfiguration}. * * @param config Configuration handler. */ - public PulseManager(IConfiguration config) - { - this.init(); - this.useConfig = true; - this.conf = config; + public PulseManager(IConfiguration config) { + init(); + useConfig = true; + conf = config; } /** * Shared initialiser code between all the constructors. */ - private void init() - { + private void init() { String modId = Loader.instance().activeModContainer().getModId(); this.id = modId; - this.log = LogManager.getLogger("Pulsar-" + modId); + log = LogManager.getLogger("Pulsar-" + modId); + flightpath.setExceptionHandler(new BusExceptionHandler(modId)); FMLCommonHandler.instance().registerCrashCallable(new CrashHandler(modId, this)); - // Attach us to the mods FML bus and setup our own bus - this.attachToContainerEventBus(this); - bus = new EventBus(new BusExceptionHandler(modId, "<*pulsar*>")); + // Attach us to the mods FML bus + attachToContainerEventBus(this); + } + + /** + * Overrides Pulsars default behaviour when a pulse emits an exception. See Flightpath's documentation. + * + * @param handler The Flightpath-compatible exception handler to use. + */ + public void setPulseExceptionHandler(IExceptionHandler handler) { + flightpath.setExceptionHandler(handler); } /** * Register a new Pulse with the manager. * - * This CANNOT be done after preInit() has been invoked. + * This CANNOT be done after preinit has been invoked. * * @param pulse The Pulse to register. */ - public void registerPulse(Object pulse) - { - if (this.blockNewRegistrations) - { - throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: " - + pulse); - } - if (!this.configLoaded) - { - this.conf.load(); - this.configLoaded = true; + public void registerPulse(Object pulse) { + if (blockNewRegistrations) throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: " + + pulse); + if (!configLoaded) { + conf.load(); + configLoaded = true; } String id, description, deps; boolean forced, enabled, defaultEnabled, missingDeps = false; - try - { + try { Pulse p = pulse.getClass().getAnnotation(Pulse.class); id = p.id(); description = p.description(); @@ -130,26 +130,18 @@ public class PulseManager forced = p.forced(); enabled = p.defaultEnable(); defaultEnabled = p.defaultEnable(); - } - catch (NullPointerException ex) - { + } catch (NullPointerException ex) { throw new RuntimeException("Could not parse @Pulse annotation for Pulse: " + pulse); } // Work around Java not allowing default-null fields. - if (description.equals("")) - { - description = null; - } + if (description.equals("")) description = null; - if (!deps.equals("")) - { + if (!deps.equals("")) { String[] parsedDeps = deps.split(";"); - for (String s : parsedDeps) - { - if (!Loader.isModLoaded(s)) - { - this.log.info("Skipping Pulse " + id + "; missing dependency: " + s); + for (String s : parsedDeps) { + if (!Loader.isModLoaded(s)) { + log.info("Skipping Pulse " + id + "; missing dependency: " + s); missingDeps = true; enabled = false; break; @@ -158,47 +150,38 @@ public class PulseManager } PulseMeta meta = new PulseMeta(id, description, forced, enabled, defaultEnabled); - meta.setEnabled(!missingDeps && this.getEnabledFromConfig(meta)); + meta.setMissingDeps(missingDeps); + meta.setEnabled(getEnabledFromConfig(meta)); - if (meta.isEnabled()) - { - this.pulses.put(pulse, meta); - // Attach Pulse to its own internal event bus - meta.bus.register(pulse); + if (meta.isEnabled()) { + pulses.put(pulse, meta); + flightpath.register(pulse); } } /** - * Helper to attach a given object to the modcontainer event bus. + * Helper to attach a given object to the mod container event bus. * * @param obj Object to register. */ - private void attachToContainerEventBus(Object obj) - { - ModContainer cnt = Loader.instance().activeModContainer(); - this.log.debug("Attaching [" + obj + "] to event bus for container [" + cnt + "]"); - try - { - FMLModContainer mc = (FMLModContainer) cnt; + private void attachToContainerEventBus(Object obj) { + ModContainer cnt = Loader.instance().activeModContainer(); + log.debug("Attaching [" + obj + "] to event bus for container [" + cnt + "]"); + try { + FMLModContainer mc = (FMLModContainer)cnt; Field ebf = mc.getClass().getDeclaredField("eventBus"); boolean access = ebf.isAccessible(); ebf.setAccessible(true); - EventBus eb = (EventBus) ebf.get(mc); + EventBus eb = (EventBus)ebf.get(mc); ebf.setAccessible(access); eb.register(obj); - } - catch (NoSuchFieldException nsfe) - { + } catch (NoSuchFieldException nsfe) { throw new RuntimeException("Pulsar >> Incompatible FML mod container (missing eventBus field) - wrong Forge version?"); - } - catch (IllegalAccessException iae) - { + } catch (IllegalAccessException iae) { throw new RuntimeException("Pulsar >> Security Manager blocked access to eventBus on mod container. Cannot continue."); - } - catch (ClassCastException cce) - { + } catch (ClassCastException cce) { throw new RuntimeException("Pulsar >> Something in the mod container had the wrong type? " + cce.getMessage()); } } @@ -211,32 +194,36 @@ public class PulseManager * @param evt An event object. */ @Subscribe - public void propagateEvent(FMLEvent evt) { + public void propagateEvent(Object evt) { if (evt instanceof FMLPreInitializationEvent) preInit((FMLPreInitializationEvent) evt); // We use individual buses due to the EventBus class using a Set rather than a List, thus losing the ordering. // This trick is shamelessly borrowed from FML. - for (PulseMeta pulse : pulses.values()) { - pulse.bus.post(evt); - } + flightpath.post(evt); } - private boolean getEnabledFromConfig(PulseMeta meta) - { - if (meta.isForced() || !this.useConfig) - { - return true; // Forced or no config set. - } + private boolean getEnabledFromConfig(PulseMeta meta) { + if (meta.isForced() || !useConfig) return true; // Forced or no config set. - return this.conf.isModuleEnabled(meta); + return conf.isModuleEnabled(meta); } - public void preInit(FMLPreInitializationEvent evt) - { - if (!this.blockNewRegistrations) - { - this.conf.flush(); // First preInit call, so flush config + private void preInit(FMLPreInitializationEvent evt) { + if (!blockNewRegistrations) conf.flush(); // First preInit call, so flush config + blockNewRegistrations = true; + } + + private boolean hasRequiredPulses(Map.Entry entry) { + String deps = entry.getKey().getClass().getAnnotation(Pulse.class).pulsesRequired(); + if (!deps.equals("")) { + String[] parsedDeps = deps.split(";"); + for (String s : parsedDeps) { + if (!isPulseLoaded(s)) { + log.info("Skipping Pulse " + entry.getValue().getId() + "; missing pulse: " + s); + return false; + } + } } - this.blockNewRegistrations = true; + return true; } /** @@ -245,12 +232,9 @@ public class PulseManager * @param pulseId The ID to check. * @return Whether the ID was present. */ - public boolean isPulseLoaded(String pulseId) - { - for (Map.Entry entry : this.pulses.entrySet()) - { - if (entry.getValue().getId().equals(pulseId)) - { + public boolean isPulseLoaded(String pulseId) { + for(Map.Entry entry : pulses.entrySet()) { + if (entry.getValue().getId().equals(pulseId)) { return true; } } @@ -262,8 +246,7 @@ public class PulseManager } @Override - public String toString() - { - return "PulseManager[" + this.id + "]"; + public String toString() { + return "PulseManager[" + id + "]"; } } diff --git a/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java b/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java index 5458721..fbc53ea 100644 --- a/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java +++ b/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java @@ -1,28 +1,25 @@ package slimeknights.mantle.pulsar.debug; +import com.google.common.eventbus.Subscribe; import slimeknights.mantle.pulsar.internal.logging.ILogger; import slimeknights.mantle.pulsar.internal.logging.LogManager; import slimeknights.mantle.pulsar.pulse.Pulse; import net.minecraftforge.fml.common.Loader; -import com.google.common.eventbus.Subscribe; - /** * Debug Pulse to 'eavesdrop' on the PulseManager event bus traffic. * * @author Arkan */ @SuppressWarnings("unused") -@Pulse(id = "EventSpy", description = "we iz in ur buses, monitorin ur eventz", forced = true) -public class EventSpy -{ +@Pulse(id="EventSpy", description="we iz in ur buses, monitorin ur eventz", forced=true) +public class EventSpy { private final ILogger log = LogManager.getLogger("EventSpy/" + Loader.instance().activeModContainer().getModId()); @Subscribe - public void receive(Object evt) - { - this.log.info("Received event: " + evt); + public void receive(Object evt) { + log.info("Received event: " + evt); } } diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java new file mode 100755 index 0000000..9299344 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java @@ -0,0 +1,15 @@ +package slimeknights.mantle.pulsar.flightpath; + +import java.lang.annotation.*; + +/** + * Default annotation for Flightpath subscriptions. + * + * We don't use @Subscriber, as too many frameworks use it (which may lead to import hell) + * + * @author Arkan + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Airdrop {} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java new file mode 100755 index 0000000..909c39c --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java @@ -0,0 +1,101 @@ +package slimeknights.mantle.pulsar.flightpath; + +import slimeknights.mantle.pulsar.flightpath.lib.AnnotationLocator; +import slimeknights.mantle.pulsar.flightpath.lib.BlackholeExceptionHandler; + +import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * Flightpath - an ordered event bus implementation. + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +@SuppressWarnings({"unused","unchecked"}) +public class Flightpath { + + private final ISubscriberLocator locator; + // Note we *MUST* use a linked map, otherwise order is lost. + private final LinkedHashMap>> subscribers = new LinkedHashMap>>(); + // Anything that manipulates state *MUST* acquire this lock. It prevents awkward issues when iterating. + private final Object lock = new Object(); + + private IExceptionHandler exceptionHandler = new BlackholeExceptionHandler(); + + /** + * Generates a plain old Flightpath, using the default @Airdrop annotation. + */ + public Flightpath() { + this.locator = new AnnotationLocator(Airdrop.class); + } + + /** + * Generates a Flightpath using a different locator implementation. + * + * Pass a custom constructed instance of AnnotationLocator to use alternative annotations. + * + * @param locator The locator to be applied to new objects. + */ + public Flightpath(ISubscriberLocator locator) { + this.locator = locator; + } + + /** + * Used to change exception handling behaviour. + * + * @param handler The handler to use. + */ + public void setExceptionHandler(IExceptionHandler handler) { + synchronized (lock) { + this.exceptionHandler = handler; + } + } + + /** + * Registers a given object onto the bus. + * + * @param obj Object to attach to the bus. + */ + public void register(Object obj) { + synchronized (lock) { + if (subscribers.containsKey(obj)) return; // Nothing to do. + subscribers.put(obj, locator.findSubscribers(obj)); + } + } + + /** + * Posts the given event on the bus. + * + * By default this blackholes exceptions. If you need different behaviour, see setExceptionHandler. + * + * @param evt The event to post. + */ + public void post(Object evt) { + synchronized (lock) { + for (Map.Entry>> ent : subscribers.entrySet()) { + for (Map.Entry> objEnt: ent.getValue().entrySet()) { + if (!objEnt.getKey().isAssignableFrom(evt.getClass())) continue; + Set ms = objEnt.getValue(); + for (Method m : ms) { + try { + boolean access = m.isAccessible(); + m.setAccessible(true); + m.invoke(ent.getKey(), evt); + m.setAccessible(access); + } catch (Exception ex) { + exceptionHandler.handle(ex); + } + } + } + } + exceptionHandler.flush(); + } + } + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java new file mode 100755 index 0000000..782a05a --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java @@ -0,0 +1,25 @@ +package slimeknights.mantle.pulsar.flightpath; + +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * General interface for an exception handler. + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +public interface IExceptionHandler { + + /** + * Handle a given exception. + * + * @param ex The exception (duh) + */ + void handle(Exception ex); + + /** + * Called after all methods have been invoked for cleanup or coalescing. + */ + void flush(); + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java new file mode 100755 index 0000000..6129148 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java @@ -0,0 +1,18 @@ +package slimeknights.mantle.pulsar.flightpath; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.Set; + +/** + * Interface for defining custom subscriber scanners. + */ +@ParametersAreNonnullByDefault +public interface ISubscriberLocator { + + @Nonnull + Map> findSubscribers(Object obj); + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java new file mode 100755 index 0000000..19963a3 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java @@ -0,0 +1,38 @@ +package slimeknights.mantle.pulsar.flightpath.lib; + +import slimeknights.mantle.pulsar.flightpath.ISubscriberLocator; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.*; + +/** + * Default implementation of ISubscriberLocator + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +public class AnnotationLocator implements ISubscriberLocator { + + private final Class annotation; + + public AnnotationLocator(Class annotation) { + this.annotation = annotation; + } + + @Override + public @Nonnull Map> findSubscribers(Object obj) { + Map> methods = new HashMap>(); + for (Method m : obj.getClass().getMethods()) { + if (m.isAnnotationPresent(annotation) && m.getParameterCount() == 1) { + Class param = m.getParameterTypes()[0]; + if (!methods.containsKey(param)) methods.put(param, new HashSet()); + methods.get(param).add(m); + } + } + return methods; + } + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java new file mode 100755 index 0000000..60f5f1b --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java @@ -0,0 +1,25 @@ +package slimeknights.mantle.pulsar.flightpath.lib; + +import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; + +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Default exception handler when Flightpath has been asked to ignore errors. + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +public class BlackholeExceptionHandler implements IExceptionHandler { + + @Override + public void handle(Exception ex) { + // NO-OP + } + + @Override + public void flush() { + // NO-OP + } + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java index bca7f53..00c66bc 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java @@ -1,28 +1,36 @@ package slimeknights.mantle.pulsar.internal; -import com.google.common.eventbus.SubscriberExceptionContext; -import com.google.common.eventbus.SubscriberExceptionHandler; -import net.minecraftforge.fml.common.FMLCommonHandler; +import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; +import slimeknights.mantle.pulsar.internal.logging.ILogger; +import slimeknights.mantle.pulsar.internal.logging.LogManager; + +import javax.annotation.ParametersAreNonnullByDefault; /** - * Needed because Google EventBus is a derp and by default swallows exceptions (dafuq guys?) + * Custom exception catcher that logs events. */ -public final class BusExceptionHandler implements SubscriberExceptionHandler { - private final String id, pulseId; +@ParametersAreNonnullByDefault +public final class BusExceptionHandler implements IExceptionHandler { + + private final String id; + private final ILogger logger; /** * @param id Mod ID to include in exception raises. */ - public BusExceptionHandler(String id, String pulseId) { + public BusExceptionHandler(String id) { this.id = id; - this.pulseId = pulseId; + this.logger = LogManager.getLogger(id + "-Pulsar-Flightpath"); } @Override - public void handleException(Throwable exception, SubscriberExceptionContext ctx) { - FMLCommonHandler.instance().raiseException(exception, "Pulsar/" + id + "/" + pulseId - + " >> Exception uncaught in [" + ctx.getSubscriber().getClass().getName() + ":" - + ctx.getSubscriberMethod().getName() + "] for event [" + ctx.getEvent().getClass().getSimpleName() - + "]", true); + public void handle(Exception ex) { + this.logger.severe("Exception caught from a pulse on flightpath for mod ID " + id + ": " + ex); } + + @Override + public void flush() { + // NO-OP + } + } diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java b/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java index dca1972..3b56e94 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java @@ -1,39 +1,32 @@ package slimeknights.mantle.pulsar.internal; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.util.HashMap; -import java.util.Map; - -import slimeknights.mantle.pulsar.config.IConfiguration; -import slimeknights.mantle.pulsar.internal.logging.ILogger; -import slimeknights.mantle.pulsar.pulse.PulseMeta; -import net.minecraftforge.fml.common.Loader; +import java.io.*; +import java.util.*; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; +import net.minecraftforge.fml.common.Loader; +import slimeknights.mantle.pulsar.config.IConfiguration; +import slimeknights.mantle.pulsar.internal.logging.ILogger; +import slimeknights.mantle.pulsar.pulse.PulseMeta; + +import javax.annotation.ParametersAreNonnullByDefault; /** * Default Gson Configuration helper. * * @author Arkan */ -public class Configuration implements IConfiguration -{ +@ParametersAreNonnullByDefault +public class Configuration implements IConfiguration { private static final int CONFIG_LEVEL = 1; private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private final String confPath; - private final ILogger logger; private Map modules; @@ -46,151 +39,111 @@ public class Configuration implements IConfiguration * @param confName The config file name (without path or .json suffix) * @param logger The logger to send debug info to. */ - public Configuration(String confName, ILogger logger) - { + public Configuration(String confName, ILogger logger) { this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".json"; this.logger = logger; } @Override - public void load() - { - this.getModulesFromJson(); + public void load() { + getModulesFromJson(); } @Override - public boolean isModuleEnabled(PulseMeta meta) - { - ConfigEntry entry = this.modules.get(meta.getId()); - if (entry == null) - { - this.modules.put(meta.getId(), new ConfigEntry(meta.isDefaultEnabled(), meta.getDescription())); + public boolean isModuleEnabled(PulseMeta meta) { + ConfigEntry entry = modules.get(meta.getId()); + if (entry == null) { + modules.put(meta.getId(), new ConfigEntry(meta.isDefaultEnabled(), meta.getDescription())); return meta.isEnabled(); - } - else - { + } else { return entry.getEnabled(); } } @Override - public void flush() - { - this.writeModulesToJson(); + public void flush() { + writeModulesToJson(); } - private void getModulesFromJson() - { + private void getModulesFromJson() { // Step 1: Does the file exist? - File f = new File(this.confPath); - if (!f.exists()) - { - this.logger.info("Couldn't find config file; will generate a new one later."); - this.modules = new HashMap(); + File f = new File(confPath); + if (!f.exists()) { + logger.info("Couldn't find config file; will generate a new one later."); + modules = new HashMap(); return; } // Step 2: File exists. Let's make sure it's usable. - if (!(f.canRead() && f.canWrite())) - { - throw new FileNotReadWritableException("Could not read/write Pulsar config: " + this.confPath); + if (!(f.canRead() && f.canWrite())) { + throw new FileNotReadWritableException("Could not read/write Pulsar config: " + confPath); } // Step 3: Good enough. Read it. - try - { - try - { - this.modules = this.parseV1Config(f); + try { + try { + modules = parseV1Config(f); + } catch (Exception ex) { + logger.warn("Failed to parse " + f.getName() + " using the v1 parser; trying the v0 parser."); + Map conf = parseV0Config(f); + logger.info("Found valid v0 configuration. Upgrading it."); + modules = conf; + writeModulesToJson(); + logger.info("Upgrade complete! Config is now in v1 format."); } - catch (Exception ex) - { - this.logger.warn("Failed to parse " + f.getName() + " using the v1 parser; trying the v0 parser."); - Map conf = this.parseV0Config(f); - this.logger.info("Found valid v0 configuration. Upgrading it."); - this.modules = conf; - this.writeModulesToJson(); - this.logger.info("Upgrade complete! Config is now in v1 format."); - } - } - catch (Exception ex) - { - this.logger.warn("Invalid config file. Discarding."); + } catch (Exception ex) { + logger.warn("Invalid config file. Discarding."); ex.printStackTrace(); - this.modules = new HashMap(); + modules = new HashMap(); } } - private Map parseV0Config(File f) throws Exception - { - try - { + private Map parseV0Config(File f) throws Exception { + try { JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f))); - Map m = gson.fromJson(reader, new TypeToken>() - { - }.getType()); // NASTY! - if (m == null) - { + Map m = gson.fromJson(reader, new TypeToken>(){}.getType()); // NASTY! + if (m == null) { throw new NullPointerException("Gson returned null."); } Map out = new HashMap(); - for (Map.Entry e : m.entrySet()) - { + for (Map.Entry e : m.entrySet()) { out.put(e.getKey(), new ConfigEntry(e.getValue())); } return out; - } - catch (FileNotFoundException fnfe) - { + } catch (FileNotFoundException fnfe) { throw new RuntimeException("This shouldn't be possible... " + fnfe); } } - private Map parseV1Config(File f) throws Exception - { - try - { + private Map parseV1Config(File f) throws Exception { + try { JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f))); GsonConfig c = gson.fromJson(reader, GsonConfig.class); - if (c.getConfigVersion() > 1) - { - throw new RuntimeException("Pulsar config is from a newer version! Remove it! " + f.getAbsolutePath()); - } - if (c.getModules() == null) - { - throw new IllegalArgumentException("Not a valid GsonConfig. Try v0 parsing."); - } + if (c.getConfigVersion() > 1) throw new RuntimeException("Pulsar config is from a newer version! Remove it! " + f.getAbsolutePath()); + if (c.getModules() == null) throw new IllegalArgumentException("Not a valid GsonConfig. Try v0 parsing."); return c.getModules(); - } - catch (FileNotFoundException fnfe) - { + } catch (FileNotFoundException fnfe) { throw new RuntimeException("This shouldn't be possible... " + fnfe); } } - private void writeModulesToJson() - { - try - { - JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(new File(this.confPath)))); + private void writeModulesToJson() { + try { + JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(new File(confPath)))); writer.setIndent(" "); - GsonConfig out = new GsonConfig(CONFIG_LEVEL, this.modules); + GsonConfig out = new GsonConfig(CONFIG_LEVEL, modules); gson.toJson(out, GsonConfig.class, writer); writer.close(); - } - catch (Exception ex) - { - this.logger.warn("Could not write config? " + this.confPath); + } catch (Exception ex) { + logger.warn("Could not write config? " + confPath); } } /** * Internal exception for an unreadable/unwritable config. */ - private static class FileNotReadWritableException extends RuntimeException - { - public FileNotReadWritableException(String message) - { + private static class FileNotReadWritableException extends RuntimeException { + public FileNotReadWritableException(String message) { super(message); } } @@ -198,54 +151,53 @@ public class Configuration implements IConfiguration /** * Internal data holder, for use in the map and JSON. */ - private static class ConfigEntry - { + private static class ConfigEntry { private Boolean enabled; - private String description = null; - public ConfigEntry(Boolean enabled) - { + public ConfigEntry(Boolean enabled) { this.enabled = enabled; } - public ConfigEntry(Boolean enabled, String description) - { + public ConfigEntry(Boolean enabled, String description) { this(enabled); this.description = description; } - public Boolean getEnabled() - { - return this.enabled; + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public String getDescription() { + return description; } } /** * Internal representation of a version 1+ config file. */ - private static class GsonConfig - { + private static class GsonConfig { private int CONFIG_VERSION = 0; private Map modules; - public GsonConfig(int version, Map modules) - { + public GsonConfig(int version, Map modules) { this.CONFIG_VERSION = version; this.modules = modules; } - public int getConfigVersion() - { - return this.CONFIG_VERSION; + public int getConfigVersion() { + return CONFIG_VERSION; } - public Map getModules() - { - return this.modules; + public Map getModules() { + return modules; } } diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java b/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java index 81f011b..c45b4e9 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java @@ -1,59 +1,46 @@ package slimeknights.mantle.pulsar.internal; +import net.minecraftforge.fml.common.ICrashCallable; import slimeknights.mantle.pulsar.control.PulseManager; import slimeknights.mantle.pulsar.pulse.PulseMeta; -import net.minecraftforge.fml.common.ICrashCallable; /** * FML crash callable for Pulse Managers; dumps a list of loaded pulses to the error log. * * @author Arkan */ -public class CrashHandler implements ICrashCallable -{ +public class CrashHandler implements ICrashCallable { private String id; - private PulseManager manager; - public CrashHandler(String modId, PulseManager manager) - { + public CrashHandler(String modId, PulseManager manager) { this.id = "Pulsar/" + modId + " loaded Pulses"; this.manager = manager; } @Override - public String getLabel() - { - return this.id; + public String getLabel() { + return id; } @Override - public String call() throws Exception - { + public String call() throws Exception { String out = "\n"; - for (PulseMeta meta : this.manager.getAllPulseMetadata()) - { + for (PulseMeta meta : manager.getAllPulseMetadata()) { String state = getStateFromMeta(meta); out += "\t\t- " + meta.getId() + " (" + state + ")\n"; // Yes, yes, manual indenting, I know... } return out; } - private static String getStateFromMeta(PulseMeta meta) - { - if (meta.isForced()) - { + private static String getStateFromMeta(PulseMeta meta) { + if (meta.isForced()) { return "Enabled/Forced"; - } - else - { - if (meta.isEnabled()) - { + } else { + if (meta.isEnabled()) { return "Enabled/Not Forced"; - } - else - { + } else { return "Disabled/Not Forced"; } } diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/logging/ILogger.java b/src/main/java/slimeknights/mantle/pulsar/internal/logging/ILogger.java index 7845712..ef47f51 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/logging/ILogger.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/logging/ILogger.java @@ -6,8 +6,7 @@ package slimeknights.mantle.pulsar.internal.logging; * @author Arkan */ @SuppressWarnings("unused") -public interface ILogger -{ +public interface ILogger { public void fatal(String msg); diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/logging/JULLogger.java b/src/main/java/slimeknights/mantle/pulsar/internal/logging/JULLogger.java index 991b227..1f3497e 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/logging/JULLogger.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/logging/JULLogger.java @@ -7,50 +7,42 @@ import java.util.logging.Logger; * * @author Arkan */ -public class JULLogger implements ILogger -{ +public class JULLogger implements ILogger { private final Logger log; - public JULLogger(String name) - { - this.log = Logger.getLogger(name); + public JULLogger(String name) { + log = Logger.getLogger(name); } @Override - public void fatal(String msg) - { - this.log.severe(msg); // JUL doesn't -have- fatal... + public void fatal(String msg) { + log.severe(msg); // JUL doesn't -have- fatal... } @Override - public void severe(String msg) - { - this.log.severe(msg); + public void severe(String msg) { + log.severe(msg); } @Override - public void warn(String msg) - { - this.log.warning(msg); + public void warn(String msg) { + log.warning(msg); } @Override - public void info(String msg) - { - this.log.info(msg); + public void info(String msg) { + log.info(msg); } @Override - public void debug(String msg) - { - this.log.fine(msg); // Good enough. + public void debug(String msg) { + log.fine(msg); // Good enough. } @Override - public void trace(String msg) - { - this.log.finest(msg); // Closest we'll get. + public void trace(String msg) { + log.finest(msg); // Closest we'll get. } } diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/logging/Log4jLogger.java b/src/main/java/slimeknights/mantle/pulsar/internal/logging/Log4jLogger.java index 0ee21ec..d061bf7 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/logging/Log4jLogger.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/logging/Log4jLogger.java @@ -7,50 +7,42 @@ import org.apache.logging.log4j.Logger; * * @author Arkan */ -public class Log4jLogger implements ILogger -{ +public class Log4jLogger implements ILogger { private final Logger log; - public Log4jLogger(String name) - { - this.log = org.apache.logging.log4j.LogManager.getLogger(name); + public Log4jLogger(String name) { + log = org.apache.logging.log4j.LogManager.getLogger(name); } @Override - public void fatal(String msg) - { - this.log.fatal(msg); + public void fatal(String msg) { + log.fatal(msg); } @Override - public void severe(String msg) - { - this.log.error(msg); + public void severe(String msg) { + log.error(msg); } @Override - public void warn(String msg) - { - this.log.warn(msg); + public void warn(String msg) { + log.warn(msg); } @Override - public void info(String msg) - { - this.log.info(msg); + public void info(String msg) { + log.info(msg); } @Override - public void debug(String msg) - { - this.log.debug(msg); + public void debug(String msg) { + log.debug(msg); } @Override - public void trace(String msg) - { - this.log.trace(msg); + public void trace(String msg) { + log.trace(msg); } } diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/logging/LogManager.java b/src/main/java/slimeknights/mantle/pulsar/internal/logging/LogManager.java index db4892d..47369bb 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/logging/LogManager.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/logging/LogManager.java @@ -5,12 +5,9 @@ package slimeknights.mantle.pulsar.internal.logging; * * @author Arkan */ -public class LogManager -{ +public class LogManager { - private LogManager() - { - } // Singleton. + private LogManager() {} // Singleton. private static final boolean useLog4j2; @@ -19,33 +16,22 @@ public class LogManager * * If it's present, we can assume we should be using the damn thing. */ - static - { + static { boolean l4j = false; - try - { + try { Class cl = Class.forName("org.apache.logging.log4j.LogManager"); - if (cl == null) - { - throw new ClassNotFoundException("This should never happen..."); - } + if (cl == null) throw new ClassNotFoundException("This should never happen..."); l4j = true; - } - catch (ClassNotFoundException cnfe) - { + } catch (ClassNotFoundException cnfe) { // Ignore } useLog4j2 = l4j; } - public static ILogger getLogger(String name) - { - if (useLog4j2) - { + public static ILogger getLogger(String name) { + if (useLog4j2) { return new Log4jLogger(name); - } - else - { + } else { return new JULLogger(name); } } diff --git a/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java b/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java index 50e21ff..81fc979 100644 --- a/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java +++ b/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java @@ -1,60 +1,53 @@ package slimeknights.mantle.pulsar.pulse; -import com.google.common.eventbus.EventBus; -import net.minecraftforge.fml.common.Loader; - -import slimeknights.mantle.pulsar.internal.BusExceptionHandler; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; /** * Metadata wrapper for parsed @Pulse metadata. * * @author Arkan */ -public class PulseMeta -{ +@ParametersAreNonnullByDefault +public class PulseMeta { private String id, description; - private boolean forced, enabled, defaultEnabled; - public final EventBus bus; + private boolean missingDeps = false; - public PulseMeta(String id, String description, boolean forced, boolean enabled, boolean defaultEnabled) - { + public PulseMeta(String id, @Nullable String description, boolean forced, boolean enabled, boolean defaultEnabled) { this.id = id; this.description = description; this.forced = forced; this.enabled = enabled; this.defaultEnabled = defaultEnabled; - this.bus = new EventBus(new BusExceptionHandler(Loader.instance().activeModContainer().getModId(), id)); } - public String getId() - { - return this.id; + public String getId() { + return id; } - public String getDescription() - { - return this.description; + public String getDescription() { + return description; } - public boolean isForced() - { - return this.forced; + public boolean isForced() { + return !missingDeps && forced; } - public boolean isEnabled() - { - return this.enabled; + public boolean isEnabled() { + return !missingDeps && enabled; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; } - public boolean isDefaultEnabled() - { - return this.defaultEnabled; + public void setMissingDeps(boolean missing) { + missingDeps = missing; + } + + public boolean isDefaultEnabled() { + return defaultEnabled; } }