1
0
mirror of https://github.com/Zrips/Jobs.git synced 2024-11-25 20:16:13 +01:00

Added loggin functionalaty, still in experimental stage

This commit is contained in:
Zrips 2015-09-17 10:48:10 +03:00
parent 320b9c08f4
commit f41b968f29
37 changed files with 2603 additions and 1628 deletions

View File

@ -1,4 +1,4 @@
package Gui;
package com.gamingmesh.jobs.Gui;
import java.util.ArrayList;
import java.util.List;

View File

@ -1,4 +1,4 @@
package Gui;
package com.gamingmesh.jobs.Gui;
import java.util.ArrayList;
import java.util.HashMap;

View File

@ -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<Log> 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);
}
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}
}
}
}
}

View File

@ -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<String, JobsPlayer> players = Collections.synchronizedMap(new HashMap<String, JobsPlayer>());
private Map<String, JobsPlayer> players = new HashMap<String, JobsPlayer>();
private Map<String, JobsPlayer> players = Collections.synchronizedMap(new HashMap<String, JobsPlayer>());
//private Map<String, JobsPlayer> players = new HashMap<String, JobsPlayer>();
/**
* 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()));
}
}
}
}
}
/**

View File

@ -1,4 +1,4 @@
package Signs;
package com.gamingmesh.jobs.Signs;
public class Sign {

View File

@ -1,4 +1,4 @@
package Signs;
package com.gamingmesh.jobs.Signs;
import java.util.ArrayList;
import java.util.List;

View File

@ -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<Signs.Sign> Copy = new ArrayList<Signs.Sign>(Signs.GetAllSigns().size());
for (Signs.Sign foo : Signs.GetAllSigns()) {
List<com.gamingmesh.jobs.Signs.Sign> Copy = new ArrayList<com.gamingmesh.jobs.Signs.Sign>(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);

View File

@ -1,2 +1,3 @@
/JobCommand.class
/JobsCommands.class
/JobsCommands$1.class

View File

@ -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<Log> logList = JPlayer.getLog();
//
// if (logList.size() == 0)
// return true;
//
// for (Log one : logList) {
//
// HashMap<String, LogAmounts> AmountList = one.getAmountList();
//
// for (Entry<String, LogAmounts> 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<Log> logList = JPlayer.getLog();
if (logList.size() == 0)
return true;
Map<String, Double> unsortMap = new HashMap<String, Double>();
for (Log one : logList) {
HashMap<String, LogAmounts> AmountList = one.getAmountList();
for (Entry<String, LogAmounts> 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<String, LogAmounts> AmountList = one.getAmountList();
for (Entry<String, Double> oneSorted : unsortMap.entrySet()) {
for (Entry<String, LogAmounts> 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<LogAmounts, Double> unsortMap = new HashMap<LogAmounts, Double>();
Collection<? extends Player> onlineP = Bukkit.getOnlinePlayers();
sender.sendMessage("Looking for players data");
for (Player OneP : onlineP) {
JobsPlayer JPlayer = Jobs.getPlayerManager().getJobsPlayer(OneP);
if (JPlayer == null)
continue;
List<Log> logList = JPlayer.getLog();
if (logList.size() == 0)
continue;
for (Log one : logList) {
HashMap<String, LogAmounts> AmountList = one.getAmountList();
for (Entry<String, LogAmounts> 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<LogAmounts, Double> 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

View File

@ -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<Job> jobs = new ArrayList<Job>();
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<Job> jobs = new ArrayList<Job>();
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<JobPermission> jobPermissions = new ArrayList<JobPermission>();
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> jobConditions = new ArrayList<JobConditions>();
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<String> requires = permissionSection.getStringList("requires");
List<String> 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<JobPermission> jobPermissions = new ArrayList<JobPermission>();
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<String> JobsCommandOnLeave = new ArrayList<String>();
if (jobSection.isList("cmd-on-leave")) {
JobsCommandOnLeave = jobSection.getStringList("cmd-on-leave");
}
// Command on join
List<String> JobsCommandOnJoin = new ArrayList<String>();
if (jobSection.isList("cmd-on-join")) {
JobsCommandOnJoin = jobSection.getStringList("cmd-on-join");
}
// Commands
ArrayList<JobCommands> jobCommand = new ArrayList<JobCommands>();
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> jobItems = new ArrayList<JobItems>();
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<String> lore = new ArrayList<String>();
for (String eachLine : itemSection.getStringList("lore")) {
lore.add(org.bukkit.ChatColor.translateAlternateColorCodes('&', eachLine));
}
List<String> enchants = new ArrayList<String>();
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> jobInfo = new ArrayList<JobInfo>();
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<String> JobsCommandOnLeave = new ArrayList<String>();
if (jobSection.isList("cmd-on-leave")) {
JobsCommandOnLeave = jobSection.getStringList("cmd-on-leave");
}
// Command on join
List<String> JobsCommandOnJoin = new ArrayList<String>();
if (jobSection.isList("cmd-on-join")) {
JobsCommandOnJoin = jobSection.getStringList("cmd-on-join");
}
// Commands
ArrayList<JobCommands> jobCommand = new ArrayList<JobCommands>();
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> jobItems = new ArrayList<JobItems>();
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<String> lore = new ArrayList<String>();
for (String eachLine : itemSection.getStringList("lore")) {
lore.add(org.bukkit.ChatColor.translateAlternateColorCodes('&', eachLine));
}
List<String> enchants = new ArrayList<String>();
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> jobInfo = new ArrayList<JobInfo>();
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();
//}
}
}

View File

@ -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"));

View File

@ -20,3 +20,4 @@
/Schedule.class
/Log.class
/LogAmounts.class
/JobConditions.class

View File

@ -38,6 +38,8 @@ public class Job {
private List<JobPermission> jobPermissions;
// commands
private List<JobCommands> jobCommands;
// conditions
private List<JobConditions> jobConditions;
// items
private List<JobItems> 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<JobPermission> jobPermissions, List<JobCommands> jobCommands, List<JobItems> jobItems, List<String> CmdOnJoin, List<String> CmdOnLeave, ItemStack GUIitem) {
public Job(String jobName, String jobShortName, String description, ChatColor jobColour, Parser maxExpEquation, DisplayMethod displayMethod, int maxLevel, int vipmaxLevel, Integer maxSlots, List<JobPermission> jobPermissions, List<JobCommands> jobCommands, List<JobConditions> jobConditions, List<JobItems> jobItems, List<String> CmdOnJoin, List<String> 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<JobCommands> getCommands() {
return Collections.unmodifiableList(jobCommands);
}
/**
* Get the conditions for this job
* @return Conditions for this job
*/
public List<JobConditions> getConditions() {
return Collections.unmodifiableList(jobConditions);
}
/**
* Get the item nodes for this job

View File

@ -0,0 +1,45 @@
/**
* Jobs Plugin for Bukkit
* Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com>
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.gamingmesh.jobs.container;
import java.util.List;
public class JobConditions {
private String node;
private List<String> requires;
private List<String> perform;
public JobConditions(String node, List<String> requires, List<String> perform) {
this.node = node;
this.requires = requires;
this.perform = perform;
}
public String getNode() {
return node;
}
public List<String> getRequires() {
return requires;
}
public List<String> getPerform() {
return perform;
}
}

View File

@ -52,7 +52,7 @@ public class JobsPlayer {
// save lock
public final Object saveLock = new Object();
// log
private List<Log> logList = new ArrayList<Log>();
@ -87,11 +87,15 @@ public class JobsPlayer {
}
return jPlayer;
}
public static void loadLogFromDao(JobsPlayer jPlayer) {
Jobs.getJobsDAO().loadLog(jPlayer);
}
public List<Log> 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);
}
}

View File

@ -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<String, LogAmounts> amountMap = new HashMap<String, LogAmounts>();
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<String, LogAmounts> 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;
}
}

View File

@ -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;
}
}

View File

@ -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<String> Days = new ArrayList<String>(Arrays.asList("all"));
List<Job> JobsList = new ArrayList<Job>();
List<String> Days = new ArrayList<String>(Arrays.asList("all"));
List<Job> JobsList = new ArrayList<Job>();
List<String> MessageOnStart = new ArrayList<String>();
List<String> MessageOnStop = new ArrayList<String>();
List<String> MessageOnStart = new ArrayList<String>();
List<String> MessageOnStop = new ArrayList<String>();
boolean started = false;
boolean stoped = true;
List<String> MessageToBroadcast = new ArrayList<String>();
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<String> JobsNameList) {
for (int z = 0; z < JobsNameList.size(); z++) {
if (JobsNameList.get(z).equalsIgnoreCase("all")) {
JobsList.clear();
List<Job> 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<Job> GetJobs() {
return this.JobsList;
}
public void setDays(List<String> 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<String> GetDays() {
return this.Days;
}
public void setMessageOnStart(List<String> msg, String From, String Until) {
List<String> temp = new ArrayList<String>();
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<String> GetMessageOnStart() {
return this.MessageOnStart;
}
public void setMessageOnStop(List<String> msg, String From, String Until) {
List<String> temp = new ArrayList<String>();
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<String> GetMessageOnStop() {
return this.MessageOnStop;
}
public void setMessageToBroadcast(List<String> msg, String From, String Until) {
List<String> temp = new ArrayList<String>();
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<String> 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<String> JobsNameList) {
for (int z = 0; z < JobsNameList.size(); z++) {
if (JobsNameList.get(z).equalsIgnoreCase("all")) {
JobsList.clear();
List<Job> 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<Job> GetJobs() {
return this.JobsList;
}
public void setDays(List<String> Days) {
for (int z = 0; z < Days.size(); z++) {
Days.set(z, Days.get(z).toLowerCase());
}
this.Days = Days;
}
public List<String> GetDays() {
return this.Days;
}
public void setMessageOnStart(List<String> msg) {
List<String> temp = new ArrayList<String>();
for (String one : msg) {
temp.add(ChatColor.translateAlternateColorCodes('&', one));
}
this.MessageOnStart.addAll(temp);
}
public List<String> GetMessageOnStart() {
return this.MessageOnStart;
}
public void setMessageOnStop(List<String> msg) {
List<String> temp = new ArrayList<String>();
for (String one : msg) {
temp.add(ChatColor.translateAlternateColorCodes('&', one));
}
this.MessageOnStop.addAll(temp);
}
public List<String> GetMessageOnStop() {
return this.MessageOnStop;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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<String> usernames = new ArrayList<String>();
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<String> usernames = new ArrayList<String>();
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 {
}
}
}

View File

@ -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<String> usernames = new ArrayList<String>();
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<String> usernames = new ArrayList<String>();
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 {
}
}
}

View File

@ -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)));
}
}
}

View File

@ -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);
}

View File

@ -66,4 +66,5 @@ public class VaultEconomy implements Economy {
public String format(double money) {
return vault.format(money);
}
}

View File

@ -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);

View File

@ -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

View File

@ -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<Log> 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<Log> 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);
}
}
}

View File

@ -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<String> 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;

View File

@ -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<String, Integer> sortDESC(Map<String, Integer> unsortMap) {
// Convert Map to List
List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());
// Sort list with comparator, to compare the Map values
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
// Convert sorted map back to a Map
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext();) {
Map.Entry<String, Integer> entry = it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static Map<String, Double> sortDoubleDESC(Map<String, Double> unsortMap) {
// Convert Map to List
List<Map.Entry<String, Double>> list = new LinkedList<Map.Entry<String, Double>>(unsortMap.entrySet());
// Sort list with comparator, to compare the Map values
Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
// Convert sorted map back to a Map
Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
for (Iterator<Map.Entry<String, Double>> it = list.iterator(); it.hasNext();) {
Map.Entry<String, Double> entry = it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static Map<LogAmounts, Double> sortDoubleDESCByLog(Map<LogAmounts, Double> unsortMap) {
// Convert Map to List
List<Map.Entry<LogAmounts, Double>> list = new LinkedList<Map.Entry<LogAmounts, Double>>(unsortMap.entrySet());
// Sort list with comparator, to compare the Map values
Collections.sort(list, new Comparator<Map.Entry<LogAmounts, Double>>() {
public int compare(Map.Entry<LogAmounts, Double> o1, Map.Entry<LogAmounts, Double> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
// Convert sorted map back to a Map
Map<LogAmounts, Double> sortedMap = new LinkedHashMap<LogAmounts, Double>();
for (Iterator<Map.Entry<LogAmounts, Double>> it = list.iterator(); it.hasNext();) {
Map.Entry<LogAmounts, Double> entry = it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static Map<String, Integer> sortASC(Map<String, Integer> unsortMap) {
// Convert Map to List
List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());
// Sort list with comparator, to compare the Map values
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
// Convert sorted map back to a Map
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext();) {
Map.Entry<String, Integer> entry = it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}

View File

@ -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()));
}
}

View File

@ -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

View File

@ -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:

View File

@ -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***********************************************'
- '&e***********************************************'
BroadcastInterval: 15
BroadcastMessage:
- '&e******************************************************'
- '&e* 2x money boost time for Miner and Woodcutter jobs'
- '&e* Is activated until [until]'
- '&e******************************************************'