· 8 years ago · Dec 10, 2017, 07:56 AM
1package praxis.slipcor.classranksBP;
2
3import java.io.File;
4import java.io.FileOutputStream;
5import java.io.InputStream;
6import java.net.MalformedURLException;
7import java.util.Map;
8import java.util.jar.JarEntry;
9import java.util.jar.JarFile;
10import java.util.logging.Level;
11import java.util.logging.Logger;
12
13import org.bukkit.ChatColor;
14import org.bukkit.Material;
15import org.bukkit.command.Command;
16import org.bukkit.command.CommandSender;
17import org.bukkit.entity.Player;
18import org.bukkit.event.Event;
19import org.bukkit.event.Event.Priority;
20import org.bukkit.inventory.ItemStack;
21import org.bukkit.plugin.PluginDescriptionFile;
22import org.bukkit.plugin.PluginManager;
23import org.bukkit.plugin.java.JavaPlugin;
24import org.bukkit.util.config.Configuration;
25
26import com.alta189.sqlLibrary.MySQL.mysqlCore;
27import com.alta189.sqlLibrary.SQLite.sqlCore;
28
29import de.bananaco.permissions.Permissions;
30import de.bananaco.permissions.worlds.WorldPermissionsManager;
31import praxis.classranks.register.payment.Method;
32import praxis.slipcor.classranksBP.CRClasses;
33import praxis.slipcor.classranksBP.CRFormats;
34
35/*
36 * main class
37 *
38 * v0.1.4.2 - Reagents => Items ; Cooldown ; Sign usage
39 *
40 * History:
41 *
42 * v0.1.4.0 - Register API
43 * v0.1.3.4 - Fix: cost parsing
44 * - Fix: class change announcement
45 * - Cleanup: static plugin access
46 * - Cleanup: ordering
47 * v0.1.3.3 - Possibility to require items for upranking
48 * v0.1.3.2 - little fix of auto completion, cleanup
49 * v0.1.3.1 - database filling via content.yml
50 * v0.1.3.0 - big rewrite: +SQL, +classadmin
51 * v0.1.2.8 - rewritten config, ready for ingame ranks and permissionsbukkit
52 * v0.1.2.7 - consistency tweaks, removed debugging, username autocomplete
53 * v0.1.2.6 - corrected permission nodes
54 * v0.1.2.3 - world and player color customizable
55 * v0.1.2.0 - renaming for release
56 *
57 * 2do:
58 *
59 * @author slipcor
60 */
61
62public class ClassRanks extends JavaPlugin {
63 private final CRPlayerListener playerListener = new CRPlayerListener();
64 public static CRServerListener serverListener = new CRServerListener();
65 public static WorldPermissionsManager permissionHandler; // Permissions access
66 public static Method method = null; // eConomy access
67 private static Logger Logger; // Logfile access
68 //mySQL access
69 public mysqlCore manageMySQL; // MySQL handler
70 public sqlCore manageSQLite; // SQLite handler
71
72 // Settings Variables
73 public Boolean MySQL = false;
74 public String dbHost = null;
75 public String dbUser = null;
76 public String dbPass = null;
77 public String dbDatabase = null;
78
79 /*
80 * Function that gets executed when players use a command
81 * (non-Javadoc)
82 * @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
83 */
84 public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
85 if ((cmd.getName().equalsIgnoreCase("rankup")) || (cmd.getName().equalsIgnoreCase("rankdown"))) {
86 // if we use the shortcut /rankup or /rankdown, shift the array
87 String[] tStr = new String[args.length+1];
88 System.arraycopy(args, 0, tStr, 1, args.length);
89 tStr[0] = cmd.getName();
90 return CRClasses.parseCommand((Player) sender, tStr);
91 }
92
93 if (cmd.getName().equalsIgnoreCase("class")){
94 // standard class command, parse it!
95 return CRClasses.parseCommand((Player) sender, args);
96 }
97 if (cmd.getName().equalsIgnoreCase("classadmin")) {
98 // admin class command, parse it!
99 return CRClasses.parseAdminCommand((Player) sender, args);
100 }
101 return true;
102 }
103
104 /*
105 * Function that gets executed on plugin activation
106 * (non-Javadoc)
107 * @see org.bukkit.plugin.Plugin#onEnable()
108 */
109 public void onEnable(){
110 Logger = java.util.logging.Logger.getLogger("Minecraft");
111
112 PluginManager pm = getServer().getPluginManager();
113 pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, playerListener, Priority.Normal, this);
114 pm.registerEvent(Event.Type.PLAYER_INTERACT, playerListener, Priority.Normal, this);
115 pm.registerEvent(Event.Type.PLUGIN_ENABLE, serverListener, Priority.Normal, this);
116 pm.registerEvent(Event.Type.PLUGIN_DISABLE, serverListener, Priority.Normal, this);
117
118 loadConfig(); // load the config file
119
120 if (!setupPermissions()) {
121 // Disable plugin, because useless without Permissions
122 getServer().getPluginManager().disablePlugin(this);
123 return;
124 }
125 CRClasses.plugin = this; // hand over plugin
126 PluginDescriptionFile pdfFile = this.getDescription();
127
128 log("v" + pdfFile.getVersion() + " enabled", Level.INFO);
129 }
130
131 /*
132 * Function that stores the values out of the config.yml into the plugin
133 */
134 @SuppressWarnings("unchecked")
135 public void loadConfig() {
136 if(!this.getDataFolder().exists()){
137 this.getDataFolder().mkdir();
138 }
139
140 File fConfig = new File(this.getDataFolder(),"config.yml");
141 if(!fConfig.isFile()){
142 try{ // save the default config.yml (from jar) into the data folder
143 File jarloc = new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getCanonicalFile();
144 if(jarloc.isFile()){
145 JarFile jar = new JarFile(jarloc);
146 JarEntry entry = jar.getJarEntry("config.yml");
147
148 if(entry != null && !entry.isDirectory()){
149 InputStream in = jar.getInputStream(entry);
150 FileOutputStream out = new FileOutputStream(fConfig);
151 byte[] tempbytes = new byte[512];
152 int readbytes = in.read(tempbytes,0,512);
153 while(readbytes>-1){
154 out.write(tempbytes,0,readbytes);
155 readbytes = in.read(tempbytes,0,512);
156 }
157 out.close();
158 in.close();
159
160 log("Created default config.yml", Level.INFO);
161 }
162 }
163 }catch(Exception e){
164 log("Unable to create default config.yml:" + e, Level.INFO);
165 }
166 }
167
168 Configuration config = new Configuration(fConfig);
169 config.load();
170
171 // set prices
172 Map<Integer,String> prices = (Map<Integer,String>) config.getProperty("prices");
173 CRClasses.cost = new double[prices.size()];
174 int i = 0;
175 for (Integer Key : prices.keySet()) {
176 String sVal = prices.get(Key);
177 try {
178 CRClasses.cost[i] = Double.parseDouble(sVal);
179 } catch (Exception e) {
180 CRClasses.cost[i] = 0;
181 log("Unrecognized cost key '" + String.valueOf(Key) + "': "+sVal, Level.INFO);
182 }
183 i++;
184 }
185
186 // set subcolors
187 CRClasses.colPlayer = CRFormats.cColorbyCode(config.getString("playercolor"));
188 CRClasses.colWorld = CRFormats.cColorbyCode(config.getString("worldcolor"));
189
190 // set other variables
191 CRClasses.rankpublic = config.getBoolean("rankpublic", false);
192
193 boolean signs = config.getBoolean("signcheck", false);
194 if (signs) {
195 CRClasses.signCheck[0] = config.getString("signchoose","[choose]");
196 CRClasses.signCheck[1] = config.getString("signrankup","[rankup]");
197 CRClasses.signCheck[2] = config.getString("signrankdown","[rankdown]");
198 }
199
200 CRClasses.coolDown = config.getInt("cooldown", 0);
201
202 ItemStack[][] itemStacks;
203 Map<String, Object> items = (Map<String, Object>) config.getProperty("items");
204 if (items == null) {
205 itemStacks = new ItemStack[3][1];
206 } else {
207 // for each items => ItemStack[][1,2,3]
208 int iI = 0;
209 itemStacks = new ItemStack[items.size()][];
210 for (String isKey : items.keySet()) {
211 String values = (String) items.get(isKey);
212 String[] vStr = values.split(" ");
213 itemStacks[iI] = new ItemStack[vStr.length];
214 for (int iJ = 0 ; iJ < vStr.length ; iJ++) {
215
216 String[] vValue = vStr[iJ].split(":");
217
218 int vAmount = vValue.length > 1 ? Integer.parseInt(vValue[1]) : 1;
219 try {
220 itemStacks[iI][iJ] = new ItemStack(
221 Material.valueOf(vValue[0]),
222 vAmount
223 );
224 } catch (Exception e) {
225 log("Unrecognized reagent: " + vValue[0], Level.WARNING);
226 continue;
227 }
228 }
229 iI++;
230 }
231 }
232
233
234 CRClasses.rankItems = itemStacks;
235
236 // get variables from settings handler
237 if (config.getBoolean("MySQL", false)) {
238 this.MySQL = config.getBoolean("MySQL", false);
239 this.dbHost = config.getString("MySQLhost");
240 this.dbUser = config.getString("MySQLuser");
241 this.dbPass = config.getString("MySQLpass");
242 this.dbDatabase = config.getString("MySQLdb");
243 }
244
245 // Check Settings
246 if (this.MySQL) {
247 if (this.dbHost.equals(null)) { this.MySQL = false; log("MySQL is on, but host is not defined, defaulting to SQLite", Level.SEVERE); }
248 if (this.dbUser.equals(null)) { this.MySQL = false; log("MySQL is on, but username is not defined, defaulting to SQLite", Level.SEVERE); }
249 if (this.dbPass.equals(null)) { this.MySQL = false; log("MySQL is on, but password is not defined, defaulting to SQLite", Level.SEVERE); }
250 if (this.dbDatabase.equals(null)) { this.MySQL = false; log("MySQL is on, but database is not defined, defaulting to SQLite", Level.SEVERE); }
251 }
252
253 // Enabled SQL/MySQL
254 if (this.MySQL) {
255 // Declare MySQL Handler
256 this.manageMySQL = new mysqlCore(Logger, "[ClassRanks] ", this.dbHost, this.dbDatabase, this.dbUser, this.dbPass);
257
258 log("MySQL Initializing", Level.INFO);
259 // Initialize MySQL Handler
260 this.manageMySQL.initialize();
261
262 try {
263 if (this.manageMySQL.checkConnection()) {
264 log("MySQL connection successful", Level.INFO);
265 // Check if the tables exist, if not, create them
266 if (!this.manageMySQL.checkTable("classranks_classes")) {
267 log("Creating table classranks_classes", Level.INFO);
268 String query = "CREATE TABLE `classranks_classes` ( `id` int(3) NOT NULL AUTO_INCREMENT, `classname` varchar(42) NOT NULL, PRIMARY KEY (`id`) ) AUTO_INCREMENT=1 ;";
269 this.manageMySQL.createTable(query);
270 }
271 if (!this.manageMySQL.checkTable("classranks_ranks")) { // Check if the table exists in the database if not create it
272 log("Creating table classranks_ranks", Level.INFO);
273 String query = "CREATE TABLE `classranks_ranks` ( `id` int(4) NOT NULL AUTO_INCREMENT, `cid` int(3) NOT NULL, `oid` int(20) NOT NULL, `permname` varchar(42) NOT NULL, `dispname` varchar(42) DEFAULT NULL, `color` int(2) NOT NULL DEFAULT '15', PRIMARY KEY (`id`) ) AUTO_INCREMENT=1 ;";
274 this.manageMySQL.createTable(query);
275 }
276 } else {
277 log("MySQL connection failed", Level.SEVERE);
278 this.MySQL = false;
279 }
280 } catch (MalformedURLException e) {
281 e.printStackTrace();
282 } catch (InstantiationException e) {
283 e.printStackTrace();
284 } catch (IllegalAccessException e) {
285 e.printStackTrace();
286 }
287 } else {
288 log("SQLite Initializing", Level.INFO);
289
290 // Declare SQLite handler
291 this.manageSQLite = new sqlCore(Logger, "[ClassRanks]", "ClassRanks", this.getDataFolder().toString());
292
293 // Initialize SQLite handler
294 this.manageSQLite.initialize();
295
296 // Check if the tables exist, if not, create them
297 if (!this.manageSQLite.checkTable("classranks_classes")) {
298 log("Creating classranks_classes", Level.INFO);
299 String query = "CREATE TABLE `classranks_classes` ( `id` int(3) PRIMARY KEY, `classname` varchar(42) NOT NULL );";
300 this.manageSQLite.createTable(query); // Use sqlCore.createTable(query) to create tables
301 }
302 if (!this.manageSQLite.checkTable("classranks_ranks")) {
303 log("Creating classranks_ranks", Level.INFO);
304 String query = "CREATE TABLE `classranks_ranks` ( `id` int(4) PRIMARY KEY, `cid` int(3) NOT NULL, `oid` int(20) NOT NULL, `permname` varchar(42) NOT NULL, `dispname` varchar(42) DEFAULT NULL, `color` int(2) NOT NULL DEFAULT '15' );";
305 this.manageSQLite.createTable(query); // Use sqlCore.createTable(query) to create tables
306 }
307 }
308 }
309
310 /*
311 * Function that gets executed on plugin deactivation
312 * (non-Javadoc)
313 * @see org.bukkit.plugin.Plugin#onDisable()
314 */
315 public void onDisable(){
316 log("disabled", Level.INFO);
317 }
318
319 /*
320 * Function that logs a message to the logfile
321 */
322 public static void log(String message, Level level){
323 Logger.log(level,"[ClassRanks] " + message);
324 }
325
326 /*
327 * Function that tries to setup the permissions system, returns result
328 */
329 private boolean setupPermissions() {
330 // try to load permissions, return result
331
332 ClassRanks.permissionHandler = Permissions.getWorldPermissionsManager();
333
334 if(ClassRanks.permissionHandler == null){
335 log("bPermissions not found, deactivating.", Level.SEVERE);
336 return false;
337 }
338 log("<3 bPermissions", Level.INFO);
339 return true;
340 }
341
342 /*
343 * Function that adds a prefix to a string and sends that to given player
344 */
345 public static void pmsg(Player pPlayer, String string) {
346 pPlayer.sendMessage("[" + ChatColor.AQUA + "ClassRanks" + ChatColor.WHITE + "] " + string);
347 }
348
349 /*
350 * Function that loads the database with values given in content.yml
351 */
352 @SuppressWarnings("unchecked")
353 public void loadDatabase(Player pPlayer) {
354 File fConfig = new File(this.getDataFolder(),"content.yml");
355 if(!fConfig.isFile()){
356 try{ // save the default config.yml (from jar) into the data folder
357 File jarloc = new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getCanonicalFile();
358 if(jarloc.isFile()){
359 JarFile jar = new JarFile(jarloc);
360 JarEntry entry = jar.getJarEntry("content.yml");
361
362 if(entry != null && !entry.isDirectory()){
363 InputStream in = jar.getInputStream(entry);
364 FileOutputStream out = new FileOutputStream(fConfig);
365 byte[] tempbytes = new byte[512];
366 int readbytes = in.read(tempbytes,0,512);
367 while(readbytes>-1){
368 out.write(tempbytes,0,readbytes);
369 readbytes = in.read(tempbytes,0,512);
370 }
371 out.close();
372 in.close();
373
374 log("Created default content.yml", Level.INFO);
375 }
376 }
377 }catch(Exception e){
378 log("Unable to create default content.yml:" + e, Level.INFO);
379 }
380 }
381
382 Configuration config = new Configuration(fConfig);
383 config.load();
384
385 Map<String, Object> contents = (Map<String,Object>) config.getProperty("classes");
386 for (String cClass : contents.keySet()) {
387 log(cClass, Level.INFO);
388 boolean first = true;
389 Map<String, String> ranks = (Map<String,String>) contents.get(cClass);
390 for (String rRank : ranks.keySet()) {
391 log(rRank, Level.INFO);
392 if (first) {
393 // class add
394 CRClasses.configClassAdd(cClass, rRank, ranks.get(rRank), pPlayer);
395 first = false;
396 } else {
397 // rank add
398 CRClasses.configRankAdd(cClass, rRank, ranks.get(rRank), pPlayer);
399 }
400 }
401 }
402 }
403}