update pulsar again, add in forge config class as well for tcon to use

This commit is contained in:
progwml6 committed 2014-07-02 20:15:58 -04:00
1 parent 504b639583
commit 0be4c44490
13 files changed
+536 -117

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
package mantle.pulsar.config;
import cpw.mods.fml.common.Loader;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.pulse.PulseMeta;
import net.minecraftforge.common.config.Configuration;
import java.io.*;
import java.util.Map;
public class ForgeCFG implements IConfiguration{
private static Configuration config;
private final String confPath;
private final String description;
private Map<String, Boolean> modules;
/**
* Creates a new Configuration object.
*
* Do NOT make this the same as the overall mod configuration; it will clobber it!
*
* @param confName The config file name (without path or .cfg suffix)
* @param description The description for the group that the config entries will be placed in.
*/
public ForgeCFG(String confName, String description) {
this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".cfg";
this.description = description;
}
@Override
public void load() {
config = new Configuration(new File(confPath));
}
@Override
public boolean isModuleEnabled(PulseMeta meta) {
Boolean enabled = modules.get(meta.getId());
if (enabled == null) {
modules.put(meta.getId(), meta.isEnabled());
enabled = meta.isEnabled();
config.get(description, meta.getId(), meta.isEnabled(), meta.getDescription()).set(meta.isEnabled());
}
return enabled;
}
@Override
public void flush() {
if(config.hasChanged())
config.save();
}
}
@@ -0,0 +1,30 @@
package mantle.pulsar.config;
import mantle.pulsar.pulse.PulseMeta;
/**
* Interface for config handlers.
*
* @author Arkan <[email protected]>
*/
public interface IConfiguration {
/**
* Perform any configuration loading required.
*/
public void load();
/**
* Gets whether the given module is enabled in the config.
*
* @param meta The pulse metadata.
* @return Whether the module is enabled.
*/
public boolean isModuleEnabled(PulseMeta meta);
/**
* Flush configuration to disk/database/whatever.
*/
public void flush();
}
+126 -40
View File
@@ -1,19 +1,20 @@
package mantle.pulsar.control;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Method;
import java.util.*;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import mantle.pulsar.config.IConfiguration;
import mantle.pulsar.internal.Configuration;
import mantle.pulsar.internal.PulseMeta;
import mantle.pulsar.pulse.PulseMeta;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.internal.logging.LogManager;
import mantle.pulsar.pulse.Handler;
import mantle.pulsar.pulse.IPulse;
import mantle.pulsar.pulse.Pulse;
import mantle.pulsar.pulse.PulseProxy;
@@ -25,16 +26,17 @@ import mantle.pulsar.pulse.PulseProxy;
*
* @author Arkan <[email protected]>
*/
@SuppressWarnings({"unused", "deprecated"})
public class PulseManager {
private final Logger log;
private final ILogger log;
private final boolean useConfig;
private final String configName;
private final HashMap<IPulse, PulseMeta> pulses = new HashMap<IPulse, PulseMeta>();
private final HashMap<Object, PulseMeta> pulses = new HashMap<Object, PulseMeta>();
private boolean blockNewRegistrations = false;
private Configuration conf = null;
private boolean configLoaded = false;
private IConfiguration conf;
/**
* Configuration-less constructor.
@@ -47,7 +49,7 @@ public class PulseManager {
public PulseManager(String modId) {
log = LogManager.getLogger("PulseManager-" + modId);
useConfig = false;
configName = null;
conf = null;
}
/**
@@ -61,7 +63,22 @@ public class PulseManager {
public PulseManager(String modId, String configName) {
log = LogManager.getLogger("PulseManager-" + modId);
useConfig = true;
this.configName = configName;
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 mantle.pulsar.config.IConfiguration}.
*
* @param modId The parents ModID.
* @param config Configuration handler.
*/
public PulseManager(String modId, IConfiguration config) {
log = LogManager.getLogger("PulseManager-" + modId);
useConfig = true;
conf = config;
}
/**
@@ -71,24 +88,43 @@ public class PulseManager {
*
* @param pulse The Pulse to register.
*/
public void registerPulse(IPulse pulse) {
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;
String id, description, deps;
boolean forced, enabled;
try {
Pulse p = pulse.getClass().getAnnotation(Pulse.class);
id = p.id();
description = p.description();
deps = p.modsRequired();
forced = p.forced();
enabled = p.defaultEnable();
description = p.description();
} catch (NullPointerException ex) {
throw new RuntimeException("Could not parse @Pulse annotation for Pulse: " + pulse);
}
PulseMeta meta = new PulseMeta(id, forced, enabled, description);
// Work around Java not allowing default-null fields.
if (description.equals("")) description = null;
if (!deps.equals("")) {
String[] parsedDeps = deps.split(";");
for (String s : parsedDeps) {
if (!Loader.isModLoaded(s)) {
log.info("Skipping Pulse " + id + "; missing dependency: " + s);
enabled = false;
break;
}
}
}
PulseMeta meta = new PulseMeta(id, description, forced, enabled);
meta.setEnabled(getEnabledFromConfig(meta));
if (meta.isEnabled()) {
@@ -100,29 +136,24 @@ public class PulseManager {
private boolean getEnabledFromConfig(PulseMeta meta) {
if (meta.isForced() || !useConfig) return true; // Forced or no config set.
if (conf == null) {
conf = new Configuration(configName, log);
}
return conf.isModuleEnabled(meta.getId(), meta.isEnabled(), meta.getDescription());
return conf.isModuleEnabled(meta);
}
private void parseAndAddProxies(IPulse pulse) {
/**
* @deprecated FML handles proxies now.
*
* @param pulse Pulse to parse for proxy annotations.
*/
@Deprecated
private void parseAndAddProxies(Object pulse) {
try {
for (Field f : pulse.getClass().getDeclaredFields()) {
log.debug("Parsing field: " + f);
PulseProxy p = f.getAnnotation(PulseProxy.class);
if (p != null) {
boolean accessible = f.isAccessible();
f.setAccessible(true);
switch (FMLCommonHandler.instance().getSide()) {
case CLIENT:
f.set(pulse, Class.forName(p.client()).newInstance());
break;
default:
f.set(pulse, Class.forName(p.server()).newInstance());
}
f.setAccessible(accessible);
if (p != null) { // Support for deprecated PulseProxy annotation
log.warn("Pulse " + pulse + " used the deprecated PulseProxy annotation. As of Pulsar 0.1.0, it's now preferred to use FML's SidedProxy annotation.");
log.warn("The old PulseProxy parsing will be removed in the next breaking update (Pulsar 1.x).");
setProxyField(pulse, f, p.clientSide(), p.serverSide());
}
}
} catch (Exception ex) {
@@ -130,25 +161,80 @@ public class PulseManager {
}
}
@Deprecated
private void setProxyField(Object pulse, Field f, String client, String server) throws Exception {
boolean accessible = f.isAccessible();
f.setAccessible(true);
switch (FMLCommonHandler.instance().getSide()) {
case CLIENT:
f.set(pulse, Class.forName(client).newInstance());
break;
default:
f.set(pulse, Class.forName(server).newInstance());
}
f.setAccessible(accessible);
}
public void preInit(FMLPreInitializationEvent evt) {
if (!blockNewRegistrations) conf.flush(); // First preInit call, so flush config
blockNewRegistrations = true;
for (Map.Entry<IPulse, PulseMeta> e : pulses.entrySet()) {
for (Map.Entry<Object, PulseMeta> e : pulses.entrySet()) {
log.debug("Preinitialising Pulse " + e.getValue().getId() + "...");
e.getKey().preInit(evt);
if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling
IPulse ip = (IPulse)e.getKey();
ip.preInit(evt);
} else findAndInvokeHandlers(e.getKey(), evt);
}
}
public void init(FMLInitializationEvent evt) {
for (Map.Entry<IPulse, PulseMeta> e : pulses.entrySet()) {
for (Map.Entry<Object, PulseMeta> e : pulses.entrySet()) {
log.debug("Initialising Pulse " + e.getValue().getId() + "...");
e.getKey().init(evt);
if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling
IPulse ip = (IPulse)e.getKey();
ip.init(evt);
log.warn("Pulse " + e.getValue().getId() + " is using the deprecated IPulse interface.");
log.warn("This will be removed in the next major version (Pulsar 1.x) - Please switch to @Handler!");
} else findAndInvokeHandlers(e.getKey(), evt);
}
}
public void postInit(FMLPostInitializationEvent evt) {
for (Map.Entry<IPulse, PulseMeta> e : pulses.entrySet()) {
for (Map.Entry<Object, PulseMeta> e : pulses.entrySet()) {
log.debug("Postinitialising Pulse " + e.getValue().getId() + "...");
e.getKey().postInit(evt);
if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling
IPulse ip = (IPulse)e.getKey();
ip.postInit(evt);
} else findAndInvokeHandlers(e.getKey(), evt);
}
}
/**
* Parse an object for a matching handler for the given object.
*
* @param pulse Object to inspect for Handlers
* @param evt The event object
*/
@SuppressWarnings("unchecked")
private void findAndInvokeHandlers(Object pulse, Object evt) {
for (Method m : pulse.getClass().getDeclaredMethods()) {
try {
if (m.getAnnotation(Handler.class) == null) continue; // Ignore non-@Handler methods
Class[] pTypes = m.getParameterTypes();
if (pTypes.length != 1) continue;
Class pt = pTypes[0];
if (pt.isAssignableFrom(evt.getClass())) {
m.invoke(pulse, evt);
}
} catch (Exception ex) {
log.warn("Caught exception in findAndInvokeHandlers: " + ex);
ex.printStackTrace();
}
}
}
+122 -50
View File
@@ -1,11 +1,7 @@
package mantle.pulsar.internal;
import java.io.*;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -13,19 +9,24 @@ import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import cpw.mods.fml.common.Loader;
import mantle.pulsar.config.IConfiguration;
import mantle.pulsar.internal.logging.ILogger;
import mantle.pulsar.pulse.PulseMeta;
/**
* Gson Configuration helper.
* Default Gson Configuration helper.
*
* @author Arkan <[email protected]>
*/
public class Configuration {
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 Logger logger;
private final ILogger logger;
private Map<String, ModuleConfig> modules;
private Map<String, ConfigEntry> modules;
/**
* Creates a new Configuration object.
@@ -35,42 +36,39 @@ public class Configuration {
* @param confName The config file name (without path or .json suffix)
* @param logger The logger to send debug info to.
*/
public Configuration(String confName, Logger logger) {
public Configuration(String confName, ILogger logger) {
this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".json";
this.logger = logger;
this.modules = getModulesFromJson();
}
/**
* Gets whether the given module is enabled in the config.
*
* @param id Module to lookup.
* @param defaultState Whether the module should be enabled or disabled by default (used to push new entries)
* @param defaultDescription The default description if the value does not exist already
* @return Whether the module is enabled.
*/
public boolean isModuleEnabled(String id, boolean defaultState, String defaultDescription) {
ModuleConfig modConfig = modules.get(id);
if (modConfig == null) {
modules.put(id, new ModuleConfig(defaultState, defaultDescription));
writeModulesToJson();
return defaultState;
@Override
public void load() {
getModulesFromJson();
}
@Override
public boolean isModuleEnabled(PulseMeta meta) {
ConfigEntry entry = modules.get(meta.getId());
if (entry == null) {
modules.put(meta.getId(), new ConfigEntry(meta.isEnabled(), meta.getDescription()));
return meta.isEnabled();
} else {
return entry.getEnabled();
}
return modConfig.enabled;
}
@Deprecated
public boolean isModuleEnabled(String id, boolean defaultState)
{
return isModuleEnabled(id, defaultState, null);
}
@Override
public void flush() {
writeModulesToJson();
}
private Map<String, ModuleConfig> getModulesFromJson() {
private void getModulesFromJson() {
// Step 1: Does the file exist?
File f = new File(confPath);
if (!f.exists()) {
logger.info("Couldn't find config file; will generate a new one later.");
return new HashMap<String, ModuleConfig>();
modules = new HashMap<String, ConfigEntry>();
return;
}
// Step 2: File exists. Let's make sure it's usable.
@@ -79,18 +77,50 @@ public class Configuration {
}
// Step 3: Good enough. Read it.
try {
try {
modules = parseV1Config(f);
} catch (Exception ex) {
logger.warn("Failed to parse " + f.getName() + " using the v1 parser; trying the v0 parser.");
Map<String, ConfigEntry> 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) {
logger.warn("Invalid config file. Discarding.");
ex.printStackTrace();
modules = new HashMap<String, ConfigEntry>();
}
}
private Map<String, ConfigEntry> parseV0Config(File f) throws Exception {
try {
JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f)));
Map<String, ModuleConfig> m = gson.fromJson(reader, new TypeToken<HashMap<String, ModuleConfig>>(){}.getType()); // NASTY!
Map<String, Boolean> m = gson.fromJson(reader, new TypeToken<HashMap<String, Boolean>>(){}.getType()); // NASTY!
if (m == null) {
throw new NullPointerException("Gson returned null.");
}
return m;
Map<String, ConfigEntry> out = new HashMap<String, ConfigEntry>();
for (Map.Entry<String, Boolean> e : m.entrySet()) {
out.put(e.getKey(), new ConfigEntry(e.getValue()));
}
return out;
} catch (FileNotFoundException fnfe) {
throw new RuntimeException("This shouldn't be possible... " + fnfe);
}
}
private Map<String, ConfigEntry> 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.");
return c.getModules();
} catch (FileNotFoundException fnfe) {
throw new RuntimeException("This shouldn't be possible... " + fnfe);
} catch (Exception ex) {
logger.warn("Invalid config file. Discarding.");
return new HashMap<String, ModuleConfig>();
}
}
@@ -98,8 +128,8 @@ public class Configuration {
try {
JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(new File(confPath))));
writer.setIndent(" ");
Type t = new TypeToken<Map<String, ModuleConfig>>(){}.getType();
gson.toJson(modules, t, writer);
GsonConfig out = new GsonConfig(CONFIG_LEVEL, modules);
gson.toJson(out, GsonConfig.class, writer);
writer.close();
} catch (Exception ex) {
logger.warn("Could not write config? " + confPath);
@@ -114,17 +144,59 @@ public class Configuration {
super(message);
}
}
private static class ModuleConfig
{
public boolean enabled = true;
public String description = null;
public ModuleConfig(boolean enabled, String description)
{
/**
* Internal data holder, for use in the map and JSON.
*/
private static class ConfigEntry {
private Boolean enabled;
private String description = null;
public ConfigEntry(Boolean enabled) {
this.enabled = enabled;
if (description == null || description.isEmpty())
this.description = null;
else
this.description = description;
}
public ConfigEntry(Boolean enabled, String description) {
this(enabled);
this.description = description;
}
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 int CONFIG_VERSION = 0;
private Map<String, ConfigEntry> modules;
public GsonConfig(int version, Map<String, ConfigEntry> modules) {
this.CONFIG_VERSION = version;
this.modules = modules;
}
public int getConfigVersion() {
return CONFIG_VERSION;
}
public Map<String, ConfigEntry> getModules() {
return modules;
}
}
}
@@ -0,0 +1,23 @@
package mantle.pulsar.internal.logging;
/**
* Interface for log wrappers.
*
* @author Arkan <[email protected]>
*/
@SuppressWarnings("unused")
public interface ILogger {
public void fatal(String msg);
public void severe(String msg);
public void warn(String msg);
public void info(String msg);
public void debug(String msg);
public void trace(String msg);
}
@@ -0,0 +1,48 @@
package mantle.pulsar.internal.logging;
import java.util.logging.Logger;
/**
* Java logger wrapper.
*
* @author Arkan <[email protected]>
*/
public class JULLogger implements ILogger {
private final Logger log;
public JULLogger(String name) {
log = Logger.getLogger(name);
}
@Override
public void fatal(String msg) {
log.severe(msg); // JUL doesn't -have- fatal...
}
@Override
public void severe(String msg) {
log.severe(msg);
}
@Override
public void warn(String msg) {
log.warning(msg);
}
@Override
public void info(String msg) {
log.info(msg);
}
@Override
public void debug(String msg) {
log.fine(msg); // Good enough.
}
@Override
public void trace(String msg) {
log.finest(msg); // Closest we'll get.
}
}
@@ -0,0 +1,48 @@
package mantle.pulsar.internal.logging;
import org.apache.logging.log4j.Logger;
/**
* Log4j log wrapper.
*
* @author Arkan <[email protected]>
*/
public class Log4jLogger implements ILogger {
private final Logger log;
public Log4jLogger(String name) {
log = org.apache.logging.log4j.LogManager.getLogger(name);
}
@Override
public void fatal(String msg) {
log.fatal(msg);
}
@Override
public void severe(String msg) {
log.error(msg);
}
@Override
public void warn(String msg) {
log.warn(msg);
}
@Override
public void info(String msg) {
log.info(msg);
}
@Override
public void debug(String msg) {
log.debug(msg);
}
@Override
public void trace(String msg) {
log.trace(msg);
}
}
@@ -0,0 +1,39 @@
package mantle.pulsar.internal.logging;
/**
* Static class for getting generic loggers.
*
* @author Arkan <[email protected]>
*/
public class LogManager {
private LogManager() {} // Singleton.
private static final boolean useLog4j2;
/*
* Detect the presence of log4j2.
*
* If it's present, we can assume we should be using the damn thing.
*/
static {
boolean l4j = false;
try {
Class cl = Class.forName("org.apache.logging.log4j.LogManager");
if (cl == null) throw new ClassNotFoundException("This should never happen...");
l4j = true;
} catch (ClassNotFoundException cnfe) {
// Ignore
}
useLog4j2 = l4j;
}
public static ILogger getLogger(String name) {
if (useLog4j2) {
return new Log4jLogger(name);
} else {
return new JULLogger(name);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
package mantle.pulsar.pulse;
import java.lang.annotation.*;
/**
* Annotates methods to be used for event handling.
*
* @author Arkan <[email protected]>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Handler
{}
+9 -6
View File
@@ -7,29 +7,32 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent;
/**
* Base interface for all Pulsar modules ("pulses").
*
* @deprecated Use the new {@link Handler} annotation.
*
* @author Arkan <[email protected]>
*/
@Deprecated
public interface IPulse {
/**
* FML preinit from the parent mod.
*
* @param event The FML event inherited from this Pulses parent.
* @param evt The FML event inherited from this Pulses parent.
*/
public void preInit(FMLPreInitializationEvent event);
public void preInit(FMLPreInitializationEvent evt);
/**
* FML init from the parent mod.
*
* @param event The FML event inherited from this Pulses parent.
* @param evt The FML event inherited from this Pulses parent.
*/
public void init(FMLInitializationEvent event);
public void init(FMLInitializationEvent evt);
/**
* FML postinit from the parent mod.
*
* @param event The FML event inherited from this Pulses parent.
* @param evt The FML event inherited from this Pulses parent.
*/
public void postInit(FMLPostInitializationEvent event);
public void postInit(FMLPostInitializationEvent evt);
}
+10 -4
View File
@@ -17,6 +17,16 @@ public @interface Pulse {
*/
public String id();
/**
* @return This Pulses description, human-readable for config files. Can be blank.
*/
public String description() default "";
/**
* @return Dependant mod IDs, seperated by ; as in FML. Skips checks when undefined.
*/
public String modsRequired() default "";
/**
* @return Whether this Pulse is mandatory or not (true -> mandatory).
*/
@@ -27,8 +37,4 @@ public @interface Pulse {
*/
public boolean defaultEnable() default true;
/**
* @return A description for this Pulse, if present this is used for config descriptions
*/
public String description() default "";
}
@@ -1,4 +1,4 @@
package mantle.pulsar.internal;
package mantle.pulsar.pulse;
/**
* Metadata wrapper for parsed @Pulse metadata.
@@ -10,17 +10,21 @@ public class PulseMeta {
private String id, description;
private boolean forced, enabled;
public PulseMeta(String id, boolean forced, boolean enabled, String description) {
public PulseMeta(String id, String description, boolean forced, boolean enabled) {
this.id = id;
this.description = description;
this.forced = forced;
this.enabled = enabled;
setDescription(description);
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public boolean isForced() {
return forced;
}
@@ -32,16 +36,4 @@ public class PulseMeta {
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setDescription(String description)
{
if(description == null || description.isEmpty())
this.description = null;
else
this.description = description;
}
public String getDescription() {
return description;
}
}
+5 -2
View File
@@ -5,21 +5,24 @@ import java.lang.annotation.*;
/**
* Annotation to denote a field that should be populated by a side-specific proxy.
*
* @deprecated Use FML's @SidedProxy instead.
*
* @author Arkan <[email protected]>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Documented
@Deprecated
public @interface PulseProxy {
/**
* @return The FQCN of the client proxy.
*/
public String client();
public String clientSide();
/**
* @return The FQCN of the server proxy.
*/
public String server();
public String serverSide();
}