diff --git a/Gui/.gitignore b/com/gamingmesh/jobs/Gui/.gitignore similarity index 100% rename from Gui/.gitignore rename to com/gamingmesh/jobs/Gui/.gitignore diff --git a/Gui/GuiInfoList.java b/com/gamingmesh/jobs/Gui/GuiInfoList.java similarity index 90% rename from Gui/GuiInfoList.java rename to com/gamingmesh/jobs/Gui/GuiInfoList.java index 851732a4..a1575842 100644 --- a/Gui/GuiInfoList.java +++ b/com/gamingmesh/jobs/Gui/GuiInfoList.java @@ -1,4 +1,4 @@ -package Gui; +package com.gamingmesh.jobs.Gui; import java.util.ArrayList; import java.util.List; diff --git a/Gui/GuiTools.java b/com/gamingmesh/jobs/Gui/GuiTools.java similarity index 96% rename from Gui/GuiTools.java rename to com/gamingmesh/jobs/Gui/GuiTools.java index 74bf47d6..8a041d41 100644 --- a/Gui/GuiTools.java +++ b/com/gamingmesh/jobs/Gui/GuiTools.java @@ -1,4 +1,4 @@ -package Gui; +package com.gamingmesh.jobs.Gui; import java.util.ArrayList; import java.util.HashMap; diff --git a/com/gamingmesh/jobs/Jobs.java b/com/gamingmesh/jobs/Jobs.java index 6b272abc..cc66ab7a 100644 --- a/com/gamingmesh/jobs/Jobs.java +++ b/com/gamingmesh/jobs/Jobs.java @@ -48,6 +48,7 @@ import com.gamingmesh.jobs.i18n.Language; import com.gamingmesh.jobs.stuff.ActionBar; import com.gamingmesh.jobs.stuff.Debug; import com.gamingmesh.jobs.stuff.JobsClassLoader; +import com.gamingmesh.jobs.stuff.Loging; import com.gamingmesh.jobs.tasks.BufferedPaymentThread; import com.gamingmesh.jobs.tasks.DatabaseSaveThread; @@ -563,7 +564,7 @@ public class Jobs { Jobs.getEconomy().pay(jPlayer, amount, expAmount); int oldLevel = prog.getLevel(); - recordToLog(jPlayer, info, amount, expAmount); + Loging.recordToLog(jPlayer, info, amount, expAmount); if (prog.addExperience(expAmount)) Jobs.getPlayerManager().performLevelUp(jPlayer, prog.getJob(), oldLevel); @@ -573,27 +574,4 @@ public class Jobs { } } - private static void recordToLog(JobsPlayer jPlayer, ActionInfo info, double amount, double expAmount) { - List logList = jPlayer.getLog(); - boolean found = false; - for (Log one : logList) { - if (!one.getActionType().getName().equalsIgnoreCase(info.getType().getName())) - continue; - - one.add(info.getNameWithSub(), amount, expAmount); - - found = true; - - Debug.D(info.getNameWithSub() + " : " + one.getCount(info.getNameWithSub()) + " money: " + one.getMoney(info.getNameWithSub()) + " exp:" + one.getExp(info - .getNameWithSub())); - } - if (!found) { - Log log = new Log(info.getType()); - log.add(info.getNameWithSub(), amount, expAmount); - logList.add(log); - String msg = info.getNameWithSub() + " : " + log.getCount(info.getNameWithSub()) + " money: " + log.getMoney(info.getNameWithSub()) + " exp:" + log.getExp(info - .getNameWithSub()); - Debug.D(msg); - } - } } diff --git a/com/gamingmesh/jobs/JobsPlugin.java b/com/gamingmesh/jobs/JobsPlugin.java index f29b9b38..67f26768 100644 --- a/com/gamingmesh/jobs/JobsPlugin.java +++ b/com/gamingmesh/jobs/JobsPlugin.java @@ -42,11 +42,11 @@ import com.gamingmesh.jobs.stuff.TabComplete; import com.gamingmesh.jobs.config.YmlMaker; public class JobsPlugin extends JavaPlugin { - public static Plugin instance; - public static CoreProtectAPI CPAPI; - public static boolean CPPresent = false; + public static Plugin instance; + public static CoreProtectAPI CPAPI; + public static boolean CPPresent = false; - @Override + @Override public void onEnable() { instance = this; YmlMaker jobConfig = new YmlMaker(this, "jobConfig.yml"); @@ -100,17 +100,18 @@ public class JobsPlugin extends JavaPlugin { if (ConfigManager.getJobsConfiguration().useGlobalBoostScheduler) ScheduleUtil.scheduler(); + ScheduleUtil.DateUpdater(); String message = ChatColor.translateAlternateColorCodes('&', "&2Plugin has been enabled succesfully."); ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); console.sendMessage(message); } - @Override - public void onDisable() { - Jobs.shutdown(); - String message = ChatColor.translateAlternateColorCodes('&', "&2Plugin has been disabled succesfully."); - ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); - console.sendMessage(message); - } + @Override + public void onDisable() { + Jobs.shutdown(); + String message = ChatColor.translateAlternateColorCodes('&', "&2Plugin has been disabled succesfully."); + ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); + console.sendMessage(message); + } } diff --git a/com/gamingmesh/jobs/PermissionHandler.java b/com/gamingmesh/jobs/PermissionHandler.java index dd0ed749..a5d2fd17 100644 --- a/com/gamingmesh/jobs/PermissionHandler.java +++ b/com/gamingmesh/jobs/PermissionHandler.java @@ -20,6 +20,7 @@ package com.gamingmesh.jobs; import java.util.HashMap; import java.util.List; + import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; @@ -29,6 +30,7 @@ import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.PluginManager; import com.gamingmesh.jobs.container.Job; +import com.gamingmesh.jobs.container.JobConditions; import com.gamingmesh.jobs.container.JobPermission; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; @@ -83,6 +85,62 @@ public class PermissionHandler { } } } + + for (JobConditions Condition : job.getConditions()) { + boolean ok = true; + for (String oneReq : Condition.getRequires()) { + if (oneReq.toLowerCase().contains("j:")) { + String jobName = oneReq.toLowerCase().replace("j:", "").split("-")[0]; + int jobLevel = Integer.valueOf(oneReq.toLowerCase().replace("j:", "").split("-")[1]); + boolean found = false; + for (JobProgression oneJob : jPlayer.getJobProgression()) { + if (oneJob.getJob().getName().equalsIgnoreCase(jobName)) + found = true; + if (oneJob.getJob().getName().equalsIgnoreCase(jobName) && oneJob.getLevel() < jobLevel) { + ok = false; + break; + } + } + if (found == false) + ok = false; + } + if (ok = false) + break; + + if (oneReq.toLowerCase().contains("p:")) { + if (!player.hasPermission(oneReq.replace(":p", ""))) { + ok = false; + break; + } + } + } + + if (!ok) + continue; + + for (String one : Condition.getPerform()) { + if (!one.toLowerCase().contains("p:")) + continue; + + String perm = one.toLowerCase().replace("p:", "").split("-")[0]; + boolean node = Boolean.getBoolean(one.toLowerCase().replace("p:", "").split("-")[1]); + + if (node) { + permissions.put(perm, true); + } else { + /* + * If the key exists, don't put a false node in + * This is in case we already have a true node there + */ + if (!permissions.containsKey(perm)) { + permissions.put(perm, false); + } + } + + } + + } + } } else { for (JobProgression prog : progression) { @@ -101,6 +159,59 @@ public class PermissionHandler { } } } + + for (JobConditions Condition : prog.getJob().getConditions()) { + boolean ok = true; + for (String oneReq : Condition.getRequires()) { + if (oneReq.toLowerCase().contains("j:")) { + String jobName = oneReq.toLowerCase().replace("j:", "").split("-")[0]; + int jobLevel = Integer.valueOf(oneReq.toLowerCase().replace("j:", "").split("-")[1]); + boolean found = false; + for (JobProgression oneJob : jPlayer.getJobProgression()) { + if (oneJob.getJob().getName().equalsIgnoreCase(jobName)) + found = true; + if (oneJob.getJob().getName().equalsIgnoreCase(jobName) && oneJob.getLevel() < jobLevel) { + ok = false; + break; + } + } + if (found == false) + ok = false; + + } + if (ok == false) + break; + + if (oneReq.toLowerCase().contains("p:")) { + if (!player.hasPermission(oneReq.replace("p:", ""))) { + ok = false; + break; + } + } + } + + if (!ok) + continue; + for (String one : Condition.getPerform()) { + if (!one.toLowerCase().contains("p:")) + continue; + String perm = one.toLowerCase().replace("p:", "").split("-")[0]; + String nodeString = one.toLowerCase().replace("p:", "").split("-")[1]; + boolean node = nodeString.equalsIgnoreCase("true") ? true : false; + + if (node) { + permissions.put(perm, true); + } else { + /* + * If the key exists, don't put a false node in + * This is in case we already have a true node there + */ + if (!permissions.containsKey(perm)) { + permissions.put(perm, false); + } + } + } + } } } diff --git a/com/gamingmesh/jobs/PlayerManager.java b/com/gamingmesh/jobs/PlayerManager.java index 57a1f570..dc010302 100644 --- a/com/gamingmesh/jobs/PlayerManager.java +++ b/com/gamingmesh/jobs/PlayerManager.java @@ -19,6 +19,7 @@ package com.gamingmesh.jobs; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -36,6 +37,7 @@ import com.gamingmesh.jobs.api.JobsLevelUpEvent; import com.gamingmesh.jobs.config.ConfigManager; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobCommands; +import com.gamingmesh.jobs.container.JobConditions; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.dao.JobsDAO; @@ -45,8 +47,8 @@ import com.gamingmesh.jobs.stuff.ChatColor; import com.gamingmesh.jobs.stuff.PerformCommands; public class PlayerManager { - // private Map players = Collections.synchronizedMap(new HashMap()); - private Map players = new HashMap(); + private Map players = Collections.synchronizedMap(new HashMap()); + //private Map players = new HashMap(); /** * Handles join of new player @@ -57,6 +59,7 @@ public class PlayerManager { JobsPlayer jPlayer = players.get(player.getName().toLowerCase()); if (jPlayer == null) { jPlayer = JobsPlayer.loadFromDao(Jobs.getJobsDAO(), player); + JobsPlayer.loadLogFromDao(jPlayer); players.put(player.getName().toLowerCase(), jPlayer); } jPlayer.onConnect(); @@ -65,6 +68,7 @@ public class PlayerManager { return; } } + /** * Handles player quit * @param playername @@ -175,8 +179,8 @@ public class PlayerManager { Jobs.getJobsDAO().joinJob(jPlayer, job); PerformCommands.PerformCommandsOnJoin(jPlayer, job); Jobs.takeSlot(job); - Signs.SignUtil.SignUpdate(job.getName()); - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); job.updateTotalPlayers(); } } @@ -206,8 +210,8 @@ public class PlayerManager { PerformCommands.PerformCommandsOnLeave(jPlayer, job); Jobs.leaveSlot(job); - Signs.SignUtil.SignUpdate(job.getName()); - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); job.updateTotalPlayers(); } } @@ -223,8 +227,8 @@ public class PlayerManager { PerformCommands.PerformCommandsOnLeave(jPlayer, job.getJob()); Jobs.leaveSlot(job.getJob()); - Signs.SignUtil.SignUpdate(job.getJob().getName()); - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getJob().getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); job.getJob().updateTotalPlayers(); } @@ -263,8 +267,8 @@ public class PlayerManager { jPlayer.promoteJob(job, levels, jPlayer); jPlayer.save(Jobs.getJobsDAO()); - Signs.SignUtil.SignUpdate(job.getName()); - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); } } @@ -278,8 +282,8 @@ public class PlayerManager { synchronized (jPlayer.saveLock) { jPlayer.demoteJob(job, levels); jPlayer.save(Jobs.getJobsDAO()); - Signs.SignUtil.SignUpdate(job.getName()); - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); } } @@ -299,8 +303,8 @@ public class PlayerManager { performLevelUp(jPlayer, job, oldLevel); jPlayer.save(Jobs.getJobsDAO()); - Signs.SignUtil.SignUpdate(job.getName()); - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); } } @@ -318,8 +322,8 @@ public class PlayerManager { prog.addExperience(-experience); jPlayer.save(Jobs.getJobsDAO()); - Signs.SignUtil.SignUpdate(job.getName()); - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); } } @@ -414,8 +418,58 @@ public class PlayerManager { jPlayer.reloadHonorific(); Jobs.getPermissionHandler().recalculatePermissions(jPlayer); performCommandOnLevelUp(jPlayer, prog.getJob(), oldLevel); - Signs.SignUtil.SignUpdate(job.getName()); - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); + } + + /** + * Performs command on level up + * @param jPlayer + * @param job + * @param oldLevel + */ + public void CheckConditions(JobsPlayer jPlayer, Job job) { + Player player = Bukkit.getServer().getPlayer(jPlayer.getPlayerUUID()); + JobProgression prog = jPlayer.getJobProgression(job); + if (prog == null) + return; + for (JobConditions Condition : job.getConditions()) { + boolean ok = true; + for (String oneReq : Condition.getRequires()) { + if (oneReq.toLowerCase().contains("j:")) { + String jobName = oneReq.toLowerCase().replace("j:", "").split("-")[0]; + int jobLevel = Integer.valueOf(oneReq.toLowerCase().replace("j:", "").split("-")[1]); + boolean found = false; + for (JobProgression oneJob : jPlayer.getJobProgression()) { + if (oneJob.getJob().getName().equalsIgnoreCase(jobName)) + found = true; + if (oneJob.getJob().getName().equalsIgnoreCase(jobName) && oneJob.getLevel() != jobLevel) { + ok = false; + break; + } + } + if (found == false) + ok = false; + } + if (ok = false) + break; + + if (oneReq.toLowerCase().contains("p:")) { + if (!player.hasPermission(oneReq.replace(":p", ""))) { + ok = false; + break; + } + } + } + + if (ok) { + for (String one : Condition.getPerform()) { + if (one.toLowerCase().contains("c:")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), one.replace("c:", "").replace("[name]", jPlayer.getUserName())); + } + } + } + } } /** diff --git a/Signs/.gitignore b/com/gamingmesh/jobs/Signs/.gitignore similarity index 100% rename from Signs/.gitignore rename to com/gamingmesh/jobs/Signs/.gitignore diff --git a/Signs/Sign.java b/com/gamingmesh/jobs/Signs/Sign.java similarity index 90% rename from Signs/Sign.java rename to com/gamingmesh/jobs/Signs/Sign.java index d2cf0033..60fe4636 100644 --- a/Signs/Sign.java +++ b/com/gamingmesh/jobs/Signs/Sign.java @@ -1,4 +1,4 @@ -package Signs; +package com.gamingmesh.jobs.Signs; public class Sign { diff --git a/Signs/SignInfo.java b/com/gamingmesh/jobs/Signs/SignInfo.java similarity index 87% rename from Signs/SignInfo.java rename to com/gamingmesh/jobs/Signs/SignInfo.java index 7987d461..c52001c5 100644 --- a/Signs/SignInfo.java +++ b/com/gamingmesh/jobs/Signs/SignInfo.java @@ -1,4 +1,4 @@ -package Signs; +package com.gamingmesh.jobs.Signs; import java.util.ArrayList; import java.util.List; diff --git a/Signs/SignUtil.java b/com/gamingmesh/jobs/Signs/SignUtil.java similarity index 91% rename from Signs/SignUtil.java rename to com/gamingmesh/jobs/Signs/SignUtil.java index e922fc7f..d5d18e68 100644 --- a/Signs/SignUtil.java +++ b/com/gamingmesh/jobs/Signs/SignUtil.java @@ -1,4 +1,4 @@ -package Signs; +package com.gamingmesh.jobs.Signs; import java.io.File; import java.io.IOException; @@ -42,7 +42,7 @@ public class SignUtil { return; for (String category : categoriesList) { ConfigurationSection NameSection = ConfCategory.getConfigurationSection(category); - Signs.Sign newTemp = new Signs.Sign(); + com.gamingmesh.jobs.Signs.Sign newTemp = new com.gamingmesh.jobs.Signs.Sign(); newTemp.setCategory(Integer.valueOf(category)); newTemp.setWorld(NameSection.getString("World")); newTemp.setX(NameSection.getDouble("X")); @@ -75,7 +75,7 @@ public class SignUtil { if (!conf.isConfigurationSection("Signs")) conf.createSection("Signs"); - for (Signs.Sign one : Signs.GetAllSigns()) { + for (com.gamingmesh.jobs.Signs.Sign one : Signs.GetAllSigns()) { String path = "Signs." + String.valueOf(one.GetCategory()); writer.set(path + ".World", one.GetWorld()); writer.set(path + ".X", one.GetX()); @@ -99,12 +99,12 @@ public class SignUtil { } public static boolean SignUpdate(String JobName) { - List Copy = new ArrayList(Signs.GetAllSigns().size()); - for (Signs.Sign foo : Signs.GetAllSigns()) { + List Copy = new ArrayList(Signs.GetAllSigns().size()); + for (com.gamingmesh.jobs.Signs.Sign foo : Signs.GetAllSigns()) { Copy.add(foo); } int timelapse = 1; - for (Signs.Sign one : Copy) { + for (com.gamingmesh.jobs.Signs.Sign one : Copy) { String SignJobName = one.GetJobName(); if (JobName.equalsIgnoreCase(SignJobName)) { String SignsWorld = one.GetWorld(); @@ -121,7 +121,9 @@ public class SignUtil { } if (PlayerList.size() != 0) { World world = Bukkit.getWorld(SignsWorld); - Location nloc = new Location(world, SignsX, SignsY, SignsZ); + if (world == null) + continue; + Location nloc = new Location(world, SignsX, SignsY, SignsZ); Block block = nloc.getBlock(); if (!(block.getState() instanceof org.bukkit.block.Sign)) { Signs.GetAllSigns().remove(one); diff --git a/com/gamingmesh/jobs/commands/.gitignore b/com/gamingmesh/jobs/commands/.gitignore index fbce14b1..611c61f6 100644 --- a/com/gamingmesh/jobs/commands/.gitignore +++ b/com/gamingmesh/jobs/commands/.gitignore @@ -1,2 +1,3 @@ /JobCommand.class /JobsCommands.class +/JobsCommands$1.class diff --git a/com/gamingmesh/jobs/commands/JobsCommands.java b/com/gamingmesh/jobs/commands/JobsCommands.java index e9ff0b2a..59e61f8d 100644 --- a/com/gamingmesh/jobs/commands/JobsCommands.java +++ b/com/gamingmesh/jobs/commands/JobsCommands.java @@ -24,7 +24,12 @@ import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; @@ -39,6 +44,7 @@ import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.ScoreboardManager; import com.gamingmesh.jobs.Jobs; +import com.gamingmesh.jobs.JobsPlugin; import com.gamingmesh.jobs.config.ConfigManager; import com.gamingmesh.jobs.container.ActionType; import com.gamingmesh.jobs.container.Convert; @@ -47,13 +53,17 @@ import com.gamingmesh.jobs.container.JobInfo; import com.gamingmesh.jobs.container.JobItems; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; +import com.gamingmesh.jobs.container.Log; +import com.gamingmesh.jobs.container.LogAmounts; import com.gamingmesh.jobs.container.TopList; import com.gamingmesh.jobs.economy.PaymentData; import com.gamingmesh.jobs.i18n.Language; import com.gamingmesh.jobs.stuff.ChatColor; +import com.gamingmesh.jobs.stuff.Debug; import com.gamingmesh.jobs.stuff.GiveItem; import com.gamingmesh.jobs.stuff.Perm; import com.gamingmesh.jobs.stuff.Scboard; +import com.gamingmesh.jobs.stuff.Sorting; import com.gamingmesh.jobs.stuff.TranslateName; public class JobsCommands implements CommandExecutor { @@ -1014,9 +1024,9 @@ public class JobsCommands implements CommandExecutor { return true; } if (!args[0].equalsIgnoreCase("gtoplist")) - Signs.SignUtil.SignUpdate(oldjob.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(oldjob.getName()); else - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); return true; } @@ -1347,37 +1357,126 @@ public class JobsCommands implements CommandExecutor { return true; } -// @JobCommand -// public boolean log(CommandSender sender, String[] args) { -// if (args.length != 1) { -// sendUsage(sender, "log"); -// return true; -// } -// -// JobsPlayer JPlayer = Jobs.getPlayerManager().getJobsPlayer(args[0]); -// -// if (JPlayer == null) -// return true; -// -// List logList = JPlayer.getLog(); -// -// if (logList.size() == 0) -// return true; -// -// for (Log one : logList) { -// -// HashMap AmountList = one.getAmountList(); -// -// for (Entry oneMap : AmountList.entrySet()) { -// String msg = "&e" + one.getActionType().getName() + ": &6" + oneMap.getValue().getItemName() + " &ecount: &6" + oneMap.getValue().getCount() -// + " &emoney: &6" + oneMap.getValue().getMoney() + " &eexp: &6" + oneMap.getValue().getExp(); -// msg = org.bukkit.ChatColor.translateAlternateColorCodes('&', msg); -// sender.sendMessage(msg); -// } -// } -// -// return true; -// } + @JobCommand + public boolean log(CommandSender sender, String[] args) { + + if (!(sender instanceof Player) && args.length != 1) + return false; + + if (args.length != 1 && args.length != 0) { + sendUsage(sender, "log"); + return true; + } + JobsPlayer JPlayer = null; + if (args.length == 1) + JPlayer = Jobs.getPlayerManager().getJobsPlayer(args[0]); + if (args.length == 0) + JPlayer = Jobs.getPlayerManager().getJobsPlayer(sender.getName()); + + if (JPlayer == null) + return true; + + List logList = JPlayer.getLog(); + + if (logList.size() == 0) + return true; + + Map unsortMap = new HashMap(); + + for (Log one : logList) { + HashMap AmountList = one.getAmountList(); + for (Entry oneMap : AmountList.entrySet()) { + unsortMap.put(oneMap.getKey(), oneMap.getValue().getMoney()); + } + } + + unsortMap = Sorting.sortDoubleDESC(unsortMap); + int count = 0; + int max = 10; + sender.sendMessage("******************* " + JPlayer.getUserName() + " *******************"); + for (Log one : logList) { + HashMap AmountList = one.getAmountList(); + for (Entry oneSorted : unsortMap.entrySet()) { + for (Entry oneMap : AmountList.entrySet()) { + if (oneMap.getKey().equalsIgnoreCase(oneSorted.getKey())) { + count++; + String msg = "&6" + count + ". &e" + one.getActionType() + ": &6" + oneMap.getValue().getItemName() + " &ecount: &6" + oneMap.getValue() + .getCount() + " &emoney: &6" + oneMap.getValue().getMoney() + " &eexp: &6" + oneMap.getValue().getExp(); + msg = org.bukkit.ChatColor.translateAlternateColorCodes('&', msg); + sender.sendMessage(msg); + break; + } + } + if (count > max) + break; + } + if (count > max) + break; + } + sender.sendMessage("***********************************************"); + + return true; + } + + @JobCommand + public boolean glog(final CommandSender sender, String[] args) { + if (args.length != 0) { + sendUsage(sender, "glog"); + return true; + } + Bukkit.getScheduler().runTaskAsynchronously(JobsPlugin.instance, new Runnable() { + @Override + public void run() { + Map unsortMap = new HashMap(); + + Collection onlineP = Bukkit.getOnlinePlayers(); + + sender.sendMessage("Looking for players data"); + for (Player OneP : onlineP) { + + JobsPlayer JPlayer = Jobs.getPlayerManager().getJobsPlayer(OneP); + if (JPlayer == null) + continue; + List logList = JPlayer.getLog(); + if (logList.size() == 0) + continue; + + for (Log one : logList) { + HashMap AmountList = one.getAmountList(); + for (Entry oneMap : AmountList.entrySet()) { + oneMap.getValue().setUsername(OneP.getName()); + oneMap.getValue().setAction(one.getActionType()); + unsortMap.put(oneMap.getValue(), oneMap.getValue().getMoney()); + } + } + } + + unsortMap = Sorting.sortDoubleDESCByLog(unsortMap); + + int count = 0; + int max = 10; + + for (Entry one : unsortMap.entrySet()) { + LogAmounts info = one.getKey(); + String msg = "&3" + info.getUsername() + " &e" + info.getAction() + ": &6" + (info.getItemName().toString().contains(":0") ? info.getItemName() + .toString().replace(":0", "") : info.getItemName()) + " &ecount: &6" + info.getCount() + " &emoney: &6" + info.getMoney() + " &eexp: &6" + info + .getExp(); + msg = org.bukkit.ChatColor.translateAlternateColorCodes('&', msg); + sender.sendMessage(msg); + count++; + + if (count > max) + break; + } + if (unsortMap.size() == 0) { + sender.sendMessage("No data found"); + } + + return; + } + }); + return true; + } /** * Displays info about a job diff --git a/com/gamingmesh/jobs/config/JobConfig.java b/com/gamingmesh/jobs/config/JobConfig.java index a87168a2..1f4131d4 100644 --- a/com/gamingmesh/jobs/config/JobConfig.java +++ b/com/gamingmesh/jobs/config/JobConfig.java @@ -40,6 +40,7 @@ import com.gamingmesh.jobs.container.ActionType; import com.gamingmesh.jobs.container.DisplayMethod; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobCommands; +import com.gamingmesh.jobs.container.JobConditions; import com.gamingmesh.jobs.container.JobInfo; import com.gamingmesh.jobs.container.JobItems; import com.gamingmesh.jobs.container.JobPermission; @@ -47,380 +48,407 @@ import com.gamingmesh.jobs.resources.jfep.Parser; import com.gamingmesh.jobs.stuff.ChatColor; public class JobConfig { - private JobsPlugin plugin; + private JobsPlugin plugin; - public JobConfig(JobsPlugin plugin) { - this.plugin = plugin; + public JobConfig(JobsPlugin plugin) { + this.plugin = plugin; + } + + public void reload() throws IOException { + // job settings + loadJobSettings(); + } + + /** + * Method to load the jobs configuration + * + * loads from Jobs/jobConfig.yml + * @throws IOException + */ + @SuppressWarnings("deprecation") + private void loadJobSettings() throws IOException { + File f = new File(plugin.getDataFolder(), "jobConfig.yml"); + InputStreamReader s = new InputStreamReader(new FileInputStream(f), "UTF-8"); + + ArrayList jobs = new ArrayList(); + Jobs.setJobs(jobs); + Jobs.setNoneJob(null); + if (!f.exists()) { + try { + f.createNewFile(); + } catch (IOException e) { + Jobs.getPluginLogger().severe("Unable to create jobConfig.yml! No jobs were loaded!"); + s.close(); + return; + } } - - public void reload() throws IOException { - // job settings - loadJobSettings(); + YamlConfiguration conf = new YamlConfiguration(); + conf.options().pathSeparator('/'); + try { + conf.load(s); + s.close(); + } catch (Exception e) { + Bukkit.getServer().getLogger().severe("==================== Jobs ===================="); + Bukkit.getServer().getLogger().severe("Unable to load jobConfig.yml!"); + Bukkit.getServer().getLogger().severe("Check your config for formatting issues!"); + Bukkit.getServer().getLogger().severe("No jobs were loaded!"); + Bukkit.getServer().getLogger().severe("Error: " + e.getMessage()); + Bukkit.getServer().getLogger().severe("=============================================="); + return; } + //conf.options().header(new StringBuilder().append("Jobs configuration.").append(System.getProperty("line.separator")).append(System.getProperty("line.separator")).append("Stores information about each job.").append(System.getProperty("line.separator")).append(System.getProperty("line.separator")).append("For example configurations, visit http://dev.bukkit.org/bukkit-plugins/jobs-reborn/.").append(System.getProperty("line.separator")).toString()); - /** - * Method to load the jobs configuration - * - * loads from Jobs/jobConfig.yml - * @throws IOException - */ - @SuppressWarnings("deprecation") - private void loadJobSettings() throws IOException { - File f = new File(plugin.getDataFolder(), "jobConfig.yml"); - InputStreamReader s = new InputStreamReader(new FileInputStream(f), "UTF-8"); + ConfigurationSection jobsSection = conf.getConfigurationSection("Jobs"); + //if (jobsSection == null) { + // jobsSection = conf.createSection("Jobs"); + //} + for (String jobKey : jobsSection.getKeys(false)) { + ConfigurationSection jobSection = jobsSection.getConfigurationSection(jobKey); + String jobName = jobSection.getString("fullname"); - ArrayList jobs = new ArrayList(); - Jobs.setJobs(jobs); - Jobs.setNoneJob(null); - if (!f.exists()) { - try { - f.createNewFile(); - } catch (IOException e) { - Jobs.getPluginLogger().severe("Unable to create jobConfig.yml! No jobs were loaded!"); - s.close(); - return; - } + // Translating unicode + jobName = StringEscapeUtils.unescapeJava(jobName); + + if (jobName == null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid fullname property. Skipping job!"); + continue; + } + + int maxLevel = jobSection.getInt("max-level", 0); + if (maxLevel < 0) + maxLevel = 0; + + int vipmaxLevel = jobSection.getInt("vip-max-level", 0); + if (vipmaxLevel < 0) + vipmaxLevel = 0; + + Integer maxSlots = jobSection.getInt("slots", 0); + if (maxSlots.intValue() <= 0) { + maxSlots = null; + } + + String jobShortName = jobSection.getString("shortname"); + if (jobShortName == null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " is missing the shortname property. Skipping job!"); + continue; + } + + String description = org.bukkit.ChatColor.translateAlternateColorCodes('&', jobSection.getString("description", "")); + + ChatColor color = ChatColor.WHITE; + if (jobSection.contains("ChatColour")) { + color = ChatColor.matchColor(jobSection.getString("ChatColour", "")); + if (color == null) { + color = ChatColor.WHITE; + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid ChatColour property. Defaulting to WHITE!"); } - YamlConfiguration conf = new YamlConfiguration(); - conf.options().pathSeparator('/'); - try { - conf.load(s); - s.close(); - } catch (Exception e) { - Bukkit.getServer().getLogger().severe("==================== Jobs ===================="); - Bukkit.getServer().getLogger().severe("Unable to load jobConfig.yml!"); - Bukkit.getServer().getLogger().severe("Check your config for formatting issues!"); - Bukkit.getServer().getLogger().severe("No jobs were loaded!"); - Bukkit.getServer().getLogger().severe("Error: " + e.getMessage()); - Bukkit.getServer().getLogger().severe("=============================================="); - return; + } + DisplayMethod displayMethod = DisplayMethod.matchMethod(jobSection.getString("chat-display", "")); + if (displayMethod == null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid chat-display property. Defaulting to None!"); + displayMethod = DisplayMethod.NONE; + } + + Parser maxExpEquation; + String maxExpEquationInput = jobSection.getString("leveling-progression-equation"); + try { + maxExpEquation = new Parser(maxExpEquationInput); + // test equation + maxExpEquation.setVariable("numjobs", 1); + maxExpEquation.setVariable("joblevel", 1); + maxExpEquation.getValue(); + } catch (Exception e) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid leveling-progression-equation property. Skipping job!"); + continue; + } + + Parser incomeEquation; + String incomeEquationInput = jobSection.getString("income-progression-equation"); + try { + incomeEquation = new Parser(incomeEquationInput); + // test equation + incomeEquation.setVariable("numjobs", 1); + incomeEquation.setVariable("joblevel", 1); + incomeEquation.setVariable("baseincome", 1); + incomeEquation.getValue(); + } catch (Exception e) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid income-progression-equation property. Skipping job!"); + continue; + } + + Parser expEquation; + String expEquationInput = jobSection.getString("experience-progression-equation"); + try { + expEquation = new Parser(expEquationInput); + // test equation + expEquation.setVariable("numjobs", 1); + expEquation.setVariable("joblevel", 1); + expEquation.setVariable("baseexperience", 1); + expEquation.getValue(); + } catch (Exception e) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid experience-progression-equation property. Skipping job!"); + continue; + } + + // Gui item + ItemStack GUIitem = new ItemStack(Material.getMaterial(35), 1, (byte) 13); + if (jobSection.contains("Gui")) { + ConfigurationSection guiSection = jobSection.getConfigurationSection("Gui"); + if (guiSection.contains("Id") && guiSection.contains("Data") && guiSection.isInt("Id") && guiSection.isInt("Data")) { + GUIitem = new ItemStack(Material.getMaterial(guiSection.getInt("Id")), 1, (byte) guiSection.getInt("Data")); + } else + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid Gui property. Please fix this if you want to use it!"); + } + + // Permissions + ArrayList jobPermissions = new ArrayList(); + ConfigurationSection permissionsSection = jobSection.getConfigurationSection("permissions"); + if (permissionsSection != null) { + for (String permissionKey : permissionsSection.getKeys(false)) { + ConfigurationSection permissionSection = permissionsSection.getConfigurationSection(permissionKey); + + String node = permissionKey.toLowerCase(); + if (permissionSection == null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid permission key" + permissionKey + "!"); + continue; + } + boolean value = permissionSection.getBoolean("value", true); + int levelRequirement = permissionSection.getInt("level", 0); + jobPermissions.add(new JobPermission(node, value, levelRequirement)); } - //conf.options().header(new StringBuilder().append("Jobs configuration.").append(System.getProperty("line.separator")).append(System.getProperty("line.separator")).append("Stores information about each job.").append(System.getProperty("line.separator")).append(System.getProperty("line.separator")).append("For example configurations, visit http://dev.bukkit.org/bukkit-plugins/jobs-reborn/.").append(System.getProperty("line.separator")).toString()); + } - ConfigurationSection jobsSection = conf.getConfigurationSection("Jobs"); - //if (jobsSection == null) { - // jobsSection = conf.createSection("Jobs"); - //} - for (String jobKey : jobsSection.getKeys(false)) { - ConfigurationSection jobSection = jobsSection.getConfigurationSection(jobKey); - String jobName = jobSection.getString("fullname"); + // Conditions + ArrayList jobConditions = new ArrayList(); + ConfigurationSection conditionsSection = jobSection.getConfigurationSection("conditions"); + if (conditionsSection != null) { + for (String ConditionKey : conditionsSection.getKeys(false)) { + ConfigurationSection permissionSection = conditionsSection.getConfigurationSection(ConditionKey); - // Translating unicode - jobName = StringEscapeUtils.unescapeJava(jobName); + String node = ConditionKey.toLowerCase(); + if (permissionSection == null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid condition key " + ConditionKey + "!"); + continue; + } + if (!permissionSection.contains("requires") || !permissionSection.contains("perform")) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid condition requirement " + ConditionKey + "!"); + continue; + } + List requires = permissionSection.getStringList("requires"); + List perform = permissionSection.getStringList("perform"); - if (jobName == null) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid fullname property. Skipping job!"); - continue; - } - - int maxLevel = jobSection.getInt("max-level", 0); - if (maxLevel < 0) - maxLevel = 0; - - int vipmaxLevel = jobSection.getInt("vip-max-level", 0); - if (vipmaxLevel < 0) - vipmaxLevel = 0; - - Integer maxSlots = jobSection.getInt("slots", 0); - if (maxSlots.intValue() <= 0) { - maxSlots = null; - } - - String jobShortName = jobSection.getString("shortname"); - if (jobShortName == null) { - Jobs.getPluginLogger().warning("Job " + jobKey + " is missing the shortname property. Skipping job!"); - continue; - } - - String description = org.bukkit.ChatColor.translateAlternateColorCodes('&', jobSection.getString("description", "")); - - ChatColor color = ChatColor.WHITE; - if (jobSection.contains("ChatColour")) { - color = ChatColor.matchColor(jobSection.getString("ChatColour", "")); - if (color == null) { - color = ChatColor.WHITE; - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid ChatColour property. Defaulting to WHITE!"); - } - } - DisplayMethod displayMethod = DisplayMethod.matchMethod(jobSection.getString("chat-display", "")); - if (displayMethod == null) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid chat-display property. Defaulting to None!"); - displayMethod = DisplayMethod.NONE; - } - - Parser maxExpEquation; - String maxExpEquationInput = jobSection.getString("leveling-progression-equation"); - try { - maxExpEquation = new Parser(maxExpEquationInput); - // test equation - maxExpEquation.setVariable("numjobs", 1); - maxExpEquation.setVariable("joblevel", 1); - maxExpEquation.getValue(); - } catch (Exception e) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid leveling-progression-equation property. Skipping job!"); - continue; - } - - Parser incomeEquation; - String incomeEquationInput = jobSection.getString("income-progression-equation"); - try { - incomeEquation = new Parser(incomeEquationInput); - // test equation - incomeEquation.setVariable("numjobs", 1); - incomeEquation.setVariable("joblevel", 1); - incomeEquation.setVariable("baseincome", 1); - incomeEquation.getValue(); - } catch (Exception e) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid income-progression-equation property. Skipping job!"); - continue; - } - - Parser expEquation; - String expEquationInput = jobSection.getString("experience-progression-equation"); - try { - expEquation = new Parser(expEquationInput); - // test equation - expEquation.setVariable("numjobs", 1); - expEquation.setVariable("joblevel", 1); - expEquation.setVariable("baseexperience", 1); - expEquation.getValue(); - } catch (Exception e) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid experience-progression-equation property. Skipping job!"); - continue; - } - - // Gui item - ItemStack GUIitem = new ItemStack(Material.getMaterial(35), 1, (byte) 13); - if (jobSection.contains("Gui")) { - ConfigurationSection guiSection = jobSection.getConfigurationSection("Gui"); - if (guiSection.contains("Id") && guiSection.contains("Data") && guiSection.isInt("Id") && guiSection.isInt("Data")) { - GUIitem = new ItemStack(Material.getMaterial(guiSection.getInt("Id")), 1, (byte) guiSection.getInt("Data")); - } else - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid Gui property. Please fix this if you want to use it!"); - } - - // Permissions - ArrayList jobPermissions = new ArrayList(); - ConfigurationSection permissionsSection = jobSection.getConfigurationSection("permissions"); - if (permissionsSection != null) { - for (String permissionKey : permissionsSection.getKeys(false)) { - ConfigurationSection permissionSection = permissionsSection.getConfigurationSection(permissionKey); - - String node = permissionKey.toLowerCase(); - if (permissionSection == null) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid permission key" + permissionKey + "!"); - continue; - } - boolean value = permissionSection.getBoolean("value", true); - int levelRequirement = permissionSection.getInt("level", 0); - jobPermissions.add(new JobPermission(node, value, levelRequirement)); - } - } - - // Command on leave - List JobsCommandOnLeave = new ArrayList(); - if (jobSection.isList("cmd-on-leave")) { - JobsCommandOnLeave = jobSection.getStringList("cmd-on-leave"); - } - - // Command on join - List JobsCommandOnJoin = new ArrayList(); - if (jobSection.isList("cmd-on-join")) { - JobsCommandOnJoin = jobSection.getStringList("cmd-on-join"); - } - - // Commands - ArrayList jobCommand = new ArrayList(); - ConfigurationSection commandsSection = jobSection.getConfigurationSection("commands"); - if (commandsSection != null) { - for (String commandKey : commandsSection.getKeys(false)) { - ConfigurationSection commandSection = commandsSection.getConfigurationSection(commandKey); - - String node = commandKey.toLowerCase(); - if (commandSection == null) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid command key" + commandKey + "!"); - continue; - } - String command = commandSection.getString("command"); - int levelFrom = commandSection.getInt("levelFrom"); - int levelUntil = commandSection.getInt("levelUntil"); - jobCommand.add(new JobCommands(node, command, levelFrom, levelUntil)); - } - } - - // Items - ArrayList jobItems = new ArrayList(); - ConfigurationSection itemsSection = jobSection.getConfigurationSection("items"); - if (itemsSection != null) { - for (String itemKey : itemsSection.getKeys(false)) { - ConfigurationSection itemSection = itemsSection.getConfigurationSection(itemKey); - - String node = itemKey.toLowerCase(); - if (itemSection == null) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid item key " + itemKey + "!"); - continue; - } - int id = itemSection.getInt("id"); - String name = itemSection.getString("name"); - - List lore = new ArrayList(); - for (String eachLine : itemSection.getStringList("lore")) { - lore.add(org.bukkit.ChatColor.translateAlternateColorCodes('&', eachLine)); - } - - List enchants = new ArrayList(); - if (itemSection.getStringList("enchants") != null) - for (String eachLine : itemSection.getStringList("enchants")) { - enchants.add(eachLine); - } - - Double moneyBoost = itemSection.getDouble("moneyBoost"); - Double expBoost = itemSection.getDouble("expBoost"); - jobItems.add(new JobItems(node, id, name, lore, enchants, moneyBoost, expBoost)); - } - } - - Job job = new Job(jobName, jobShortName, description, color, maxExpEquation, displayMethod, maxLevel, vipmaxLevel, maxSlots, jobPermissions, jobCommand, jobItems, JobsCommandOnJoin, JobsCommandOnLeave, GUIitem); - - for (ActionType actionType : ActionType.values()) { - ConfigurationSection typeSection = jobSection.getConfigurationSection(actionType.getName()); - ArrayList jobInfo = new ArrayList(); - if (typeSection != null) { - for (String key : typeSection.getKeys(false)) { - ConfigurationSection section = typeSection.getConfigurationSection(key); - String myKey = key; - String type = null; - String subType = ""; - String meta = ""; - int id = 0; - - if (myKey.contains("-")) { - // uses subType - subType = ":" + myKey.split("-")[1]; - meta = myKey.split("-")[1]; - myKey = myKey.split("-")[0]; - } - - Material material = Material.matchMaterial(myKey); - - if (material == null) - material = Material.getMaterial(myKey.replace(" ", "_").toUpperCase()); - - if (material == null) { - // try integer method - Integer matId = null; - try { - matId = Integer.valueOf(myKey); - } catch (NumberFormatException e) {} - if (matId != null) { - material = Material.getMaterial(matId); - if (material != null) { - Jobs.getPluginLogger().warning("Job " + jobKey + " " + actionType.getName() + " is using ID: " + key + "!"); - Jobs.getPluginLogger().warning("Please use the Material name instead: " + material.toString() + "!"); - } - } - } - - if (material != null) { - // Break and Place actions MUST be blocks - if (actionType == ActionType.BREAK || actionType == ActionType.PLACE) { - if (!material.isBlock()) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid " + actionType.getName() + " type property: " + key + "! Material must be a block!"); - continue; - } - } - // START HACK - /* - * Historically, GLOWING_REDSTONE_ORE would ONLY work as REDSTONE_ORE, and putting - * GLOWING_REDSTONE_ORE in the configuration would not work. Unfortunately, this is - * completely backwards and wrong. - * - * To maintain backwards compatibility, all instances of REDSTONE_ORE should normalize - * to GLOWING_REDSTONE_ORE, and warn the user to change their configuration. In the - * future this hack may be removed and anybody using REDSTONE_ORE will have their - * configurations broken. - */ - if (material == Material.REDSTONE_ORE && actionType == ActionType.BREAK) { - Jobs.getPluginLogger().warning("Job " + jobKey + " is using REDSTONE_ORE instead of GLOWING_REDSTONE_ORE."); - Jobs.getPluginLogger().warning("Automatically changing block to GLOWING_REDSTONE_ORE. Please update your configuration."); - Jobs.getPluginLogger().warning("In vanilla minecraft, REDSTONE_ORE changes to GLOWING_REDSTONE_ORE when interacted with."); - Jobs.getPluginLogger().warning("In the future, Jobs using REDSTONE_ORE instead of GLOWING_REDSTONE_ORE may fail to work correctly."); - material = Material.GLOWING_REDSTONE_ORE; - } - // END HACK - - type = material.toString(); - id = material.getId(); - } else if (actionType == ActionType.KILL || actionType == ActionType.TAME || actionType == ActionType.BREED || actionType == ActionType.MILK) { - // check entities - EntityType entity = EntityType.fromName(key); - if (entity == null) { - try { - entity = EntityType.valueOf(key.toUpperCase()); - } catch (IllegalArgumentException e) {} - } - - if (entity != null && entity.isAlive()) { - type = entity.toString(); - - id = entity.getTypeId(); - } - - // Just to recognize wither skeleton - if (key.equalsIgnoreCase("WitherSkeleton")) { - type = "WitherSkeleton"; - id = 51; - meta = "1"; - } - - // Just to recognize Zombie Villager - if (key.equalsIgnoreCase("ZombieVillager")) { - type = "ZombieVillager"; - id = 54; - meta = "1"; - } - - // Just to recognize Elder Guardian - if (key.equalsIgnoreCase("ElderGuardian")) { - type = "ElderGuardian"; - id = 68; - meta = "1"; - } - - } else if (actionType == ActionType.ENCHANT && material == null) { - Enchantment enchant = Enchantment.getByName(myKey); - if (enchant != null) - id = enchant.getId(); - type = myKey; - } else if (actionType == ActionType.CUSTOMKILL || actionType == ActionType.SHEAR) { - - type = myKey; - } - - if (type == null) { - Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid " + actionType.getName() + " type property: " + key + "!"); - continue; - } - - double income = section.getDouble("income", 0.0); - double experience = section.getDouble("experience", 0.0); - - jobInfo.add(new JobInfo(actionType, id, meta, type + subType, income, incomeEquation, experience, expEquation)); - } - } - job.setJobInfo(actionType, jobInfo); - } - - if (jobKey.equalsIgnoreCase("none")) { - Jobs.setNoneJob(job); - } else { - jobs.add(job); - } + jobConditions.add(new JobConditions(node, requires, perform)); } - //try { - // conf.save(f); - //} catch (IOException e) { - // e.printStackTrace(); - //} + } + + // Command on leave + List JobsCommandOnLeave = new ArrayList(); + if (jobSection.isList("cmd-on-leave")) { + JobsCommandOnLeave = jobSection.getStringList("cmd-on-leave"); + } + + // Command on join + List JobsCommandOnJoin = new ArrayList(); + if (jobSection.isList("cmd-on-join")) { + JobsCommandOnJoin = jobSection.getStringList("cmd-on-join"); + } + + // Commands + ArrayList jobCommand = new ArrayList(); + ConfigurationSection commandsSection = jobSection.getConfigurationSection("commands"); + if (commandsSection != null) { + for (String commandKey : commandsSection.getKeys(false)) { + ConfigurationSection commandSection = commandsSection.getConfigurationSection(commandKey); + + String node = commandKey.toLowerCase(); + if (commandSection == null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid command key" + commandKey + "!"); + continue; + } + String command = commandSection.getString("command"); + int levelFrom = commandSection.getInt("levelFrom"); + int levelUntil = commandSection.getInt("levelUntil"); + jobCommand.add(new JobCommands(node, command, levelFrom, levelUntil)); + } + } + + // Items + ArrayList jobItems = new ArrayList(); + ConfigurationSection itemsSection = jobSection.getConfigurationSection("items"); + if (itemsSection != null) { + for (String itemKey : itemsSection.getKeys(false)) { + ConfigurationSection itemSection = itemsSection.getConfigurationSection(itemKey); + + String node = itemKey.toLowerCase(); + if (itemSection == null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid item key " + itemKey + "!"); + continue; + } + int id = itemSection.getInt("id"); + String name = itemSection.getString("name"); + + List lore = new ArrayList(); + for (String eachLine : itemSection.getStringList("lore")) { + lore.add(org.bukkit.ChatColor.translateAlternateColorCodes('&', eachLine)); + } + + List enchants = new ArrayList(); + if (itemSection.getStringList("enchants") != null) + for (String eachLine : itemSection.getStringList("enchants")) { + enchants.add(eachLine); + } + + Double moneyBoost = itemSection.getDouble("moneyBoost"); + Double expBoost = itemSection.getDouble("expBoost"); + jobItems.add(new JobItems(node, id, name, lore, enchants, moneyBoost, expBoost)); + } + } + + Job job = new Job(jobName, jobShortName, description, color, maxExpEquation, displayMethod, maxLevel, vipmaxLevel, maxSlots, jobPermissions, jobCommand, + jobConditions, jobItems, JobsCommandOnJoin, JobsCommandOnLeave, GUIitem); + + for (ActionType actionType : ActionType.values()) { + ConfigurationSection typeSection = jobSection.getConfigurationSection(actionType.getName()); + ArrayList jobInfo = new ArrayList(); + if (typeSection != null) { + for (String key : typeSection.getKeys(false)) { + ConfigurationSection section = typeSection.getConfigurationSection(key); + String myKey = key; + String type = null; + String subType = ""; + String meta = ""; + int id = 0; + + if (myKey.contains("-")) { + // uses subType + subType = ":" + myKey.split("-")[1]; + meta = myKey.split("-")[1]; + myKey = myKey.split("-")[0]; + } + + Material material = Material.matchMaterial(myKey); + + if (material == null) + material = Material.getMaterial(myKey.replace(" ", "_").toUpperCase()); + + if (material == null) { + // try integer method + Integer matId = null; + try { + matId = Integer.valueOf(myKey); + } catch (NumberFormatException e) { + } + if (matId != null) { + material = Material.getMaterial(matId); + if (material != null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " " + actionType.getName() + " is using ID: " + key + "!"); + Jobs.getPluginLogger().warning("Please use the Material name instead: " + material.toString() + "!"); + } + } + } + + if (material != null) { + // Break and Place actions MUST be blocks + if (actionType == ActionType.BREAK || actionType == ActionType.PLACE) { + if (!material.isBlock()) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid " + actionType.getName() + " type property: " + key + + "! Material must be a block!"); + continue; + } + } + // START HACK + /* + * Historically, GLOWING_REDSTONE_ORE would ONLY work as REDSTONE_ORE, and putting + * GLOWING_REDSTONE_ORE in the configuration would not work. Unfortunately, this is + * completely backwards and wrong. + * + * To maintain backwards compatibility, all instances of REDSTONE_ORE should normalize + * to GLOWING_REDSTONE_ORE, and warn the user to change their configuration. In the + * future this hack may be removed and anybody using REDSTONE_ORE will have their + * configurations broken. + */ + if (material == Material.REDSTONE_ORE && actionType == ActionType.BREAK) { + Jobs.getPluginLogger().warning("Job " + jobKey + " is using REDSTONE_ORE instead of GLOWING_REDSTONE_ORE."); + Jobs.getPluginLogger().warning("Automatically changing block to GLOWING_REDSTONE_ORE. Please update your configuration."); + Jobs.getPluginLogger().warning("In vanilla minecraft, REDSTONE_ORE changes to GLOWING_REDSTONE_ORE when interacted with."); + Jobs.getPluginLogger().warning("In the future, Jobs using REDSTONE_ORE instead of GLOWING_REDSTONE_ORE may fail to work correctly."); + material = Material.GLOWING_REDSTONE_ORE; + } + // END HACK + + type = material.toString(); + id = material.getId(); + } else if (actionType == ActionType.KILL || actionType == ActionType.TAME || actionType == ActionType.BREED || actionType == ActionType.MILK) { + // check entities + EntityType entity = EntityType.fromName(key); + if (entity == null) { + try { + entity = EntityType.valueOf(key.toUpperCase()); + } catch (IllegalArgumentException e) { + } + } + + if (entity != null && entity.isAlive()) { + type = entity.toString(); + + id = entity.getTypeId(); + } + + // Just to recognize wither skeleton + if (key.equalsIgnoreCase("WitherSkeleton")) { + type = "WitherSkeleton"; + id = 51; + meta = "1"; + } + + // Just to recognize Zombie Villager + if (key.equalsIgnoreCase("ZombieVillager")) { + type = "ZombieVillager"; + id = 54; + meta = "1"; + } + + // Just to recognize Elder Guardian + if (key.equalsIgnoreCase("ElderGuardian")) { + type = "ElderGuardian"; + id = 68; + meta = "1"; + } + + } else if (actionType == ActionType.ENCHANT && material == null) { + Enchantment enchant = Enchantment.getByName(myKey); + if (enchant != null) + id = enchant.getId(); + type = myKey; + } else if (actionType == ActionType.CUSTOMKILL || actionType == ActionType.SHEAR) { + + type = myKey; + } + + if (type == null) { + Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid " + actionType.getName() + " type property: " + key + "!"); + continue; + } + + double income = section.getDouble("income", 0.0); + double experience = section.getDouble("experience", 0.0); + + jobInfo.add(new JobInfo(actionType, id, meta, type + subType, income, incomeEquation, experience, expEquation)); + } + } + job.setJobInfo(actionType, jobInfo); + } + + if (jobKey.equalsIgnoreCase("none")) { + Jobs.setNoneJob(job); + } else { + jobs.add(job); + } } + //try { + // conf.save(f); + //} catch (IOException e) { + // e.printStackTrace(); + //} + } } diff --git a/com/gamingmesh/jobs/config/JobsConfiguration.java b/com/gamingmesh/jobs/config/JobsConfiguration.java index a6dca791..e6a2dfa4 100644 --- a/com/gamingmesh/jobs/config/JobsConfiguration.java +++ b/com/gamingmesh/jobs/config/JobsConfiguration.java @@ -260,7 +260,7 @@ public class JobsConfiguration { // Item/Block/mobs name list loadItemList(); // Item/Block/mobs name list - Signs.SignUtil.LoadSigns(); + com.gamingmesh.jobs.Signs.SignUtil.LoadSigns(); // loadScheduler(); } @@ -549,7 +549,8 @@ public class JobsConfiguration { "0.2 means 20% of original price"); TreeFellerMultiplier = getDouble("ExploitProtections.McMMO.TreeFellerMultiplier", 0.2, config, writer); - writer.addComment("ExploitProtections.Spawner.PreventSlimeSplit", "Prevent slime spliting when they are from spawner","Protects agains exploiting as new splited slimes is treated as naturaly spawned and not from spawner"); + writer.addComment("ExploitProtections.Spawner.PreventSlimeSplit", "Prevent slime spliting when they are from spawner", + "Protects agains exploiting as new splited slimes is treated as naturaly spawned and not from spawner"); PreventSlimeSplit = getBoolean("ExploitProtections.Spawner.PreventSlimeSplit", true, config, writer); writer.addComment("ExploitProtections.Spawner.PreventMagmaCubeSplit", "Prevent magmacube spliting when they are from spawner"); PreventMagmaCubeSplit = getBoolean("ExploitProtections.Spawner.PreventMagmaCubeSplit", true, config, writer); @@ -932,22 +933,28 @@ public class JobsConfiguration { if (!path.contains("Money") || !path.isDouble("Money")) continue; + sched.setDays(path.getStringList("Days")); + sched.setJobs(path.getStringList("Jobs")); + sched.setFrom(Integer.valueOf(path.getString("From").replace(":", ""))); + sched.setUntil(Integer.valueOf(path.getString("Until").replace(":", ""))); + if (path.contains("MessageOnStart") && path.isList("MessageOnStart")) - sched.setMessageOnStart(path.getStringList("MessageOnStart")); + sched.setMessageOnStart(path.getStringList("MessageOnStart"), path.getString("From"), path.getString("Until")); if (path.contains("BroadcastOnStart")) sched.setBroadcastOnStart(path.getBoolean("BroadcastOnStart")); if (path.contains("MessageOnStop") && path.isList("MessageOnStop")) - sched.setMessageOnStop(path.getStringList("MessageOnStop")); + sched.setMessageOnStop(path.getStringList("MessageOnStop"), path.getString("From"), path.getString("Until")); if (path.contains("BroadcastOnStop")) sched.setBroadcastOnStop(path.getBoolean("BroadcastOnStop")); - sched.setDays(path.getStringList("Days")); - sched.setJobs(path.getStringList("Jobs")); - sched.setFrom(Integer.valueOf(path.getString("From").replace(":", ""))); - sched.setUntil(Integer.valueOf(path.getString("Until").replace(":", ""))); + if (path.contains("BroadcastInterval")) + sched.setBroadcastInterval(path.getInt("BroadcastInterval")); + + if (path.contains("BroadcastMessage") && path.isList("BroadcastMessage")) + sched.setMessageToBroadcast(path.getStringList("BroadcastMessage"), path.getString("From"), path.getString("Until")); sched.setExpBoost(path.getDouble("Exp")); sched.setMoneyBoost(path.getDouble("Money")); diff --git a/com/gamingmesh/jobs/container/.gitignore b/com/gamingmesh/jobs/container/.gitignore index 23899eb3..05ff95db 100644 --- a/com/gamingmesh/jobs/container/.gitignore +++ b/com/gamingmesh/jobs/container/.gitignore @@ -20,3 +20,4 @@ /Schedule.class /Log.class /LogAmounts.class +/JobConditions.class diff --git a/com/gamingmesh/jobs/container/Job.java b/com/gamingmesh/jobs/container/Job.java index 1ae86ca2..61ce78f2 100644 --- a/com/gamingmesh/jobs/container/Job.java +++ b/com/gamingmesh/jobs/container/Job.java @@ -38,6 +38,8 @@ public class Job { private List jobPermissions; // commands private List jobCommands; + // conditions + private List jobConditions; // items private List jobItems; // job name @@ -65,7 +67,7 @@ public class Job { // Item for GUI private ItemStack GUIitem; - private int totalPlayers = 0; + private int totalPlayers = -1; private double bonus = 0.0; private double ExpBoost = 1.0; @@ -88,8 +90,9 @@ public class Job { * @param jobItems - items with boost * @param CmdOnJoin - commands performed on player join * @param CmdOnLeave - commands performed on player leave + * @param jobConditions - jobs conditions */ - public Job(String jobName, String jobShortName, String description, ChatColor jobColour, Parser maxExpEquation, DisplayMethod displayMethod, int maxLevel, int vipmaxLevel, Integer maxSlots, List jobPermissions, List jobCommands, List jobItems, List CmdOnJoin, List CmdOnLeave, ItemStack GUIitem) { + public Job(String jobName, String jobShortName, String description, ChatColor jobColour, Parser maxExpEquation, DisplayMethod displayMethod, int maxLevel, int vipmaxLevel, Integer maxSlots, List jobPermissions, List jobCommands, List jobConditions, List jobItems, List CmdOnJoin, List CmdOnLeave, ItemStack GUIitem) { this.jobName = jobName; this.jobShortName = jobShortName; this.description = description; @@ -101,6 +104,7 @@ public class Job { this.maxSlots = maxSlots; this.jobPermissions = jobPermissions; this.jobCommands = jobCommands; + this.jobConditions = jobConditions; this.jobItems = jobItems; this.CmdOnJoin = CmdOnJoin; this.CmdOnLeave = CmdOnLeave; @@ -124,7 +128,7 @@ public class Job { } public int getTotalPlayers() { - if (this.totalPlayers == 0) { + if (this.totalPlayers == -1) { this.totalPlayers = Jobs.getJobsDAO().getTotalPlayerAmountByJobName(this.jobName); updateBonus(); } @@ -335,6 +339,13 @@ public class Job { public List getCommands() { return Collections.unmodifiableList(jobCommands); } + /** + * Get the conditions for this job + * @return Conditions for this job + */ + public List getConditions() { + return Collections.unmodifiableList(jobConditions); + } /** * Get the item nodes for this job diff --git a/com/gamingmesh/jobs/container/JobConditions.java b/com/gamingmesh/jobs/container/JobConditions.java new file mode 100644 index 00000000..bc0e8bba --- /dev/null +++ b/com/gamingmesh/jobs/container/JobConditions.java @@ -0,0 +1,45 @@ +/** + * Jobs Plugin for Bukkit + * Copyright (C) 2011 Zak Ford + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.gamingmesh.jobs.container; + +import java.util.List; + +public class JobConditions { + private String node; + private List requires; + private List perform; + + public JobConditions(String node, List requires, List perform) { + this.node = node; + this.requires = requires; + this.perform = perform; + } + + public String getNode() { + return node; + } + + public List getRequires() { + return requires; + } + + public List getPerform() { + return perform; + } +} diff --git a/com/gamingmesh/jobs/container/JobsPlayer.java b/com/gamingmesh/jobs/container/JobsPlayer.java index 23c4b55b..9c7411dc 100644 --- a/com/gamingmesh/jobs/container/JobsPlayer.java +++ b/com/gamingmesh/jobs/container/JobsPlayer.java @@ -52,7 +52,7 @@ public class JobsPlayer { // save lock public final Object saveLock = new Object(); - + // log private List logList = new ArrayList(); @@ -87,11 +87,15 @@ public class JobsPlayer { } return jPlayer; } - + + public static void loadLogFromDao(JobsPlayer jPlayer) { + Jobs.getJobsDAO().loadLog(jPlayer); + } + public List getLog() { return this.logList; } - + /** * Get the player * @return the player @@ -473,6 +477,7 @@ public class JobsPlayer { synchronized (saveLock) { if (!isSaved()) { dao.save(this); + dao.saveLog(this); setSaved(true); } } diff --git a/com/gamingmesh/jobs/container/Log.java b/com/gamingmesh/jobs/container/Log.java new file mode 100644 index 00000000..707b0cfe --- /dev/null +++ b/com/gamingmesh/jobs/container/Log.java @@ -0,0 +1,89 @@ +package com.gamingmesh.jobs.container; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; + +import com.gamingmesh.jobs.stuff.TimeManage; + +public final class Log { + private String action; + private int day; + private HashMap amountMap = new HashMap(); + + public Log(String action) { + this.action = action; + setDate(); + } + + public String getActionType() { + return this.action; + } + + public void add(String item, double money, double exp) { + if (!this.amountMap.containsKey(item)) { + LogAmounts LAmount = new LogAmounts(item); + LAmount.addCount(); + LAmount.addMoney(money); + LAmount.addExp(exp); + this.amountMap.put(item, LAmount); + } else { + LogAmounts LAmount = this.amountMap.get(item); + LAmount.addCount(); + LAmount.addMoney(money); + LAmount.addExp(exp); + this.amountMap.put(item, LAmount); + } + } + + public void add(String item, int count, double money, double exp) { + if (!this.amountMap.containsKey(item)) { + LogAmounts LAmount = new LogAmounts(item); + LAmount.setCount(count); + LAmount.setNewEntry(false); + LAmount.addMoney(money); + LAmount.addExp(exp); + this.amountMap.put(item, LAmount); + } else { + LogAmounts LAmount = this.amountMap.get(item); + LAmount.setCount(count); + LAmount.setNewEntry(false); + LAmount.addMoney(money); + LAmount.addExp(exp); + this.amountMap.put(item, LAmount); + } + } + + public void setDate() { + this.day = TimeManage.timeInInt(); + } + + public int getDate() { + return this.day; + } + + public HashMap getAmountList() { + return this.amountMap; + } + + public int getCount(String item) { + if (this.amountMap.containsKey(item)) + return this.amountMap.get(item).getCount(); + else + return 0; + } + + public double getMoney(String item) { + if (this.amountMap.containsKey(item)) + return this.amountMap.get(item).getMoney(); + else + return 0; + } + + public double getExp(String item) { + if (this.amountMap.containsKey(item)) + return this.amountMap.get(item).getExp(); + else + return 0; + } +} \ No newline at end of file diff --git a/com/gamingmesh/jobs/container/LogAmounts.java b/com/gamingmesh/jobs/container/LogAmounts.java new file mode 100644 index 00000000..f18ad049 --- /dev/null +++ b/com/gamingmesh/jobs/container/LogAmounts.java @@ -0,0 +1,75 @@ +package com.gamingmesh.jobs.container; + +public final class LogAmounts { + + private String username; + private String action; + + private String item; + private int count = 0; + private double money = 0.0; + private double exp = 0.0; + + private boolean newEntry = true; + + public LogAmounts(String item) { + this.item = item; + } + + public boolean isNewEntry() { + return this.newEntry; + } + + public void setNewEntry(boolean state) { + this.newEntry = state; + } + + public String getItemName() { + return this.item; + } + + public void addMoney(Double amount) { + this.money += amount; + } + + public double getMoney() { + return (int) (this.money * 100) / 100.0; + } + + public void addExp(Double amount) { + this.exp += amount; + } + + public double getExp() { + return (int) (this.exp * 100) / 100.0; + } + + public void addCount() { + this.count++; + } + + public int getCount() { + return this.count; + } + + public void setCount(int count) { + this.count = count; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getUsername() { + return this.username; + } + + public void setAction(String action) { + this.action = action; + } + + public String getAction() { + return this.action; + } + +} \ No newline at end of file diff --git a/com/gamingmesh/jobs/container/Schedule.java b/com/gamingmesh/jobs/container/Schedule.java index c9e34815..2f5f11bd 100644 --- a/com/gamingmesh/jobs/container/Schedule.java +++ b/com/gamingmesh/jobs/container/Schedule.java @@ -10,181 +10,215 @@ import com.gamingmesh.jobs.Jobs; public class Schedule { - int From = 0; - int Until = 235959; + int From = 0; + int Until = 235959; - int nextFrom = 0; - int nextUntil = 235959; + int nextFrom = 0; + int nextUntil = 235959; - boolean nextDay = false; + boolean nextDay = false; - double MoneyBoost = 1.0; - double ExpBoost = 1.0; + double MoneyBoost = 1.0; + double ExpBoost = 1.0; - String Name = null; + String Name = null; - List Days = new ArrayList(Arrays.asList("all")); - List JobsList = new ArrayList(); + List Days = new ArrayList(Arrays.asList("all")); + List JobsList = new ArrayList(); - List MessageOnStart = new ArrayList(); - List MessageOnStop = new ArrayList(); + List MessageOnStart = new ArrayList(); + List MessageOnStop = new ArrayList(); - boolean started = false; - boolean stoped = true; + List MessageToBroadcast = new ArrayList(); - boolean onStop = true; - boolean OnStart = true; + boolean started = false; + boolean stoped = true; - public Schedule() { + boolean onStop = true; + boolean OnStart = true; + + long broadcastInfoOn = 0L; + int broadcastInterval = 0; + + public Schedule() { + } + + public void setBroadcastInfoOn(long time) { + this.broadcastInfoOn = time; + } + + public long getBroadcastInfoOn() { + return this.broadcastInfoOn; + } + + public void setBroadcastOnStop(boolean stage) { + this.onStop = stage; + } + + public boolean isBroadcastOnStop() { + return this.onStop; + } + + public void setBroadcastOnStart(boolean stage) { + this.OnStart = stage; + } + + public boolean isBroadcastOnStart() { + return this.OnStart; + } + + public void setStarted(boolean stage) { + this.started = stage; + } + + public boolean isStarted() { + return this.started; + } + + public void setStoped(boolean con) { + this.stoped = con; + } + + public boolean isStoped() { + return this.stoped; + } + + public void setMoneyBoost(double MoneyBoost) { + this.MoneyBoost = MoneyBoost; + } + + public double GetMoneyBoost() { + return this.MoneyBoost; + } + + public void setExpBoost(double ExpBoost) { + this.ExpBoost = ExpBoost; + } + + public double GetExpBoost() { + return this.ExpBoost; + } + + public void setName(String Name) { + this.Name = Name; + } + + public String GetName() { + return this.Name; + } + + public void setFrom(int From) { + this.From = From; + } + + public int GetFrom() { + return this.From; + } + + public int GetNextFrom() { + return this.nextFrom; + } + + public int GetNextUntil() { + return this.nextUntil; + } + + public boolean isNextDay() { + return this.nextDay; + } + + public void setUntil(int Until) { + this.Until = Until; + + if (this.From > this.Until) { + this.nextFrom = 0; + this.nextUntil = this.Until; + this.Until = 236000; + this.nextDay = true; } + } - public void setBroadcastOnStop(boolean stage) { - this.onStop = stage; + public int GetUntil() { + return this.Until; + } + + public void setJobs(List JobsNameList) { + for (int z = 0; z < JobsNameList.size(); z++) { + + if (JobsNameList.get(z).equalsIgnoreCase("all")) { + JobsList.clear(); + List jobl = Jobs.getJobs(); + if (jobl != null) + JobsList.addAll(Jobs.getJobs()); + return; + } + + Job jb = Jobs.getJob(JobsNameList.get(z)); + + if (jb == null) + continue; + + JobsList.add(jb); } + } - public boolean isBroadcastOnStop() { - return this.onStop; + public List GetJobs() { + return this.JobsList; + } + + public void setDays(List Days) { + for (int z = 0; z < Days.size(); z++) { + Days.set(z, Days.get(z).toLowerCase()); } + this.Days = Days; + } - public void setBroadcastOnStart(boolean stage) { - this.OnStart = stage; + public List GetDays() { + return this.Days; + } + + public void setMessageOnStart(List msg, String From, String Until) { + List temp = new ArrayList(); + for (String one : msg) { + temp.add(ChatColor.translateAlternateColorCodes('&', one.replace("[until]", Until).replace("[from]", From))); } + this.MessageOnStart.addAll(temp); + } - public boolean isBroadcastOnStart() { - return this.OnStart; + public List GetMessageOnStart() { + return this.MessageOnStart; + } + + public void setMessageOnStop(List msg, String From, String Until) { + List temp = new ArrayList(); + for (String one : msg) { + temp.add(ChatColor.translateAlternateColorCodes('&', one.replace("[until]", Until).replace("[from]", From))); } + this.MessageOnStop.addAll(temp); + } - public void setStarted(boolean stage) { - this.started = stage; + public List GetMessageOnStop() { + return this.MessageOnStop; + } + + public void setMessageToBroadcast(List msg, String From, String Until) { + List temp = new ArrayList(); + for (String one : msg) { + temp.add(ChatColor.translateAlternateColorCodes('&', one.replace("[until]", Until).replace("[from]", From))); } + this.MessageToBroadcast.addAll(temp); + } - public boolean isStarted() { - return this.started; - } + public List GetMessageToBroadcast() { + return this.MessageToBroadcast; + } - public void setStoped(boolean con) { - this.stoped = con; - } + public void setBroadcastInterval(int From) { + this.broadcastInterval = From; + } - public boolean isStoped() { - return this.stoped; - } + public int GetBroadcastInterval() { + return this.broadcastInterval; + } - public void setMoneyBoost(double MoneyBoost) { - this.MoneyBoost = MoneyBoost; - } - - public double GetMoneyBoost() { - return this.MoneyBoost; - } - - public void setExpBoost(double ExpBoost) { - this.ExpBoost = ExpBoost; - } - - public double GetExpBoost() { - return this.ExpBoost; - } - - public void setName(String Name) { - this.Name = Name; - } - - public String GetName() { - return this.Name; - } - - public void setFrom(int From) { - this.From = From; - } - - public int GetFrom() { - return this.From; - } - - public int GetNextFrom() { - return this.nextFrom; - } - - public int GetNextUntil() { - return this.nextUntil; - } - - public boolean isNextDay() { - return this.nextDay; - } - - public void setUntil(int Until) { - this.Until = Until; - - if (this.From > this.Until) { - this.nextFrom = 0; - this.nextUntil = this.Until; - this.Until = 236000; - this.nextDay = true; - } - } - - public int GetUntil() { - return this.Until; - } - - public void setJobs(List JobsNameList) { - for (int z = 0; z < JobsNameList.size(); z++) { - - if (JobsNameList.get(z).equalsIgnoreCase("all")) { - JobsList.clear(); - List jobl = Jobs.getJobs(); - if (jobl != null) - JobsList.addAll(Jobs.getJobs()); - return; - } - - Job jb = Jobs.getJob(JobsNameList.get(z)); - - if (jb == null) - continue; - - JobsList.add(jb); - } - } - - public List GetJobs() { - return this.JobsList; - } - - public void setDays(List Days) { - for (int z = 0; z < Days.size(); z++) { - Days.set(z, Days.get(z).toLowerCase()); - } - this.Days = Days; - } - - public List GetDays() { - return this.Days; - } - - public void setMessageOnStart(List msg) { - List temp = new ArrayList(); - for (String one : msg) { - temp.add(ChatColor.translateAlternateColorCodes('&', one)); - } - this.MessageOnStart.addAll(temp); - } - - public List GetMessageOnStart() { - return this.MessageOnStart; - } - - public void setMessageOnStop(List msg) { - List temp = new ArrayList(); - for (String one : msg) { - temp.add(ChatColor.translateAlternateColorCodes('&', one)); - } - this.MessageOnStop.addAll(temp); - } - - public List GetMessageOnStop() { - return this.MessageOnStop; - } } diff --git a/com/gamingmesh/jobs/dao/JobsDAO.java b/com/gamingmesh/jobs/dao/JobsDAO.java index f5c92a65..cc0d1dbc 100644 --- a/com/gamingmesh/jobs/dao/JobsDAO.java +++ b/com/gamingmesh/jobs/dao/JobsDAO.java @@ -24,6 +24,7 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; +import java.util.Map.Entry; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; @@ -34,7 +35,11 @@ import com.gamingmesh.jobs.container.Convert; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; +import com.gamingmesh.jobs.container.Log; +import com.gamingmesh.jobs.container.LogAmounts; import com.gamingmesh.jobs.container.TopList; +import com.gamingmesh.jobs.stuff.Loging; +import com.gamingmesh.jobs.stuff.TimeManage; import com.gamingmesh.jobs.stuff.UUIDUtil; /** @@ -46,606 +51,700 @@ import com.gamingmesh.jobs.stuff.UUIDUtil; */ public abstract class JobsDAO { - private JobsConnectionPool pool; - private String prefix; + private JobsConnectionPool pool; + private String prefix; - protected JobsDAO(String driverName, String url, String username, String password, String prefix) { - this.prefix = prefix; - try { - pool = new JobsConnectionPool(driverName, url, username, password); - } catch (Exception e) { - e.printStackTrace(); - } + protected JobsDAO(String driverName, String url, String username, String password, String prefix) { + this.prefix = prefix; + try { + pool = new JobsConnectionPool(driverName, url, username, password); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public final synchronized void setUp() throws SQLException { + setupConfig(); + int version = getSchemaVersion(); + if (version == 0) { + Jobs.getPluginLogger().severe("Could not initialize database! Could not determine schema version!"); + return; } - public final synchronized void setUp() throws SQLException { - setupConfig(); - int version = getSchemaVersion(); - if (version == 0) { - Jobs.getPluginLogger().severe("Could not initialize database! Could not determine schema version!"); - return; - } + try { + if (version <= 1) + checkUpdate1(); + else if (version <= 2) + checkUpdate2(); + else if (version <= 3) + checkUpdate4(); + else if (version <= 4) + checkUpdate5(); - try { - if (version <= 1) - checkUpdate1(); - else if (version <= 2) - checkUpdate2(); - else if (version <= 3) - checkUpdate4(); + version = 5; + } finally { + updateSchemaVersion(version); + } + } - version = 4; - } finally { - updateSchemaVersion(version); - } + protected abstract void setupConfig() throws SQLException; + + protected abstract void checkUpdate1() throws SQLException; + + protected abstract void checkUpdate2() throws SQLException; + + protected abstract void checkUpdate4() throws SQLException; + + protected abstract void checkUpdate5() throws SQLException; + + /** + * Gets the database prefix + * @return the prefix + */ + protected String getPrefix() { + return prefix; + } + + /** + * Get all jobs the player is part of. + * @param playerUUID - the player being searched for + * @return list of all of the names of the jobs the players are part of. + */ + public synchronized List getAllJobs(OfflinePlayer player) { + ArrayList jobs = new ArrayList(); + JobsConnection conn = getConnection(); + if (conn == null) + return jobs; + try { + PreparedStatement prest = conn.prepareStatement("SELECT `player_uuid`, `job`, `level`, `experience` FROM `" + prefix + "jobs` WHERE `player_uuid` = ?;"); + prest.setBytes(1, UUIDUtil.toBytes(player.getUniqueId())); + ResultSet res = prest.executeQuery(); + while (res.next()) { + jobs.add(new JobsDAOData(player.getUniqueId(), res.getString(2), res.getInt(3), res.getInt(4))); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return jobs; + } + + /** + * Get player count for a job. + * @param JobName - the job name + * @return amount of player currently working. + */ + public synchronized int getTotalPlayerAmountByJobName(String JobName) { + JobsConnection conn = getConnection(); + if (conn == null) + return 0; + int count = 0; + try { + PreparedStatement prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + prefix + "jobs` WHERE `job` = ?;"); + prest.setString(1, JobName); + ResultSet res = prest.executeQuery(); + while (res.next()) { + count = res.getInt(1); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return count; + } + + /** + * Get player count for a job. + * @return total amount of player currently working. + */ + public synchronized int getTotalPlayers() { + JobsConnection conn = getConnection(); + if (conn == null) + return 0; + int count = 0; + try { + PreparedStatement prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + prefix + "jobs`;"); + ResultSet res = prest.executeQuery(); + while (res.next()) { + count = res.getInt(1); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return count; + } + + /** + * Get all jobs the player is part of. + * @param userName - the player being searched for + * @return list of all of the names of the jobs the players are part of. + */ + public synchronized List getAllJobsOffline(String userName) { + ArrayList jobs = new ArrayList(); + JobsConnection conn = getConnection(); + if (conn == null) + return jobs; + try { + PreparedStatement prest = conn.prepareStatement("SELECT `player_uuid`, `job`, `level`, `experience` FROM `" + prefix + "jobs` WHERE `username` LIKE ?;"); + prest.setString(1, userName); + ResultSet res = prest.executeQuery(); + while (res.next()) { + jobs.add(new JobsDAOData(UUIDUtil.fromBytes(res.getBytes(1)), res.getString(2), res.getInt(3), res.getInt(4))); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return jobs; + } + + /** + * Join a job (create player-job entry from storage) + * @param player - player that wishes to join the job + * @param job - job that the player wishes to join + */ + public synchronized void joinJob(JobsPlayer jPlayer, Job job) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + try { + int level = 1; + int exp = 0; + if (checkArchive(jPlayer, job).size() > 0) { + List info = checkArchive(jPlayer, job); + level = info.get(0); + deleteArchive(jPlayer, job); + } + PreparedStatement prest = conn.prepareStatement("INSERT INTO `" + prefix + + "jobs` (`player_uuid`, `username`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?, ?);"); + prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); + prest.setString(2, jPlayer.getUserName()); + prest.setString(3, job.getName()); + prest.setInt(4, level); + prest.setInt(5, exp); + prest.execute(); + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * Join a job (create player-job entry from storage) + * @param player - player that wishes to join the job + * @param job - job that the player wishes to join + * @throws SQLException + */ + public List convertDatabase(Player Player, String table) throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) + return null; + + List list = new ArrayList(); + try { + PreparedStatement prest = conn.prepareStatement("SELECT * FROM `" + prefix + table + "`"); + ResultSet res = prest.executeQuery(); + while (res.next()) { + list.add(new Convert(res.getInt("id"), res.getString("username"), UUIDUtil.fromBytes(res.getBytes("player_uuid")), res.getString("job"), res.getInt( + "level"), res.getInt("experience"))); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); } - protected abstract void setupConfig() throws SQLException; - - protected abstract void checkUpdate1() throws SQLException; - - protected abstract void checkUpdate2() throws SQLException; - - protected abstract void checkUpdate4() throws SQLException; - - /** - * Gets the database prefix - * @return the prefix - */ - protected String getPrefix() { - return prefix; + try { + conn.closeConnection(); + } catch (SQLException e) { + e.printStackTrace(); } + return list; + } - /** - * Get all jobs the player is part of. - * @param playerUUID - the player being searched for - * @return list of all of the names of the jobs the players are part of. - */ - public synchronized List getAllJobs(OfflinePlayer player) { - ArrayList jobs = new ArrayList(); - JobsConnection conn = getConnection(); - if (conn == null) - return jobs; + public void continueConvertions(List list, String table) throws SQLException { + JobsConnection conns = this.getConnection(); + if (conns == null) + return; + PreparedStatement insert = null; + int i = list.size(); + try { + + Statement statement = conns.createStatement(); + if (ConfigManager.getJobsConfiguration().storageMethod.equalsIgnoreCase("sqlite")) { + statement.executeUpdate("TRUNCATE `" + getPrefix() + table + "`"); + } else { + statement.executeUpdate("DELETE from `" + getPrefix() + table + "`"); + } + + insert = conns.prepareStatement("INSERT INTO `" + getPrefix() + table + "` (`username`,`player_uuid`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?, ?);"); + conns.setAutoCommit(false); + while (i > 0) { + i--; + Convert convertData = list.get(i); + insert.setString(1, convertData.GetName()); + insert.setBytes(2, UUIDUtil.toBytes(convertData.GetUuid())); + insert.setString(3, convertData.GetJobName()); + insert.setInt(4, convertData.GetLevel()); + insert.setInt(5, convertData.GetExp()); + insert.addBatch(); + } + insert.executeBatch(); + conns.commit(); + conns.setAutoCommit(true); + } finally { + if (insert != null) { try { - PreparedStatement prest = conn.prepareStatement("SELECT `player_uuid`, `job`, `level`, `experience` FROM `" + prefix + "jobs` WHERE `player_uuid` = ?;"); - prest.setBytes(1, UUIDUtil.toBytes(player.getUniqueId())); - ResultSet res = prest.executeQuery(); - while (res.next()) { - jobs.add(new JobsDAOData(player.getUniqueId(), res.getString(2), res.getInt(3), res.getInt(4))); - } - prest.close(); + insert.close(); } catch (SQLException e) { - e.printStackTrace(); } - return jobs; + } } + } - /** - * Get player count for a job. - * @param JobName - the job name - * @return amount of player currently working. - */ - public synchronized int getTotalPlayerAmountByJobName(String JobName) { - JobsConnection conn = getConnection(); - if (conn == null) - return 0; - int count = 0; + /** + * Quit a job (delete player-job entry from storage) + * @param player - player that wishes to quit the job + * @param job - job that the player wishes to quit + */ + public synchronized void quitJob(JobsPlayer jPlayer, Job job) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + try { + PreparedStatement prest = conn.prepareStatement("DELETE FROM `" + prefix + "jobs` WHERE `player_uuid` = ? AND `job` = ?;"); + prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); + prest.setString(2, job.getName()); + prest.execute(); + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * Record job to archive + * @param player - player that wishes to quit the job + * @param job - job that the player wishes to quit + */ + public void recordToArchive(JobsPlayer jPlayer, Job job) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + try { + int level = 1; + int exp = 0; + for (JobProgression progression : jPlayer.getJobProgression()) { + if (progression.getJob().getName().equalsIgnoreCase(job.getName())) { + level = progression.getLevel(); + exp = (int) progression.getExperience(); + } + } + PreparedStatement prest = conn.prepareStatement("INSERT INTO `" + prefix + + "archive` (`player_uuid`, `username`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?, ?);"); + prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); + prest.setString(2, jPlayer.getUserName()); + prest.setString(3, job.getName()); + prest.setInt(4, level); + prest.setInt(5, exp); + prest.execute(); + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * Check job in archive + * @param player - player that wishes to quit the job + * @param job - job that the player wishes to quit + */ + public synchronized List checkArchive(JobsPlayer jPlayer, Job job) { + JobsConnection conn = getConnection(); + if (conn == null) + return null; + try { + List info = new ArrayList(); + PreparedStatement prest = conn.prepareStatement("SELECT `level`, `experience` FROM `" + prefix + "archive` WHERE `player_uuid` = ? AND `job` = ?;"); + prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); + prest.setString(2, job.getName()); + ResultSet res = prest.executeQuery(); + if (res.next()) { + int level = (int) ((res.getInt(1) - (res.getInt(1) * (ConfigManager.getJobsConfiguration().levelLossPercentage / 100.0)))); + if (level < 1) + level = 1; + + int maxLevel = 0; + if (jPlayer.havePermission("jobs." + job.getName() + ".vipmaxlevel") && job.getVipMaxLevel() != 0) + maxLevel = job.getVipMaxLevel(); + else + maxLevel = job.getMaxLevel(); + + if (ConfigManager.getJobsConfiguration().fixAtMaxLevel && res.getInt(1) == maxLevel) + level = res.getInt(1); + info.add(level); + info.add(res.getInt(2)); + } + prest.close(); + return info; + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + public List getGlobalTopList() { + return getGlobalTopList(0); + } + + /** + * Get all jobs from archive by player + * @param player - targeted player + * @return info - information about jobs + */ + public List getGlobalTopList(int start) { + JobsConnection conn = getConnection(); + + List names = new ArrayList(); + + if (conn == null) + return null; + try { + + PreparedStatement prest = conn.prepareStatement("SELECT username, player_uuid, COUNT(*) AS amount, sum(level) AS totallvl FROM `" + prefix + + "jobs` GROUP BY username ORDER BY totallvl DESC LIMIT " + start + ",20;"); + ResultSet res = prest.executeQuery(); + + while (res.next()) { + + TopList top = new TopList(res.getString("username"), res.getInt("totallvl"), 0, res.getBytes("player_uuid")); + + names.add(top); + } + + prest.close(); + return names; + } catch (SQLException e) { + e.printStackTrace(); + } + return names; + } + + /** + * Get all jobs from archive by player + * @param player - targeted player + * @return info - information about jobs + */ + public synchronized List getJobsFromArchive(JobsPlayer jPlayer) { + JobsConnection conn = getConnection(); + if (conn == null) + return null; + try { + List info = new ArrayList(); + PreparedStatement prest = conn.prepareStatement("SELECT `job`, `level`, `experience` FROM `" + prefix + "archive` WHERE `player_uuid` = ?;"); + prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); + ResultSet res = prest.executeQuery(); + while (res.next()) { + + int level = (int) ((res.getInt(2) - (res.getInt(2) * (ConfigManager.getJobsConfiguration().levelLossPercentage / 100.0)))); + if (level < 1) + level = 1; + + int maxLevel = 0; + if (jPlayer.havePermission("jobs." + Jobs.getJob(res.getString(1)).getName() + ".vipmaxlevel")) + maxLevel = Jobs.getJob(res.getString(1)).getVipMaxLevel(); + else + maxLevel = Jobs.getJob(res.getString(1)).getMaxLevel(); + + if (ConfigManager.getJobsConfiguration().fixAtMaxLevel && res.getInt(2) == maxLevel) + level = res.getInt(2); + + info.add(res.getString(1) + ":" + res.getInt(2) + ":" + level + ":" + res.getInt(3)); + } + prest.close(); + return info; + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + /** + * Delete job from archive + * @param player - player that wishes to quit the job + * @param job - job that the player wishes to quit + */ + public synchronized void deleteArchive(JobsPlayer jPlayer, Job job) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + try { + PreparedStatement prest = conn.prepareStatement("DELETE FROM `" + prefix + "archive` WHERE `player_uuid` = ? AND `job` = ?;"); + prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); + prest.setString(2, job.getName()); + prest.execute(); + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * Save player-job information + * @param jobInfo - the information getting saved + */ + public synchronized void save(JobsPlayer player) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + try { + PreparedStatement prest = conn.prepareStatement("UPDATE `" + prefix + "jobs` SET `level` = ?, `experience` = ? WHERE `player_uuid` = ? AND `job` = ?;"); + for (JobProgression progression : player.getJobProgression()) { + prest.setInt(1, progression.getLevel()); + prest.setInt(2, (int) progression.getExperience()); + prest.setBytes(3, UUIDUtil.toBytes(player.getPlayerUUID())); + prest.setString(4, progression.getJob().getName()); + prest.execute(); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * Save player-job information + * @param jobInfo - the information getting saved + */ + public synchronized void saveLog(JobsPlayer player) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + try { + + PreparedStatement prest = conn.prepareStatement("UPDATE `" + prefix + + "log` SET `count` = ?, `money` = ?, `exp` = ? WHERE `player_uuid` = ? AND `time` = ? AND `action` = ? AND `itemname` = ?;"); + for (Log log : player.getLog()) { + for (Entry one : log.getAmountList().entrySet()) { + if (one.getValue().isNewEntry()) + continue; + + prest.setInt(1, one.getValue().getCount()); + prest.setDouble(2, one.getValue().getMoney()); + prest.setDouble(3, one.getValue().getExp()); + + prest.setBytes(4, UUIDUtil.toBytes(player.getPlayerUUID())); + prest.setInt(5, log.getDate()); + prest.setString(6, log.getActionType()); + prest.setString(7, one.getKey()); + prest.execute(); + } + } + prest = conn.prepareStatement("INSERT INTO `" + prefix + + "log` (`player_uuid`, `username`, `time`, `action`, `itemname`, `count`, `money`, `exp`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); + for (Log log : player.getLog()) { + for (Entry one : log.getAmountList().entrySet()) { + + if (!one.getValue().isNewEntry()) + continue; + + one.getValue().setNewEntry(false); + + prest.setBytes(1, UUIDUtil.toBytes(player.getPlayerUUID())); + prest.setString(2, player.getUserName()); + prest.setInt(3, log.getDate()); + prest.setString(4, log.getActionType()); + prest.setString(5, one.getKey()); + prest.setInt(6, one.getValue().getCount()); + prest.setDouble(7, one.getValue().getMoney()); + prest.setDouble(8, one.getValue().getExp()); + prest.execute(); + } + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * Save player-job information + * @param jobInfo - the information getting saved + */ + public void loadLog(JobsPlayer player) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + try { + + int time = TimeManage.timeInInt(); + + PreparedStatement prest = conn.prepareStatement("SELECT `player_uuid`, `username`, `time`, `action`, `itemname`, `count`, `money`, `exp` FROM `" + prefix + + "log` WHERE `player_uuid` = ? AND `time` = ? ;"); + prest.setBytes(1, UUIDUtil.toBytes(player.getPlayerUUID())); + prest.setInt(2, time); + ResultSet res = prest.executeQuery(); + while (res.next()) { + Loging.loadToLog(player, res.getString("action"), res.getString("itemname"), res.getInt("count"), res.getDouble("money"), res.getDouble("exp")); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * Show top list + * @param toplist - toplist by jobs name + * @return + */ + public synchronized ArrayList toplist(String jobsname, int limit) { + ArrayList jobs = new ArrayList(); + JobsConnection conn = getConnection(); + if (conn == null) + return jobs; + try { + PreparedStatement prest = conn.prepareStatement("SELECT `username`, `level`, `experience`,`player_uuid` FROM `" + prefix + + "jobs` WHERE `job` LIKE ? ORDER BY `level` DESC, LOWER(username) ASC LIMIT " + limit + ", 15;"); + prest.setString(1, jobsname); + ResultSet res = prest.executeQuery(); + while (res.next()) { + jobs.add(new TopList(res.getString(1), res.getInt(2), res.getInt(3), res.getBytes(4))); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return jobs; + } + + /** + * Get the number of players that have a particular job + * @param job - the job + * @return the number of players that have a particular job + */ + public synchronized int getSlotsTaken(Job job) { + int slot = 0; + JobsConnection conn = getConnection(); + if (conn == null) + return slot; + try { + PreparedStatement prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + prefix + "jobs` WHERE `job` = ?;"); + prest.setString(1, job.getName()); + ResultSet res = prest.executeQuery(); + if (res.next()) { + slot = res.getInt(1); + } + prest.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return slot; + } + + /** + * Gets the current schema version + * @return schema version number + */ + protected int getSchemaVersion() { + JobsConnection conn = getConnection(); + if (conn == null) + return 0; + PreparedStatement prest = null; + try { + prest = conn.prepareStatement("SELECT `value` FROM `" + prefix + "config` WHERE `key` = ?;"); + prest.setString(1, "version"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + return Integer.valueOf(res.getString(1)); + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (NumberFormatException e) { + e.printStackTrace(); + } finally { + if (prest != null) { try { - PreparedStatement prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + prefix + "jobs` WHERE `job` = ?;"); - prest.setString(1, JobName); - ResultSet res = prest.executeQuery(); - while (res.next()) { - count = res.getInt(1); - } - prest.close(); + prest.close(); } catch (SQLException e) { - e.printStackTrace(); } - return count; + } } - /** - * Get player count for a job. - * @return total amount of player currently working. - */ - public synchronized int getTotalPlayers() { - JobsConnection conn = getConnection(); - if (conn == null) - return 0; - int count = 0; + return 0; + } + + /** + * Updates schema to version number + * @param version + */ + protected void updateSchemaVersion(int version) { + updateSchemaConfig("version", Integer.toString(version)); + } + + /** + * Updates configuration value + * @param key - the configuration key + * @param value - the configuration value + */ + private void updateSchemaConfig(String key, String value) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + PreparedStatement prest = null; + try { + prest = conn.prepareStatement("UPDATE `" + prefix + "config` SET `value` = ? WHERE `key` = ?;"); + prest.setString(1, value); + prest.setString(2, key); + prest.execute(); + } catch (SQLException e) { + e.printStackTrace(); + } finally { + if (prest != null) { try { - PreparedStatement prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + prefix + "jobs`;"); - ResultSet res = prest.executeQuery(); - while (res.next()) { - count = res.getInt(1); - } - prest.close(); + prest.close(); } catch (SQLException e) { - e.printStackTrace(); } - return count; + } } + } - /** - * Get all jobs the player is part of. - * @param userName - the player being searched for - * @return list of all of the names of the jobs the players are part of. - */ - public synchronized List getAllJobsOffline(String userName) { - ArrayList jobs = new ArrayList(); - JobsConnection conn = getConnection(); - if (conn == null) - return jobs; - try { - PreparedStatement prest = conn.prepareStatement("SELECT `player_uuid`, `job`, `level`, `experience` FROM `" + prefix + "jobs` WHERE `username` LIKE ?;"); - prest.setString(1, userName); - ResultSet res = prest.executeQuery(); - while (res.next()) { - jobs.add(new JobsDAOData(UUIDUtil.fromBytes(res.getBytes(1)), res.getString(2), res.getInt(3), res.getInt(4))); - } - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - return jobs; + /** + * Executes an SQL query + * @param sql - The SQL + * @throws SQLException + */ + public void executeSQL(String sql) throws SQLException { + JobsConnection conn = getConnection(); + Statement stmt = conn.createStatement(); + try { + stmt.execute(sql); + } finally { + try { + stmt.close(); + } catch (SQLException e) { + } } + } - /** - * Join a job (create player-job entry from storage) - * @param player - player that wishes to join the job - * @param job - job that the player wishes to join - */ - public synchronized void joinJob(JobsPlayer jPlayer, Job job) { - JobsConnection conn = getConnection(); - if (conn == null) - return; - try { - int level = 1; - int exp = 0; - if (checkArchive(jPlayer, job).size() > 0) { - List info = checkArchive(jPlayer, job); - level = info.get(0); - deleteArchive(jPlayer, job); - } - PreparedStatement prest = conn.prepareStatement("INSERT INTO `" + prefix + "jobs` (`player_uuid`, `username`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?, ?);"); - prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); - prest.setString(2, jPlayer.getUserName()); - prest.setString(3, job.getName()); - prest.setInt(4, level); - prest.setInt(5, exp); - prest.execute(); - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + /** + * Get a database connection + * @return JobsConnection object + * @throws SQLException + */ + protected JobsConnection getConnection() { + try { + return pool.getConnection(); + } catch (SQLException e) { + Jobs.getPluginLogger().severe("Unable to connect to the database: " + e.getMessage()); + return null; } + } - /** - * Join a job (create player-job entry from storage) - * @param player - player that wishes to join the job - * @param job - job that the player wishes to join - * @throws SQLException - */ - public List convertDatabase(Player Player, String table) throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) - return null; - - List list = new ArrayList(); - try { - PreparedStatement prest = conn.prepareStatement("SELECT * FROM `" + prefix + table + "`"); - ResultSet res = prest.executeQuery(); - while (res.next()) { - list.add(new Convert(res.getInt("id"), res.getString("username"), UUIDUtil.fromBytes(res.getBytes("player_uuid")), res.getString("job"), res.getInt("level"), res.getInt("experience"))); - } - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - - try { - conn.closeConnection(); - } catch (SQLException e) { - e.printStackTrace(); - } - return list; - } - - public void continueConvertions(List list, String table) throws SQLException { - JobsConnection conns = this.getConnection(); - if (conns == null) - return; - PreparedStatement insert = null; - int i = list.size(); - try { - - Statement statement = conns.createStatement(); - if (ConfigManager.getJobsConfiguration().storageMethod.equalsIgnoreCase("sqlite")) { - statement.executeUpdate("TRUNCATE `" + getPrefix() + table + "`"); - } else { - statement.executeUpdate("DELETE from `" + getPrefix() + table + "`"); - } - - insert = conns.prepareStatement("INSERT INTO `" + getPrefix() + table + "` (`username`,`player_uuid`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?, ?);"); - conns.setAutoCommit(false); - while (i > 0) { - i--; - Convert convertData = list.get(i); - insert.setString(1, convertData.GetName()); - insert.setBytes(2, UUIDUtil.toBytes(convertData.GetUuid())); - insert.setString(3, convertData.GetJobName()); - insert.setInt(4, convertData.GetLevel()); - insert.setInt(5, convertData.GetExp()); - insert.addBatch(); - } - insert.executeBatch(); - conns.commit(); - conns.setAutoCommit(true); - } finally { - if (insert != null) { - try { - insert.close(); - } catch (SQLException e) {} - } - } - } - - /** - * Quit a job (delete player-job entry from storage) - * @param player - player that wishes to quit the job - * @param job - job that the player wishes to quit - */ - public synchronized void quitJob(JobsPlayer jPlayer, Job job) { - JobsConnection conn = getConnection(); - if (conn == null) - return; - try { - PreparedStatement prest = conn.prepareStatement("DELETE FROM `" + prefix + "jobs` WHERE `player_uuid` = ? AND `job` = ?;"); - prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); - prest.setString(2, job.getName()); - prest.execute(); - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - /** - * Record job to archive - * @param player - player that wishes to quit the job - * @param job - job that the player wishes to quit - */ - public void recordToArchive(JobsPlayer jPlayer, Job job) { - JobsConnection conn = getConnection(); - if (conn == null) - return; - try { - int level = 1; - int exp = 0; - for (JobProgression progression : jPlayer.getJobProgression()) { - if (progression.getJob().getName().equalsIgnoreCase(job.getName())) { - level = progression.getLevel(); - exp = (int) progression.getExperience(); - } - } - PreparedStatement prest = conn.prepareStatement("INSERT INTO `" + prefix + "archive` (`player_uuid`, `username`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?, ?);"); - prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); - prest.setString(2, jPlayer.getUserName()); - prest.setString(3, job.getName()); - prest.setInt(4, level); - prest.setInt(5, exp); - prest.execute(); - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - /** - * Check job in archive - * @param player - player that wishes to quit the job - * @param job - job that the player wishes to quit - */ - public synchronized List checkArchive(JobsPlayer jPlayer, Job job) { - JobsConnection conn = getConnection(); - if (conn == null) - return null; - try { - List info = new ArrayList(); - PreparedStatement prest = conn.prepareStatement("SELECT `level`, `experience` FROM `" + prefix + "archive` WHERE `player_uuid` = ? AND `job` = ?;"); - prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); - prest.setString(2, job.getName()); - ResultSet res = prest.executeQuery(); - if (res.next()) { - int level = (int) ((res.getInt(1) - (res.getInt(1) * (ConfigManager.getJobsConfiguration().levelLossPercentage / 100.0)))); - if (level < 1) - level = 1; - - int maxLevel = 0; - if (jPlayer.havePermission("jobs." + job.getName() + ".vipmaxlevel") && job.getVipMaxLevel() != 0) - maxLevel = job.getVipMaxLevel(); - else - maxLevel = job.getMaxLevel(); - - if (ConfigManager.getJobsConfiguration().fixAtMaxLevel && res.getInt(1) == maxLevel) - level = res.getInt(1); - info.add(level); - info.add(res.getInt(2)); - } - prest.close(); - return info; - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - - public List getGlobalTopList() { - return getGlobalTopList(0); - } - - /** - * Get all jobs from archive by player - * @param player - targeted player - * @return info - information about jobs - */ - public List getGlobalTopList(int start) { - JobsConnection conn = getConnection(); - - List names = new ArrayList(); - - if (conn == null) - return null; - try { - - PreparedStatement prest = conn.prepareStatement("SELECT username, player_uuid, COUNT(*) AS amount, sum(level) AS totallvl FROM `" + prefix + "jobs` GROUP BY username ORDER BY totallvl DESC LIMIT " + start + ",20;"); - ResultSet res = prest.executeQuery(); - - while (res.next()) { - - TopList top = new TopList(res.getString("username"), res.getInt("totallvl"), 0, res.getBytes("player_uuid")); - - names.add(top); - } - - prest.close(); - return names; - } catch (SQLException e) { - e.printStackTrace(); - } - return names; - } - - /** - * Get all jobs from archive by player - * @param player - targeted player - * @return info - information about jobs - */ - public synchronized List getJobsFromArchive(JobsPlayer jPlayer) { - JobsConnection conn = getConnection(); - if (conn == null) - return null; - try { - List info = new ArrayList(); - PreparedStatement prest = conn.prepareStatement("SELECT `job`, `level`, `experience` FROM `" + prefix + "archive` WHERE `player_uuid` = ?;"); - prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); - ResultSet res = prest.executeQuery(); - while (res.next()) { - - int level = (int) ((res.getInt(2) - (res.getInt(2) * (ConfigManager.getJobsConfiguration().levelLossPercentage / 100.0)))); - if (level < 1) - level = 1; - - int maxLevel = 0; - if (jPlayer.havePermission("jobs." + Jobs.getJob(res.getString(1)).getName() + ".vipmaxlevel")) - maxLevel = Jobs.getJob(res.getString(1)).getVipMaxLevel(); - else - maxLevel = Jobs.getJob(res.getString(1)).getMaxLevel(); - - if (ConfigManager.getJobsConfiguration().fixAtMaxLevel && res.getInt(2) == maxLevel) - level = res.getInt(2); - - info.add(res.getString(1) + ":" + res.getInt(2) + ":" + level + ":" + res.getInt(3)); - } - prest.close(); - return info; - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Delete job from archive - * @param player - player that wishes to quit the job - * @param job - job that the player wishes to quit - */ - public synchronized void deleteArchive(JobsPlayer jPlayer, Job job) { - JobsConnection conn = getConnection(); - if (conn == null) - return; - try { - PreparedStatement prest = conn.prepareStatement("DELETE FROM `" + prefix + "archive` WHERE `player_uuid` = ? AND `job` = ?;"); - prest.setBytes(1, UUIDUtil.toBytes(jPlayer.getPlayerUUID())); - prest.setString(2, job.getName()); - prest.execute(); - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - /** - * Save player-job information - * @param jobInfo - the information getting saved - */ - public synchronized void save(final JobsPlayer player) { - JobsConnection conn = getConnection(); - if (conn == null) - return; - try { - PreparedStatement prest = conn.prepareStatement("UPDATE `" + prefix + "jobs` SET `level` = ?, `experience` = ? WHERE `player_uuid` = ? AND `job` = ?;"); - for (JobProgression progression : player.getJobProgression()) { - prest.setInt(1, progression.getLevel()); - prest.setInt(2, (int) progression.getExperience()); - prest.setBytes(3, UUIDUtil.toBytes(player.getPlayerUUID())); - prest.setString(4, progression.getJob().getName()); - prest.execute(); - } - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - /** - * Show top list - * @param toplist - toplist by jobs name - * @return - */ - public synchronized ArrayList toplist(String jobsname, int limit) { - ArrayList jobs = new ArrayList(); - JobsConnection conn = getConnection(); - if (conn == null) - return jobs; - try { - PreparedStatement prest = conn.prepareStatement("SELECT `username`, `level`, `experience`,`player_uuid` FROM `" + prefix + "jobs` WHERE `job` LIKE ? ORDER BY `level` DESC, LOWER(username) ASC LIMIT " + limit + ", 15;"); - prest.setString(1, jobsname); - ResultSet res = prest.executeQuery(); - while (res.next()) { - jobs.add(new TopList(res.getString(1), res.getInt(2), res.getInt(3), res.getBytes(4))); - } - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - return jobs; - } - - /** - * Get the number of players that have a particular job - * @param job - the job - * @return the number of players that have a particular job - */ - public synchronized int getSlotsTaken(Job job) { - int slot = 0; - JobsConnection conn = getConnection(); - if (conn == null) - return slot; - try { - PreparedStatement prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + prefix + "jobs` WHERE `job` = ?;"); - prest.setString(1, job.getName()); - ResultSet res = prest.executeQuery(); - if (res.next()) { - slot = res.getInt(1); - } - prest.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - return slot; - } - - /** - * Gets the current schema version - * @return schema version number - */ - protected int getSchemaVersion() { - JobsConnection conn = getConnection(); - if (conn == null) - return 0; - PreparedStatement prest = null; - try { - prest = conn.prepareStatement("SELECT `value` FROM `" + prefix + "config` WHERE `key` = ?;"); - prest.setString(1, "version"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - return Integer.valueOf(res.getString(1)); - } - } catch (SQLException e) { - e.printStackTrace(); - } catch (NumberFormatException e) { - e.printStackTrace(); - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) {} - } - } - - return 0; - } - - /** - * Updates schema to version number - * @param version - */ - protected void updateSchemaVersion(int version) { - updateSchemaConfig("version", Integer.toString(version)); - } - - /** - * Updates configuration value - * @param key - the configuration key - * @param value - the configuration value - */ - private void updateSchemaConfig(String key, String value) { - JobsConnection conn = getConnection(); - if (conn == null) - return; - PreparedStatement prest = null; - try { - prest = conn.prepareStatement("UPDATE `" + prefix + "config` SET `value` = ? WHERE `key` = ?;"); - prest.setString(1, value); - prest.setString(2, key); - prest.execute(); - } catch (SQLException e) { - e.printStackTrace(); - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) {} - } - } - } - - /** - * Executes an SQL query - * @param sql - The SQL - * @throws SQLException - */ - public void executeSQL(String sql) throws SQLException { - JobsConnection conn = getConnection(); - Statement stmt = conn.createStatement(); - try { - stmt.execute(sql); - } finally { - try { - stmt.close(); - } catch (SQLException e) {} - } - } - - /** - * Get a database connection - * @return JobsConnection object - * @throws SQLException - */ - protected JobsConnection getConnection() { - try { - return pool.getConnection(); - } catch (SQLException e) { - Jobs.getPluginLogger().severe("Unable to connect to the database: " + e.getMessage()); - return null; - } - } - - /** - * Close all active database handles - */ - public synchronized void closeConnections() { - pool.closeConnection(); - } + /** + * Close all active database handles + */ + public synchronized void closeConnections() { + pool.closeConnection(); + } } diff --git a/com/gamingmesh/jobs/dao/JobsDAOMySQL.java b/com/gamingmesh/jobs/dao/JobsDAOMySQL.java index d2388e6f..e45bb4be 100644 --- a/com/gamingmesh/jobs/dao/JobsDAOMySQL.java +++ b/com/gamingmesh/jobs/dao/JobsDAOMySQL.java @@ -31,244 +31,289 @@ import com.gamingmesh.jobs.stuff.ChatColor; import com.gamingmesh.jobs.stuff.UUIDUtil; public class JobsDAOMySQL extends JobsDAO { - private String database; + private String database; - private JobsDAOMySQL(String hostname, String database, String username, String password, String prefix) { - super("com.mysql.jdbc.Driver", "jdbc:mysql://" + hostname + "/" + database, username, password, prefix); - this.database = database; + private JobsDAOMySQL(String hostname, String database, String username, String password, String prefix) { + super("com.mysql.jdbc.Driver", "jdbc:mysql://" + hostname + "/" + database, username, password, prefix); + this.database = database; + } + + public static JobsDAOMySQL initialize(String hostname, String database, String username, String password, String prefix) { + JobsDAOMySQL dao = new JobsDAOMySQL(hostname, database, username, password, prefix); + try { + dao.setUp(); + } catch (SQLException e) { + e.printStackTrace(); } + return dao; + } - public static JobsDAOMySQL initialize(String hostname, String database, String username, String password, String prefix) { - JobsDAOMySQL dao = new JobsDAOMySQL(hostname, database, username, password, prefix); + @Override + protected synchronized void setupConfig() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for config table + prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); + prest.setString(1, database); + prest.setString(2, getPrefix() + "config"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { try { - dao.setUp(); + prest.close(); } catch (SQLException e) { - e.printStackTrace(); } - return dao; + } } - @Override - protected synchronized void setupConfig() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; + if (rows == 0) { + PreparedStatement insert = null; + try { + executeSQL("CREATE TABLE `" + getPrefix() + "config` (`key` varchar(50) NOT NULL PRIMARY KEY, `value` varchar(100) NOT NULL);"); + + insert = conn.prepareStatement("INSERT INTO `" + getPrefix() + "config` (`key`, `value`) VALUES (?, ?);"); + insert.setString(1, "version"); + insert.setString(2, "1"); + insert.execute(); + } finally { + if (insert != null) { + try { + insert.close(); + } catch (SQLException e) { + } } - PreparedStatement prest = null; - int rows = 0; + } + } + } + + @SuppressWarnings("deprecation") + @Override + protected synchronized void checkUpdate1() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for jobs table + prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); + prest.setString(1, database); + prest.setString(2, getPrefix() + "jobs"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { try { - // Check for config table - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "config"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) {} - } - } - - if (rows == 0) { - PreparedStatement insert = null; - try { - executeSQL("CREATE TABLE `" + getPrefix() + "config` (`key` varchar(50) NOT NULL PRIMARY KEY, `value` varchar(100) NOT NULL);"); - - insert = conn.prepareStatement("INSERT INTO `" + getPrefix() + "config` (`key`, `value`) VALUES (?, ?);"); - insert.setString(1, "version"); - insert.setString(2, "1"); - insert.execute(); - } finally { - if (insert != null) { - try { - insert.close(); - } catch (SQLException e) {} - } - } + prest.close(); + } catch (SQLException e) { } + } } - @SuppressWarnings("deprecation") - @Override - protected synchronized void checkUpdate1() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - int rows = 0; + PreparedStatement pst1 = null; + PreparedStatement pst2 = null; + try { + if (rows == 0) { + executeSQL("CREATE TABLE `" + getPrefix() + + "jobs` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `job` varchar(20), `experience` int, `level` int);"); + } else { + Jobs.getPluginLogger().info("Converting existing usernames to Mojang UUIDs. This could take a long time!"); + try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "jobs"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } + // Check for jobs table id column + // This is extra check to be sure there is no column by this name already + int idrows = 0; + prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?;"); + prest.setString(1, database); + prest.setString(2, getPrefix() + "jobs"); + prest.setString(3, "id"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + idrows = res.getInt(1); + } + if (idrows == 0) + executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;"); } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) {} - } + } - PreparedStatement pst1 = null; - PreparedStatement pst2 = null; try { - if (rows == 0) { - executeSQL("CREATE TABLE `" + getPrefix() + "jobs` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `job` varchar(20), `experience` int, `level` int);"); - } else { - Jobs.getPluginLogger().info("Converting existing usernames to Mojang UUIDs. This could take a long time!"); - - try { - // Check for jobs table id column - // This is extra check to be sure there is no column by this name already - int idrows = 0; - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "jobs"); - prest.setString(3, "id"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - idrows = res.getInt(1); - } - if (idrows == 0) - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;"); - } finally { - - } - - try { - // Check for jobs table id column - // This is extra check to be sure there is no column by this name already - int uuidrows = 0; - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "jobs"); - prest.setString(3, "player_uuid"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - uuidrows = res.getInt(1); - } - if (uuidrows == 0) - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `player_uuid` binary(16) DEFAULT NULL AFTER `id`;"); - } finally { - - } - - pst1 = conn.prepareStatement("SELECT DISTINCT `username` FROM `" + getPrefix() + "jobs` WHERE `player_uuid` IS NULL;"); - ResultSet rs = pst1.executeQuery(); - ArrayList usernames = new ArrayList(); - while (rs.next()) { - usernames.add(rs.getString(1)); - } - - pst2 = conn.prepareStatement("UPDATE `" + getPrefix() + "jobs` SET `player_uuid` = ? WHERE `username` = ?;"); - - int i = 0; - int y = 0; - for (String names : usernames) { - i++; - y++; - if (i >= 10) { - Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.DARK_GREEN + "" + y + " of " + usernames.size()); - i = 0; - } - pst2.setBytes(1, UUIDUtil.toBytes(UUID.fromString(Bukkit.getOfflinePlayer(names).getUniqueId().toString()))); - pst2.setString(2, names); - pst2.execute(); - } - - Jobs.getPluginLogger().info("Mojang UUID conversion complete!"); - } + // Check for jobs table id column + // This is extra check to be sure there is no column by this name already + int uuidrows = 0; + prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?;"); + prest.setString(1, database); + prest.setString(2, getPrefix() + "jobs"); + prest.setString(3, "player_uuid"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + uuidrows = res.getInt(1); + } + if (uuidrows == 0) + executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `player_uuid` binary(16) DEFAULT NULL AFTER `id`;"); } finally { - if (pst1 != null) { - try { - pst1.close(); - } catch (SQLException e) {} - } - if (pst2 != null) { - try { - pst2.close(); - } catch (SQLException e) {} - } + } - checkUpdate2(); + pst1 = conn.prepareStatement("SELECT DISTINCT `username` FROM `" + getPrefix() + "jobs` WHERE `player_uuid` IS NULL;"); + ResultSet rs = pst1.executeQuery(); + ArrayList usernames = new ArrayList(); + while (rs.next()) { + usernames.add(rs.getString(1)); + } + + pst2 = conn.prepareStatement("UPDATE `" + getPrefix() + "jobs` SET `player_uuid` = ? WHERE `username` = ?;"); + + int i = 0; + int y = 0; + for (String names : usernames) { + i++; + y++; + if (i >= 10) { + Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.DARK_GREEN + "" + y + " of " + usernames.size()); + i = 0; + } + pst2.setBytes(1, UUIDUtil.toBytes(UUID.fromString(Bukkit.getOfflinePlayer(names).getUniqueId().toString()))); + pst2.setString(2, names); + pst2.execute(); + } + + Jobs.getPluginLogger().info("Mojang UUID conversion complete!"); + } + } finally { + if (pst1 != null) { + try { + pst1.close(); + } catch (SQLException e) { + } + } + if (pst2 != null) { + try { + pst2.close(); + } catch (SQLException e) { + } + } } - @Override - protected synchronized void checkUpdate2() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "jobs"); - prest.setString(3, "username"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) {} - } - } + checkUpdate2(); + } + @Override + protected synchronized void checkUpdate2() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for jobs table + prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?;"); + prest.setString(1, database); + prest.setString(2, getPrefix() + "jobs"); + prest.setString(3, "username"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { try { - if (rows == 0) - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `username` varchar(20);"); - } finally { + prest.close(); + } catch (SQLException e) { } - checkUpdate4(); + } } - @Override - protected synchronized void checkUpdate4() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "archive"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) {} - } - } - - try { - if (rows == 0) - executeSQL("CREATE TABLE `" + getPrefix() + "archive` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); - } finally {} + try { + if (rows == 0) + executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `username` varchar(20);"); + } finally { } + checkUpdate4(); + } + + @Override + protected synchronized void checkUpdate4() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for jobs table + prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); + prest.setString(1, database); + prest.setString(2, getPrefix() + "archive"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { + try { + prest.close(); + } catch (SQLException e) { + } + } + } + + try { + if (rows == 0) + executeSQL("CREATE TABLE `" + getPrefix() + + "archive` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); + } finally { + } + } + + @Override + protected synchronized void checkUpdate5() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for jobs table + prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); + prest.setString(1, database); + prest.setString(2, getPrefix() + "log"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { + try { + prest.close(); + } catch (SQLException e) { + } + } + } + + try { + if (rows == 0) + executeSQL("CREATE TABLE `" + getPrefix() + + "log` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `time` bigint, `action` varchar(20), `itemname` varchar(20), `count` int, `money` double, `exp` double);"); + } finally { + } + } } diff --git a/com/gamingmesh/jobs/dao/JobsDAOSQLite.java b/com/gamingmesh/jobs/dao/JobsDAOSQLite.java index 9684159e..4f577557 100644 --- a/com/gamingmesh/jobs/dao/JobsDAOSQLite.java +++ b/com/gamingmesh/jobs/dao/JobsDAOSQLite.java @@ -32,222 +32,259 @@ import com.gamingmesh.jobs.stuff.ChatColor; import com.gamingmesh.jobs.stuff.UUIDUtil; public class JobsDAOSQLite extends JobsDAO { - public static JobsDAOSQLite initialize() { - JobsDAOSQLite dao = new JobsDAOSQLite(); - File dir = Jobs.getDataFolder(); - if (!dir.exists()) - dir.mkdirs(); + public static JobsDAOSQLite initialize() { + JobsDAOSQLite dao = new JobsDAOSQLite(); + File dir = Jobs.getDataFolder(); + if (!dir.exists()) + dir.mkdirs(); + try { + dao.setUp(); + } catch (SQLException e) { + e.printStackTrace(); + } + return dao; + } + + private JobsDAOSQLite() { + super("org.sqlite.JDBC", "jdbc:sqlite:" + new File(Jobs.getDataFolder(), "jobs.sqlite.db").getPath(), null, null, ""); + } + + @Override + protected synchronized void setupConfig() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + + PreparedStatement prest = null; + int rows = 0; + try { + // Check for config table + prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); + prest.setString(1, getPrefix() + "config"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { try { - dao.setUp(); + prest.close(); } catch (SQLException e) { - e.printStackTrace(); } - return dao; + } } - private JobsDAOSQLite() { - super("org.sqlite.JDBC", "jdbc:sqlite:" + new File(Jobs.getDataFolder(), "jobs.sqlite.db").getPath(), null, null, ""); + if (rows == 0) { + PreparedStatement insert = null; + try { + executeSQL("CREATE TABLE `" + getPrefix() + "config` (`key` varchar(50) NOT NULL PRIMARY KEY, `value` varchar(100) NOT NULL);"); + + insert = conn.prepareStatement("INSERT INTO `" + getPrefix() + "config` (`key`, `value`) VALUES (?, ?);"); + insert.setString(1, "version"); + insert.setString(2, "1"); + insert.execute(); + } finally { + if (insert != null) { + try { + insert.close(); + } catch (SQLException e) { + } + } + } + } + } + + @SuppressWarnings("deprecation") + @Override + protected synchronized void checkUpdate1() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for jobs table + prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); + prest.setString(1, getPrefix() + "jobs"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { + try { + prest.close(); + } catch (SQLException e) { + } + } } - @Override - protected synchronized void setupConfig() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; + PreparedStatement pst1 = null; + PreparedStatement pst2 = null; + try { + if (rows > 0) { + Jobs.getPluginLogger().info("Converting existing usernames to Mojang UUIDs. This could take a long time!!!"); + executeSQL("ALTER TABLE `" + getPrefix() + "jobs` RENAME TO `" + getPrefix() + "jobs_old`;"); + executeSQL("ALTER TABLE `" + getPrefix() + "jobs_old` ADD COLUMN `player_uuid` binary(16) DEFAULT NULL;"); + } + + executeSQL("CREATE TABLE `" + getPrefix() + + "jobs` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` binary(16) NOT NULL, `job` varchar(20), `experience` int, `level` int);"); + + if (rows > 0) { + pst1 = conn.prepareStatement("SELECT DISTINCT `username` FROM `" + getPrefix() + "jobs_old` WHERE `player_uuid` IS NULL;"); + ResultSet rs = pst1.executeQuery(); + ArrayList usernames = new ArrayList(); + while (rs.next()) { + usernames.add(rs.getString(1)); } - - PreparedStatement prest = null; - int rows = 0; + pst2 = conn.prepareStatement("UPDATE `" + getPrefix() + "jobs_old` SET `player_uuid` = ? WHERE `username` = ?;"); + int i = 0; + int y = 0; + for (String names : usernames) { + i++; + y++; + if (i >= 50) { + Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.DARK_GREEN + "" + y + " of " + usernames.size()); + i = 0; + } + pst2.setBytes(1, UUIDUtil.toBytes(UUID.fromString(Bukkit.getOfflinePlayer(names).getUniqueId().toString()))); + pst2.setString(2, names); + pst2.execute(); + } + executeSQL("INSERT INTO `" + getPrefix() + "jobs` (`player_uuid`, `job`, `experience`, `level`) SELECT `player_uuid`, `job`, `experience`, `level` FROM `" + + getPrefix() + "jobs_old`;"); + } + } finally { + if (pst1 != null) { try { - // Check for config table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "config"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) { - } - } + pst1.close(); + } catch (SQLException e) { } - - if (rows == 0) { - PreparedStatement insert = null; - try { - executeSQL("CREATE TABLE `" + getPrefix() + "config` (`key` varchar(50) NOT NULL PRIMARY KEY, `value` varchar(100) NOT NULL);"); - - insert = conn.prepareStatement("INSERT INTO `" + getPrefix() + "config` (`key`, `value`) VALUES (?, ?);"); - insert.setString(1, "version"); - insert.setString(2, "1"); - insert.execute(); - } finally { - if (insert != null) { - try { - insert.close(); - } catch (SQLException e) { - } - } - } + } + if (pst2 != null) { + try { + pst2.close(); + } catch (SQLException e) { } + } } - @SuppressWarnings("deprecation") - @Override - protected synchronized void checkUpdate1() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - int rows = 0; + if (rows > 0) { + executeSQL("DROP TABLE `" + getPrefix() + "jobs_old`;"); + + Jobs.getPluginLogger().info("Mojang UUID conversion complete!"); + } + checkUpdate2(); + } + + @Override + protected synchronized void checkUpdate2() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for jobs table + prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); + prest.setString(1, getPrefix() + "jobs"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "jobs"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) { - } - } + prest.close(); + } catch (SQLException e) { } - - PreparedStatement pst1 = null; - PreparedStatement pst2 = null; - try { - if (rows > 0) { - Jobs.getPluginLogger().info("Converting existing usernames to Mojang UUIDs. This could take a long time!!!"); - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` RENAME TO `" + getPrefix() + "jobs_old`;"); - executeSQL("ALTER TABLE `" + getPrefix() + "jobs_old` ADD COLUMN `player_uuid` binary(16) DEFAULT NULL;"); - } - - executeSQL("CREATE TABLE `" + getPrefix() + "jobs` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` binary(16) NOT NULL, `job` varchar(20), `experience` int, `level` int);"); - - if (rows > 0) { - pst1 = conn.prepareStatement("SELECT DISTINCT `username` FROM `" + getPrefix() + "jobs_old` WHERE `player_uuid` IS NULL;"); - ResultSet rs = pst1.executeQuery(); - ArrayList usernames = new ArrayList(); - while (rs.next()) { - usernames.add(rs.getString(1)); - } - pst2 = conn.prepareStatement("UPDATE `" + getPrefix() + "jobs_old` SET `player_uuid` = ? WHERE `username` = ?;"); - int i = 0; - int y = 0; - for (String names : usernames) { - i++; - y++; - if (i >= 50) { - Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.DARK_GREEN + "" + y + " of " + usernames.size()); - i = 0; - } - pst2.setBytes(1, UUIDUtil.toBytes(UUID.fromString(Bukkit.getOfflinePlayer(names).getUniqueId().toString()))); - pst2.setString(2, names); - pst2.execute(); - } - executeSQL("INSERT INTO `" + getPrefix() + "jobs` (`player_uuid`, `job`, `experience`, `level`) SELECT `player_uuid`, `job`, `experience`, `level` FROM `" + getPrefix() + "jobs_old`;"); - } - } finally { - if (pst1 != null) { - try { - pst1.close(); - } catch (SQLException e) { - } - } - if (pst2 != null) { - try { - pst2.close(); - } catch (SQLException e) { - } - } - } - - if (rows > 0) { - executeSQL("DROP TABLE `" + getPrefix() + "jobs_old`;"); - - Jobs.getPluginLogger().info("Mojang UUID conversion complete!"); - } - checkUpdate2(); + } } - @Override - protected synchronized void checkUpdate2() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "jobs"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) { - } - } - } + try { + if (rows > 0) { + executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `username` varchar(20);"); + } - try { - if (rows > 0) { - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `username` varchar(20);"); - } - - } finally { - } - checkUpdate4(); + } finally { } - - @Override - protected synchronized void checkUpdate4() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "archive"); - ResultSet res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) { - } - } - } + checkUpdate4(); + } - try { - if (rows == 0) { - executeSQL("CREATE TABLE `" + getPrefix() + "archive` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); - } - - } finally { - } + @Override + protected synchronized void checkUpdate4() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for jobs table + prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); + prest.setString(1, getPrefix() + "archive"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { + try { + prest.close(); + } catch (SQLException e) { + } + } + } + + try { + if (rows == 0) { + executeSQL("CREATE TABLE `" + getPrefix() + + "archive` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); + } + + } finally { + } + } + + @Override + protected synchronized void checkUpdate5() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + try { + // Check for jobs table + prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); + prest.setString(1, getPrefix() + "log"); + ResultSet res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + if (prest != null) { + try { + prest.close(); + } catch (SQLException e) { + } + } + } + + try { + if (rows == 0) + executeSQL("CREATE TABLE `" + getPrefix() + + "log` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `time` bigint, `action` varchar(20), `itemname` varchar(20), `count` int, `money` double, `exp` double);"); + } finally { + } + } } diff --git a/com/gamingmesh/jobs/economy/BufferedEconomy.java b/com/gamingmesh/jobs/economy/BufferedEconomy.java index 4d539b20..6ce45a90 100644 --- a/com/gamingmesh/jobs/economy/BufferedEconomy.java +++ b/com/gamingmesh/jobs/economy/BufferedEconomy.java @@ -141,8 +141,8 @@ public class BufferedEconomy { if (!Jobs.actionbartoggle.containsKey(ServerTaxesAccountname) && ConfigManager.getJobsConfiguration().JobsToggleEnabled) Jobs.actionbartoggle.put(ServerTaxesAccountname, true); if (Jobs.actionbartoggle.containsKey(ServerTaxesAccountname) && Jobs.actionbartoggle.get(ServerTaxesAccountname)) { - ActionBar.send((Player) ServerTaxesAccount, Language.getMessage("message.taxes").replace("[amount]", String.valueOf((int) (TotalAmount * 100) - / 100.0))); + ActionBar.send(Bukkit.getPlayer(ServerAccountname), Language.getMessage("message.taxes").replace("[amount]", String.valueOf((int) (TotalAmount + * 100) / 100.0))); } } } diff --git a/com/gamingmesh/jobs/economy/Economy.java b/com/gamingmesh/jobs/economy/Economy.java index a256d42e..216c128d 100644 --- a/com/gamingmesh/jobs/economy/Economy.java +++ b/com/gamingmesh/jobs/economy/Economy.java @@ -22,10 +22,16 @@ import org.bukkit.OfflinePlayer; public interface Economy { public boolean depositPlayer(OfflinePlayer offlinePlayer, double money); + public boolean withdrawPlayer(OfflinePlayer offlinePlayer, double money); + public String format(double money); - boolean hasMoney(OfflinePlayer offlinePlayer, double money); - boolean hasMoney(String PlayerName, double money); - boolean withdrawPlayer(String PlayerName, double money); - boolean depositPlayer(String PlayerName, double money); + + boolean hasMoney(OfflinePlayer offlinePlayer, double money); + + boolean hasMoney(String PlayerName, double money); + + boolean withdrawPlayer(String PlayerName, double money); + + boolean depositPlayer(String PlayerName, double money); } diff --git a/com/gamingmesh/jobs/economy/VaultEconomy.java b/com/gamingmesh/jobs/economy/VaultEconomy.java index d4f6e6de..88896894 100644 --- a/com/gamingmesh/jobs/economy/VaultEconomy.java +++ b/com/gamingmesh/jobs/economy/VaultEconomy.java @@ -66,4 +66,5 @@ public class VaultEconomy implements Economy { public String format(double money) { return vault.format(money); } + } diff --git a/com/gamingmesh/jobs/listeners/JobsListener.java b/com/gamingmesh/jobs/listeners/JobsListener.java index 53c09852..14a81346 100644 --- a/com/gamingmesh/jobs/listeners/JobsListener.java +++ b/com/gamingmesh/jobs/listeners/JobsListener.java @@ -46,13 +46,12 @@ import org.bukkit.plugin.PluginManager; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.JobsPlugin; +import com.gamingmesh.jobs.Signs.SignUtil; import com.gamingmesh.jobs.config.ConfigManager; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.i18n.Language; -import Signs.SignUtil; - public class JobsListener implements Listener { // hook to the main plugin private JobsPlugin plugin; @@ -277,7 +276,7 @@ public class JobsListener implements Listener { Location loc = block.getLocation(); - for (Signs.Sign one : SignUtil.Signs.GetAllSigns()) { + for (com.gamingmesh.jobs.Signs.Sign one : SignUtil.Signs.GetAllSigns()) { if (one.GetX() != loc.getBlockX()) continue; @@ -353,13 +352,13 @@ public class JobsListener implements Listener { return; } - Signs.Sign signInfo = new Signs.Sign(); + com.gamingmesh.jobs.Signs.Sign signInfo = new com.gamingmesh.jobs.Signs.Sign(); Location loc = sign.getLocation(); int category = 1; - if (Signs.SignUtil.Signs.GetAllSigns().size() > 0) - category = Signs.SignUtil.Signs.GetAllSigns().get(Signs.SignUtil.Signs.GetAllSigns().size() - 1).GetCategory() + 1; + if (com.gamingmesh.jobs.Signs.SignUtil.Signs.GetAllSigns().size() > 0) + category = com.gamingmesh.jobs.Signs.SignUtil.Signs.GetAllSigns().get(com.gamingmesh.jobs.Signs.SignUtil.Signs.GetAllSigns().size() - 1).GetCategory() + 1; signInfo.setNumber(Number); signInfo.setWorld(loc.getWorld().getName()); signInfo.setX(loc.getX()); @@ -372,16 +371,16 @@ public class JobsListener implements Listener { signInfo.setJobName("gtoplist"); signInfo.setSpecial(special); - Signs.SignUtil.Signs.addSign(signInfo); - Signs.SignUtil.saveSigns(); + com.gamingmesh.jobs.Signs.SignUtil.Signs.addSign(signInfo); + com.gamingmesh.jobs.Signs.SignUtil.saveSigns(); event.setCancelled(true); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(JobsPlugin.instance, new Runnable() { public void run() { if (!signtype.equalsIgnoreCase("gtoplist")) - Signs.SignUtil.SignUpdate(job.getName()); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate(job.getName()); else - Signs.SignUtil.SignUpdate("gtoplist"); + com.gamingmesh.jobs.Signs.SignUtil.SignUpdate("gtoplist"); return; } }, 1L); diff --git a/com/gamingmesh/jobs/stuff/.gitignore b/com/gamingmesh/jobs/stuff/.gitignore index e97af8cc..de4e3e19 100644 --- a/com/gamingmesh/jobs/stuff/.gitignore +++ b/com/gamingmesh/jobs/stuff/.gitignore @@ -17,3 +17,12 @@ /Scboard.class /ScheduleUtil$1.class /ScheduleUtil.class +/Sorting.class +/Sorting$1.class +/Sorting$2.class +/Sorting$3.class +/Sorting$4.class +/TimeUtil.class +/TimeManage.class +/Loging.class +/ScheduleUtil$2.class diff --git a/com/gamingmesh/jobs/stuff/Loging.java b/com/gamingmesh/jobs/stuff/Loging.java new file mode 100644 index 00000000..5b1dcf78 --- /dev/null +++ b/com/gamingmesh/jobs/stuff/Loging.java @@ -0,0 +1,70 @@ +package com.gamingmesh.jobs.stuff; + +import java.util.List; + +import com.gamingmesh.jobs.Jobs; +import com.gamingmesh.jobs.container.ActionInfo; +import com.gamingmesh.jobs.container.JobsPlayer; +import com.gamingmesh.jobs.container.Log; + +public class Loging { + + public static void recordToLog(JobsPlayer jPlayer, ActionInfo info, double amount, double expAmount) { + recordToLog(jPlayer, info.getType().getName(), info.getNameWithSub(), amount, expAmount); + } + + public static void recordToLog(JobsPlayer jPlayer, String ActionName, String item, double amount, double expAmount) { + List logList = jPlayer.getLog(); + boolean found = false; + + if (jPlayer.getLog().size() > 0 && ScheduleUtil.dateByInt != jPlayer.getLog().get(0).getDate()) { + ScheduleUtil.dateByInt = TimeManage.timeInInt(); + Debug.D("1 Not equals " + ScheduleUtil.dateByInt + " " + jPlayer.getLog().get(0).getDate()); + if (ScheduleUtil.dateByInt != jPlayer.getLog().get(0).getDate()) { + Debug.D("Not equals " + ScheduleUtil.dateByInt + " " + jPlayer.getLog().get(0).getDate()); + Jobs.getJobsDAO().saveLog(jPlayer); + jPlayer.getLog().clear(); + } + } + + for (Log one : logList) { + if (!one.getActionType().equalsIgnoreCase(ActionName)) + continue; + + one.add(item, amount, expAmount); + + found = true; + + Debug.D(item + " : " + one.getCount(item) + " money: " + one.getMoney(item) + " exp:" + one.getExp(item)); + } + if (!found) { + Log log = new Log(ActionName); + log.add(item, amount, expAmount); + logList.add(log); + String msg = item + " : " + log.getCount(item) + " money: " + log.getMoney(item) + " exp:" + log.getExp(item); + Debug.D(msg); + } + } + + public static void loadToLog(JobsPlayer jPlayer, String ActionName, String item, int count, double money, double expAmount) { + List logList = jPlayer.getLog(); + boolean found = false; + for (Log one : logList) { + if (!one.getActionType().equalsIgnoreCase(ActionName)) + continue; + + one.add(item, count, money, expAmount); + + found = true; + + Debug.D(item + " : " + one.getCount(item) + " money: " + one.getMoney(item) + " exp:" + one.getExp(item)); + } + if (!found) { + Log log = new Log(ActionName); + log.add(item, count, money, expAmount); + logList.add(log); + String msg = item + " : " + log.getCount(item) + " money: " + log.getMoney(item) + " exp:" + log.getExp(item); + Debug.D(msg); + } + } +} diff --git a/com/gamingmesh/jobs/stuff/ScheduleUtil.java b/com/gamingmesh/jobs/stuff/ScheduleUtil.java index 4091564c..38b5dad8 100644 --- a/com/gamingmesh/jobs/stuff/ScheduleUtil.java +++ b/com/gamingmesh/jobs/stuff/ScheduleUtil.java @@ -15,6 +15,23 @@ import com.gamingmesh.jobs.container.Schedule; import com.gamingmesh.jobs.i18n.Language; public class ScheduleUtil { + + public static int dateByInt = 0; + + public static void DateUpdater() { + if (dateByInt == 0) + dateByInt = TimeManage.timeInInt(); + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(JobsPlugin.instance, new Runnable() { + public void run() { + + dateByInt = TimeManage.timeInInt(); + + DateUpdater(); + return; + } + }, 60 * 20L); + } + public static boolean scheduler() { if (ConfigManager.getJobsConfiguration().BoostSchedule.size() > 0 && ConfigManager.getJobsConfiguration().useGlobalBoostScheduler) { @@ -34,6 +51,13 @@ public class ScheduleUtil { List days = one.GetDays(); + if (one.isStarted() && one.getBroadcastInfoOn() < System.currentTimeMillis() && one.GetBroadcastInterval() > 0) { + one.setBroadcastInfoOn(System.currentTimeMillis() + one.GetBroadcastInterval() * 60 * 1000); + for (String oneMsg : one.GetMessageToBroadcast()) { + Bukkit.broadcastMessage(oneMsg); + } + } + if (((one.isNextDay() && (Current >= From && Current < one.GetUntil() || Current >= one.GetNextFrom() && Current < one.GetNextUntil()) && !one .isStarted()) || !one.isNextDay() && (Current >= From && Current < Until)) && (days.contains(CurrentDayName) || days.contains("all")) && !one .isStarted()) { @@ -50,6 +74,9 @@ public class ScheduleUtil { onejob.setExpBoost(one.GetExpBoost()); onejob.setMoneyBoost(one.GetMoneyBoost()); } + + one.setBroadcastInfoOn(System.currentTimeMillis() + one.GetBroadcastInterval() * 60 * 1000); + one.setStarted(true); one.setStoped(false); break; diff --git a/com/gamingmesh/jobs/stuff/Sorting.java b/com/gamingmesh/jobs/stuff/Sorting.java new file mode 100644 index 00000000..75ffc9c9 --- /dev/null +++ b/com/gamingmesh/jobs/stuff/Sorting.java @@ -0,0 +1,97 @@ +package com.gamingmesh.jobs.stuff; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import com.gamingmesh.jobs.container.LogAmounts; + +public class Sorting { + public static Map sortDESC(Map unsortMap) { + + // Convert Map to List + List> list = new LinkedList>(unsortMap.entrySet()); + + // Sort list with comparator, to compare the Map values + Collections.sort(list, new Comparator>() { + public int compare(Map.Entry o1, Map.Entry o2) { + return (o2.getValue()).compareTo(o1.getValue()); + } + }); + + // Convert sorted map back to a Map + Map sortedMap = new LinkedHashMap(); + for (Iterator> it = list.iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + sortedMap.put(entry.getKey(), entry.getValue()); + } + return sortedMap; + } + + public static Map sortDoubleDESC(Map unsortMap) { + + // Convert Map to List + List> list = new LinkedList>(unsortMap.entrySet()); + + // Sort list with comparator, to compare the Map values + Collections.sort(list, new Comparator>() { + public int compare(Map.Entry o1, Map.Entry o2) { + return (o2.getValue()).compareTo(o1.getValue()); + } + }); + + // Convert sorted map back to a Map + Map sortedMap = new LinkedHashMap(); + for (Iterator> it = list.iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + sortedMap.put(entry.getKey(), entry.getValue()); + } + return sortedMap; + } + + public static Map sortDoubleDESCByLog(Map unsortMap) { + + // Convert Map to List + List> list = new LinkedList>(unsortMap.entrySet()); + + // Sort list with comparator, to compare the Map values + Collections.sort(list, new Comparator>() { + public int compare(Map.Entry o1, Map.Entry o2) { + return (o2.getValue()).compareTo(o1.getValue()); + } + }); + + // Convert sorted map back to a Map + Map sortedMap = new LinkedHashMap(); + for (Iterator> it = list.iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + sortedMap.put(entry.getKey(), entry.getValue()); + } + return sortedMap; + } + + public static Map sortASC(Map unsortMap) { + + // Convert Map to List + List> list = new LinkedList>(unsortMap.entrySet()); + + // Sort list with comparator, to compare the Map values + Collections.sort(list, new Comparator>() { + public int compare(Map.Entry o1, Map.Entry o2) { + return (o1.getValue()).compareTo(o2.getValue()); + } + }); + + // Convert sorted map back to a Map + Map sortedMap = new LinkedHashMap(); + for (Iterator> it = list.iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + sortedMap.put(entry.getKey(), entry.getValue()); + } + return sortedMap; + } +} diff --git a/com/gamingmesh/jobs/stuff/TimeManage.java b/com/gamingmesh/jobs/stuff/TimeManage.java new file mode 100644 index 00000000..dfdb6b14 --- /dev/null +++ b/com/gamingmesh/jobs/stuff/TimeManage.java @@ -0,0 +1,18 @@ + +package com.gamingmesh.jobs.stuff; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + +public class TimeManage { + public static int timeInInt() { + return timeInInt(System.currentTimeMillis()); + } + + public static int timeInInt(Long time) { + SimpleDateFormat formatter = new SimpleDateFormat("YYMMdd"); + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(time); + return Integer.valueOf(formatter.format(calendar.getTime())); + } +} diff --git a/jobConfig.yml b/jobConfig.yml index 93efd231..2f027b4c 100644 --- a/jobConfig.yml +++ b/jobConfig.yml @@ -291,6 +291,19 @@ Jobs: value: true # Permission granted when reaching level 10 level: 10 + # Permissions granted when perticular conditions are meet + conditions: + # Condition mane, irelevent, you can write anything in here + first: + requires: + # j marks that player should have particular jobs level and higher + - j:Miner-50 + - j:Digger-50 + # p marks permission requirement + - p:essentials.notnoob + perform: + # p marks permission, player will get if given true value, if used false, permission will be taken + - p:essentials.fly-true # Commands executed when player reached level commands: # command name, just to have better idea what this do diff --git a/plugin.yml b/plugin.yml index 23f2fb32..a0751ae5 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,7 +1,7 @@ name: Jobs description: Jobs Plugin for the BukkitAPI main: com.gamingmesh.jobs.JobsPlugin -version: 2.48.1 +version: 2.50.1 author: phrstbrn softdepend: [Vault] commands: diff --git a/schedule.yml b/schedule.yml index 1a80541a..1c312580 100644 --- a/schedule.yml +++ b/schedule.yml @@ -5,6 +5,8 @@ # Jobs can be any of your settup job or use All to give for all jobs at once # BroadcastOnStart or BroadcastOnStop - set it false to disable message when boost starts/stops # MessageOnStart or MessageOnStop - optional messages, if not given, then message from locale file will be shown +# BroadcastInterval - how often in minutes to broadcast message about money/exp boost for jobs +# BroadcastMessage - message to show every x minutes Boost: NightBoost: @@ -29,6 +31,11 @@ Boost: - '&e* Boost time for jobs have beed stoped' - '&e* All rates reseted to original ones' - '&e***********************************************' + BroadcastInterval: 15 + BroadcastMessage: + - '&e******************************************************' + - '&e* 2x boost time for all jobs is activated until [until] *' + - '&e******************************************************' ShortMoneyBoost: Enabled: false From: '07:00:00' @@ -52,4 +59,10 @@ Boost: - '&e***********************************************' - '&e* Boost time for Miner and Woodcutter have beed stoped' - '&e* Money rates reseted to original ones' - - '&e***********************************************' \ No newline at end of file + - '&e***********************************************' + BroadcastInterval: 15 + BroadcastMessage: + - '&e******************************************************' + - '&e* 2x money boost time for Miner and Woodcutter jobs' + - '&e* Is activated until [until]' + - '&e******************************************************' \ No newline at end of file