Citizens2/src/main/java/net/citizensnpcs/Citizens.java

371 lines
14 KiB
Java
Raw Normal View History

2012-01-15 00:51:37 +01:00
package net.citizensnpcs;
2012-01-19 11:52:58 +01:00
import java.io.File;
2012-05-26 16:31:01 +02:00
import java.io.IOException;
2012-02-17 08:48:20 +01:00
import java.sql.SQLException;
import java.util.Iterator;
2012-01-19 11:52:58 +01:00
2012-01-23 15:30:15 +01:00
import net.citizensnpcs.Settings.Setting;
2012-01-15 00:51:37 +01:00
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.CitizensPlugin;
2012-03-08 02:03:32 +01:00
import net.citizensnpcs.api.event.CitizensReloadEvent;
2012-01-19 11:52:58 +01:00
import net.citizensnpcs.api.exception.NPCLoadException;
2012-01-18 05:04:08 +01:00
import net.citizensnpcs.api.npc.NPC;
2012-05-17 15:34:03 +02:00
import net.citizensnpcs.api.npc.NPCRegistry;
2012-04-12 17:31:54 +02:00
import net.citizensnpcs.api.scripting.EventRegistrar;
2012-05-03 17:22:31 +02:00
import net.citizensnpcs.api.scripting.ObjectProvider;
2012-04-12 17:01:56 +02:00
import net.citizensnpcs.api.scripting.ScriptCompiler;
2012-07-19 17:10:30 +02:00
import net.citizensnpcs.api.trait.TraitFactory;
2012-02-12 09:00:19 +01:00
import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.DatabaseStorage;
2012-03-30 16:01:36 +02:00
import net.citizensnpcs.api.util.NBTStorage;
2012-02-12 09:00:19 +01:00
import net.citizensnpcs.api.util.Storage;
import net.citizensnpcs.api.util.YamlStorage;
import net.citizensnpcs.command.CommandManager;
2012-01-25 21:07:49 +01:00
import net.citizensnpcs.command.Injector;
import net.citizensnpcs.command.command.AdminCommands;
2012-02-27 09:32:43 +01:00
import net.citizensnpcs.command.command.EditorCommands;
2012-02-08 09:26:14 +01:00
import net.citizensnpcs.command.command.HelpCommands;
import net.citizensnpcs.command.command.NPCCommands;
2012-04-13 17:59:51 +02:00
import net.citizensnpcs.command.command.ScriptCommands;
2012-02-29 11:50:45 +01:00
import net.citizensnpcs.command.exception.CommandException;
import net.citizensnpcs.command.exception.CommandUsageException;
import net.citizensnpcs.command.exception.ServerCommandException;
import net.citizensnpcs.command.exception.UnhandledCommandException;
import net.citizensnpcs.command.exception.WrappedCommandException;
2012-02-27 16:59:39 +01:00
import net.citizensnpcs.editor.Editor;
2012-03-09 21:53:02 +01:00
import net.citizensnpcs.npc.CitizensNPC;
2012-05-17 15:34:03 +02:00
import net.citizensnpcs.npc.CitizensNPCRegistry;
2012-07-19 17:10:30 +02:00
import net.citizensnpcs.npc.CitizensTraitFactory;
import net.citizensnpcs.npc.NPCSelector;
import net.citizensnpcs.util.Messaging;
import net.citizensnpcs.util.StringHelper;
2012-01-15 00:51:37 +01:00
import org.bukkit.Bukkit;
2012-01-22 18:43:58 +01:00
import org.bukkit.ChatColor;
2012-01-19 11:52:58 +01:00
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
2012-01-29 21:58:19 +01:00
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.EntityType;
2012-01-19 11:52:58 +01:00
import org.bukkit.entity.Player;
2012-07-19 17:10:30 +02:00
import org.bukkit.plugin.Plugin;
2012-01-15 00:51:37 +01:00
import org.bukkit.plugin.java.JavaPlugin;
2012-05-26 16:31:01 +02:00
import com.google.common.collect.Iterables;
public class Citizens extends JavaPlugin implements CitizensPlugin {
2012-02-12 08:19:32 +01:00
private final CommandManager commands = new CommandManager();
2012-03-10 11:33:11 +01:00
private boolean compatible;
2012-03-27 16:42:15 +02:00
private Settings config;
2012-04-18 04:12:17 +02:00
private ClassLoader contextClassLoader;
2012-05-17 15:34:03 +02:00
private CitizensNPCRegistry npcRegistry;
private Storage saves; // TODO: refactor this, it's used in too many places
private NPCSelector selector;
2012-07-19 17:10:30 +02:00
private CitizensTraitFactory traitFactory;
2012-03-02 14:04:40 +01:00
2012-07-19 17:10:30 +02:00
private void despawnNPCs() {
Iterator<NPC> itr = npcRegistry.iterator();
while (itr.hasNext()) {
NPC npc = itr.next();
itr.remove();
npc.despawn();
}
}
private void enableSubPlugins() {
File root = new File(getDataFolder(), Setting.SUBPLUGIN_FOLDER.asString());
if (!root.exists() || !root.isDirectory())
return;
Plugin[] plugins = Bukkit.getPluginManager().loadPlugins(root);
// code beneath modified from CraftServer
for (Plugin plugin : plugins) {
try {
Messaging.logF("Loading %s", plugin.getDescription().getFullName());
plugin.onLoad();
} catch (Throwable ex) {
Messaging.severe(ex.getMessage() + " initializing " + plugin.getDescription().getFullName());
ex.printStackTrace();
}
}
}
2012-05-17 15:34:03 +02:00
public Iterable<net.citizensnpcs.command.Command> getCommands(String base) {
return commands.getCommands(base);
2012-03-02 11:36:54 +01:00
}
@Override
2012-05-17 15:34:03 +02:00
public NPCRegistry getNPCRegistry() {
return npcRegistry;
2012-03-02 11:36:54 +01:00
}
public NPCSelector getNPCSelector() {
return selector;
}
@Override
public File getScriptFolder() {
return new File(getDataFolder(), "scripts");
}
@Override
2012-07-19 17:10:30 +02:00
public TraitFactory getTraitFactory() {
return traitFactory;
}
2012-01-23 09:45:34 +01:00
@Override
public boolean onCommand(CommandSender sender, Command cmd, String cmdName, String[] args) {
try {
// must put command into split.
String[] split = new String[args.length + 1];
System.arraycopy(args, 0, split, 1, args.length);
split[0] = cmd.getName().toLowerCase();
2012-02-12 08:19:32 +01:00
String modifier = args.length > 0 ? args[0] : "";
2012-02-12 08:19:32 +01:00
if (!commands.hasCommand(split[0], modifier) && !modifier.isEmpty()) {
return suggestClosestModifier(sender, split[0], modifier);
}
NPC npc = selector.getSelected(sender);
// TODO: change the args supplied to a context style system for
// flexibility (ie. adding more context in the future without
// changing everything)
try {
commands.execute(split, sender, sender, npc);
} catch (ServerCommandException ex) {
2012-02-29 11:50:45 +01:00
Messaging.send(sender, "You must be in-game to execute that command.");
} catch (CommandUsageException ex) {
Messaging.sendError(sender, ex.getMessage());
Messaging.sendError(sender, ex.getUsage());
2012-02-29 11:50:45 +01:00
} catch (WrappedCommandException ex) {
throw ex.getCause();
} catch (UnhandledCommandException ex) {
return false;
2012-02-29 11:50:45 +01:00
} catch (CommandException ex) {
Messaging.sendError(sender, ex.getMessage());
}
2012-02-29 11:50:45 +01:00
} catch (NumberFormatException ex) {
Messaging.sendError(sender, "That is not a valid number.");
2012-02-29 11:50:45 +01:00
} catch (Throwable ex) {
ex.printStackTrace();
if (sender instanceof Player) {
Messaging.sendError(sender, "Please report this error: [See console]");
Messaging.sendError(sender, ex.getClass().getName() + ": " + ex.getMessage());
}
2012-01-23 09:45:34 +01:00
}
return true;
}
2012-01-19 12:43:21 +01:00
@Override
public void onDisable() {
Bukkit.getPluginManager().callEvent(new CitizensDisableEvent());
2012-07-22 08:18:24 +02:00
Editor.leaveAll();
CitizensAPI.shutdown();
tearDownScripting();
2012-01-29 21:58:19 +01:00
// Don't bother with this part if MC versions are not compatible
2012-01-30 12:58:59 +01:00
if (compatible) {
2012-02-28 08:41:15 +01:00
save();
despawnNPCs();
2012-05-17 15:34:03 +02:00
npcRegistry = null;
2012-01-29 21:58:19 +01:00
}
2012-01-21 13:53:58 +01:00
Messaging.logF("v%s disabled.", getDescription().getVersion());
2012-01-19 12:43:21 +01:00
}
2012-01-15 00:51:37 +01:00
2012-01-19 12:43:21 +01:00
@Override
public void onEnable() {
2012-01-29 21:58:19 +01:00
// Disable if the server is not using the compatible Minecraft version
2012-01-30 12:58:59 +01:00
String mcVersion = ((CraftServer) getServer()).getServer().getVersion();
2012-04-05 17:03:30 +02:00
compatible = mcVersion.startsWith(COMPATIBLE_MC_VERSION);
2012-01-30 12:58:59 +01:00
if (!compatible) {
2012-07-22 08:18:24 +02:00
Messaging.severeF("v%s is not compatible with Minecraft v%s. Disabling.", getDescription()
.getVersion(), mcVersion);
2012-01-29 21:58:19 +01:00
getServer().getPluginManager().disablePlugin(this);
return;
}
2012-04-18 04:12:17 +02:00
registerScriptHelpers();
2012-01-29 21:58:19 +01:00
2012-04-15 01:32:43 +02:00
config = new Settings(getDataFolder());
2012-01-19 11:52:58 +01:00
2012-04-18 04:12:17 +02:00
setupStorage();
2012-02-12 08:19:32 +01:00
2012-05-17 15:34:03 +02:00
npcRegistry = new CitizensNPCRegistry(saves);
2012-07-19 17:10:30 +02:00
traitFactory = new CitizensTraitFactory();
selector = new NPCSelector(this);
CitizensAPI.setImplementation(this);
2012-01-23 17:05:22 +01:00
2012-05-17 15:34:03 +02:00
getServer().getPluginManager().registerEvents(new EventListen(), this);
registerCommands();
2012-01-23 15:30:15 +01:00
Messaging.logF("v%s enabled.", getDescription().getVersion());
2012-01-18 05:04:08 +01:00
2012-01-19 12:43:21 +01:00
// Setup NPCs after all plugins have been enabled (allows for multiworld
// support and for NPCs to properly register external settings)
if (getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
2012-01-19 12:43:21 +01:00
@Override
public void run() {
setupNPCs();
2012-05-26 16:31:01 +02:00
startMetrics();
2012-07-19 17:10:30 +02:00
enableSubPlugins();
2012-01-19 12:43:21 +01:00
}
2012-01-20 08:27:14 +01:00
}) == -1) {
Messaging.severe("Issue enabling plugin. Disabling.");
2012-01-19 12:43:21 +01:00
getServer().getPluginManager().disablePlugin(this);
}
}
@Override
public void onImplementationChanged() {
Messaging.severe("Citizens implementation changed, disabling plugin.");
Bukkit.getPluginManager().disablePlugin(this);
}
2012-03-02 11:36:54 +01:00
private void registerCommands() {
commands.setInjector(new Injector(this));
// Register command classes
commands.register(AdminCommands.class);
commands.register(EditorCommands.class);
commands.register(HelpCommands.class);
commands.register(NPCCommands.class);
2012-04-13 17:59:51 +02:00
commands.register(ScriptCommands.class);
}
private void registerScriptHelpers() {
setupScripting();
2012-04-13 17:59:51 +02:00
ScriptCompiler compiler = CitizensAPI.getScriptCompiler();
compiler.registerGlobalContextProvider(new EventRegistrar(this));
2012-05-03 17:22:31 +02:00
compiler.registerGlobalContextProvider(new ObjectProvider("plugin", this));
2012-02-28 08:41:15 +01:00
}
public void reload() throws NPCLoadException {
2012-02-27 16:59:39 +01:00
Editor.leaveAll();
2012-04-15 01:32:43 +02:00
config.reload();
despawnNPCs();
setupNPCs();
2012-03-08 02:03:32 +01:00
getServer().getPluginManager().callEvent(new CitizensReloadEvent());
}
2012-03-02 11:36:54 +01:00
public void save() {
2012-05-17 15:34:03 +02:00
for (NPC npc : npcRegistry)
2012-03-09 21:53:02 +01:00
((CitizensNPC) npc).save(saves.getKey("npc." + npc.getId()));
2012-04-14 18:49:18 +02:00
2012-03-02 11:36:54 +01:00
saves.save();
}
2012-04-18 04:12:17 +02:00
// TODO: refactor
2012-04-19 05:52:07 +02:00
private void setupNPCs() {
saves.load();
2012-01-29 12:43:27 +01:00
int created = 0, spawned = 0;
for (DataKey key : saves.getKey("npc").getIntegerSubKeys()) {
2012-01-19 12:43:21 +01:00
int id = Integer.parseInt(key.name());
2012-04-19 05:52:07 +02:00
if (!key.keyExists("name")) {
Messaging.logF("Could not find a name for the NPC with ID '%s'.", id);
2012-04-19 05:52:07 +02:00
continue;
}
2012-04-20 17:19:15 +02:00
String unparsedEntityType = key.getString("traits.type", "PLAYER");
EntityType type = EntityType.fromName(unparsedEntityType);
2012-03-27 16:42:15 +02:00
if (type == null) {
try {
type = EntityType.valueOf(unparsedEntityType);
2012-03-27 16:42:15 +02:00
} catch (IllegalArgumentException ex) {
2012-07-22 08:18:24 +02:00
Messaging.logF("NPC type '%s' was not recognized. Did you spell it correctly?",
unparsedEntityType);
2012-04-19 05:52:07 +02:00
continue;
2012-03-27 16:42:15 +02:00
}
}
2012-07-19 17:10:30 +02:00
NPC npc = npcRegistry.createNPC(type, id, key.getString("name"));
((CitizensNPC) npc).load(key);
2012-02-12 08:19:32 +01:00
2012-01-29 12:43:27 +01:00
++created;
if (npc.isSpawned())
++spawned;
2012-01-19 12:43:21 +01:00
}
Messaging.logF("Loaded %d NPCs (%d spawned).", created, spawned);
2012-01-19 12:43:21 +01:00
}
2012-03-02 11:36:54 +01:00
private void setupScripting() {
contextClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClassLoader());
2012-07-19 17:10:30 +02:00
// Workaround to fix scripts not loading plugin classes properly.
// The built in Sun Rhino Javascript engine uses the context classloader
// to search for class imports. Since the context classloader only has
// CraftBukkit classes, we replace it with a PluginClassLoader, which
// allows all plugin classes to be imported.
}
private void setupStorage() {
String type = Setting.STORAGE_TYPE.asString();
if (type.equalsIgnoreCase("db") || type.equalsIgnoreCase("database")) {
try {
2012-07-22 08:18:24 +02:00
saves = new DatabaseStorage(Setting.DATABASE_DRIVER.asString(),
Setting.DATABASE_URL.asString(), Setting.DATABASE_USERNAME.asString(),
Setting.DATABASE_PASSWORD.asString());
} catch (SQLException e) {
e.printStackTrace();
Messaging.log("Unable to connect to database, falling back to YAML");
}
} else if (type.equalsIgnoreCase("nbt")) {
saves = new NBTStorage(getDataFolder() + File.separator + Setting.STORAGE_FILE.asString(),
"Citizens NPC Storage");
}
if (saves == null) {
saves = new YamlStorage(getDataFolder() + File.separator + Setting.STORAGE_FILE.asString(),
"Citizens NPC Storage");
}
Messaging.logF("Save method set to %s.", saves.toString());
}
2012-07-19 17:10:30 +02:00
private void startMetrics() {
new Thread() {
@Override
public void run() {
try {
Metrics metrics = new Metrics(Citizens.this);
if (metrics.isOptOut())
return;
metrics.addCustomData(new Metrics.Plotter("Total NPCs") {
@Override
public int getValue() {
return Iterables.size(npcRegistry);
}
});
traitFactory.addPlotters(metrics.createGraph("traits"));
metrics.start();
Messaging.log("Metrics started.");
} catch (IOException e) {
Messaging.logF("Unable to start metrics: %s.", e.getMessage());
}
}
}.start();
}
2012-03-02 11:36:54 +01:00
private boolean suggestClosestModifier(CommandSender sender, String command, String modifier) {
int minDist = Integer.MAX_VALUE;
String closest = "";
for (String string : commands.getAllCommandModifiers(command)) {
int distance = StringHelper.getLevenshteinDistance(modifier, string);
if (minDist > distance) {
minDist = distance;
closest = string;
}
}
if (!closest.isEmpty()) {
sender.sendMessage(ChatColor.GRAY + "Unknown command. Did you mean:");
sender.sendMessage(StringHelper.wrap(" /") + command + " " + StringHelper.wrap(closest));
return true;
}
return false;
}
2012-03-27 16:42:15 +02:00
private void tearDownScripting() {
2012-07-22 08:18:24 +02:00
if (Thread.currentThread().getContextClassLoader() == getClassLoader())
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
2012-03-31 23:15:53 +02:00
private static final String COMPATIBLE_MC_VERSION = "1.2.5";
2012-01-15 00:51:37 +01:00
}