Advertisement
Guest User

Untitled

a guest
Jan 31st, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.05 KB | None | 0 0
  1. package io.github.mikey.TrustedGamesBattle;
  2.  
  3. import java.util.Timer;
  4. import java.util.TimerTask;
  5.  
  6. import org.bukkit.Bukkit;
  7. import org.bukkit.ChatColor;
  8. import org.bukkit.Material;
  9. import org.bukkit.entity.Player;
  10. import org.bukkit.event.EventHandler;
  11. import org.bukkit.event.Listener;
  12. import org.bukkit.inventory.ItemStack;
  13. import org.bukkit.plugin.java.JavaPlugin;
  14.  
  15. import com.mewin.WGRegionEvents.events.RegionEnterEvent;
  16. import com.mewin.WGRegionEvents.events.RegionLeaveEvent;
  17.  
  18. import io.github.mikey.TrustedGamesBattle.Backend.BackendManager;
  19. import io.github.mikey.TrustedGamesBattle.Backend.MySQL;
  20. import io.github.mikey.TrustedGamesBattle.Config.ConfigManager;
  21.  
  22. public class Main extends JavaPlugin implements Listener {
  23.  
  24.     ConfigManager ConfigManager;
  25.     MySQL Connection;
  26.     BackendManager BackendManager;
  27.     Timer autoUpdater;
  28.    
  29.     public void onEnable()
  30.     {
  31.         ConfigManager = new ConfigManager(this);
  32.         Connection = new MySQL(this, ConfigManager.getMySQLAddress(), ConfigManager.getMySQLPort(), ConfigManager.getMySQLDatabaseName(), "MySQLInventories", ConfigManager.getMySQLUsername(), ConfigManager.getMySQLPassword());
  33.         Connection.dbConnect();
  34.         BackendManager = new BackendManager(this, Connection);
  35.         this.getServer().getPluginManager().registerEvents(this, this);
  36.         autoUpdater = new Timer();
  37.         if(!(ConfigManager.getUpdateDelay() <= 0))
  38.         {
  39.             startAutoUpdater(ConfigManager.getUpdateDelay());
  40.         }
  41.     }
  42.    
  43.     @SuppressWarnings("deprecation")
  44.     public void onDisable()
  45.     {
  46.         Bukkit.getServer().getScheduler().cancelAllTasks();
  47.         Bukkit.getServer().getScheduler().cancelTasks(this);
  48.         autoUpdater.cancel();
  49.         if(Bukkit.getOnlinePlayers().length > 0)
  50.     {
  51.            
  52.     }
  53.         }
  54.    
  55.    
  56.     private void startAutoUpdater(int delay)
  57.     {
  58.         delay = delay * 1000;
  59.         autoUpdater.scheduleAtFixedRate(new TimerTask() {
  60.               @SuppressWarnings("deprecation")
  61.             @Override
  62.               public void run()
  63.               {
  64.                   if(Connection.isConnected())
  65.                   {
  66.                       if(Bukkit.getOnlinePlayers().length > 0)
  67.                       {
  68.                           for(Player p : Bukkit.getOnlinePlayers())
  69.                           {
  70.                               BackendManager.saveInventory(p);
  71.                           }
  72.                       }
  73.                   }
  74.                   else
  75.                   {
  76.                       Connection.dbConnect();
  77.                   }
  78.               }
  79.         }, delay, delay);
  80.     }
  81.    
  82.     @EventHandler
  83.     public void onRegionEnter(RegionEnterEvent e){
  84.         if (e.getRegion().getId().contains("battle")) {
  85.             if(ConfigManager.getSaveOnRegionEnter())
  86.             {
  87.                 BackendManager.saveInventory(e.getPlayer());
  88.                 e.getPlayer().getInventory().clear();
  89.                 e.getPlayer().getInventory().setArmorContents(null);
  90.                 e.getPlayer().getInventory().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS));
  91.                 e.getPlayer().getInventory().setBoots(new ItemStack(Material.DIAMOND_BOOTS));
  92.                 e.getPlayer().getInventory().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE));
  93.                 e.getPlayer().getInventory().setHelmet(new ItemStack(Material.DIAMOND_HELMET));
  94.                 e.getPlayer().getInventory().addItem(new ItemStack(Material.DIAMOND_SWORD));
  95.                 e.getPlayer().getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE,1,(short)1));
  96.                 e.getPlayer().sendMessage(ChatColor.DARK_BLUE + "" + ChatColor.BOLD + "[" + ChatColor.BLUE + "TG" + " " + "Battle" + ChatColor.DARK_BLUE + ChatColor.BOLD + "]" + ChatColor.RESET + ChatColor.RED + "Kill Your Opponent For A Reward");
  97.                 }else e.setCancelled(true);
  98.          }
  99.     }
  100.    
  101.    
  102.     @EventHandler
  103.     public void onRegionLeave(RegionLeaveEvent e){
  104.         if (e.getRegion().getId().contains("battle")){             
  105.             }
  106.                
  107.     {
  108.        
  109.         BackendManager.restoreInventory(e.getPlayer());
  110.     }
  111.     }
  112.     }
  113.  
  114. package io.github.mikey.TrustedGamesBattle.Backend;
  115.  
  116. import java.sql.PreparedStatement;
  117. import java.sql.ResultSet;
  118. import java.sql.SQLException;
  119.  
  120. import org.bukkit.entity.Player;
  121. import org.bukkit.inventory.ItemStack;
  122. import org.bukkit.plugin.java.JavaPlugin;
  123. import org.bukkit.scheduler.BukkitRunnable;
  124.  
  125. public class BackendManager {
  126.    
  127.     private JavaPlugin plugin;
  128.     private MySQL connection;
  129.    
  130.     public BackendManager(JavaPlugin plugin, MySQL connection)
  131.     {
  132.         this.plugin = plugin;
  133.         this.connection = connection;
  134.     }
  135.    
  136.     public void saveInventory(Player player)
  137.     {
  138.         ItemStack[] contents = player.getInventory().getContents();
  139.         ItemStack[] armor = player.getInventory().getArmorContents();
  140.         saveInventory(player.getName(), contents, armor);
  141.     }
  142.    
  143.     public void saveInventory(String player, ItemStack[] contents, ItemStack[] armor)
  144.     {
  145.         new SaveTask(player, contents, armor).runTaskAsynchronously(this.plugin);
  146.     }
  147.    
  148.     public void restoreInventory(Player p)
  149.     {
  150.         p.getInventory().clear();
  151.         p.getInventory().setArmorContents(null);
  152.         new RestoreTask(p).runTaskAsynchronously(this.plugin);
  153.     }
  154.        
  155.     private class SaveTask extends BukkitRunnable {
  156.        
  157.         String player;
  158.         ItemStack[] contents;
  159.         ItemStack[] armor;
  160.        
  161.         public SaveTask(String player, ItemStack[] contents, ItemStack[] armor)
  162.         {
  163.             this.player = player;
  164.             this.contents = contents;
  165.             this.armor = armor;
  166.         }
  167.        
  168.         public void run()
  169.         {
  170.             byte[] contentsByte = Serializer.Serialize(contents);
  171.             byte[] armorByte = Serializer.Serialize(armor);
  172.                        
  173.             try {
  174.                 PreparedStatement prest1 = connection.getConnection().prepareStatement("SELECT * FROM MySQLInventories WHERE Player=?");
  175.                 prest1.setString(1, player);
  176.                 ResultSet result = prest1.executeQuery();
  177.                 if(!result.next())
  178.                 {
  179.                     PreparedStatement prest2 = connection.getConnection().prepareStatement("INSERT INTO MySQLInventories (Player, Inventory, Armor) VALUES (?, ?, ?)");
  180.                     prest2.setString(1, player);
  181.                     prest2.setBytes(2, contentsByte);
  182.                     prest2.setBytes(3, armorByte);
  183.                     prest2.executeUpdate();
  184.                 }
  185.                 else
  186.                 {
  187.                     PreparedStatement prest2 = connection.getConnection().prepareStatement("UPDATE MySQLInventories SET Inventory=?, Armor=? WHERE Player=?");
  188.                     prest2.setBytes(1, contentsByte);
  189.                     prest2.setBytes(2, armorByte);
  190.                     prest2.setString(3, player);
  191.                     prest2.executeUpdate();
  192.                 }
  193.             } catch (SQLException e) {
  194.                 e.printStackTrace();
  195.             }
  196.         }
  197.     }
  198.    
  199.     private class RestoreTask extends BukkitRunnable {
  200.        
  201.         Player player;
  202.        
  203.         public RestoreTask(Player player)
  204.         {
  205.             this.player = player;
  206.         }
  207.        
  208.         public void run()
  209.         {
  210.            
  211.             PreparedStatement prest1;
  212.             try {
  213.                 prest1 = connection.getConnection().prepareStatement("SELECT * FROM MySQLInventories WHERE Player=?");
  214.                 prest1.setString(1, player.getName());
  215.                 ResultSet result = prest1.executeQuery();
  216.                 if(result.next())
  217.                 {
  218.                     final ItemStack[] contents = Serializer.Deserialize(result.getBytes(2), false);
  219.                     final ItemStack[] armor = Serializer.Deserialize(result.getBytes(3), true);
  220.                     // Restore the ItemStack's using a thread-safe sync task
  221.                     plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
  222.                         public void run() {
  223.                             player.getInventory().setContents(contents);
  224.                             player.getInventory().setArmorContents(armor);
  225.                             player.updateInventory();
  226.                         }
  227.                     });
  228.                 }
  229.                
  230.             } catch (SQLException e) {
  231.                 e.printStackTrace();
  232.             }
  233.         }
  234.     }
  235.  
  236. }
  237.  
  238. package io.github.mikey.TrustedGamesBattle.Backend;
  239.  
  240. import java.io.ByteArrayOutputStream;
  241. import java.io.IOException;
  242. import java.util.zip.GZIPOutputStream;
  243.  
  244. public class Compression {
  245.  
  246.  
  247.    
  248.     public static byte[] compress(byte[] content){
  249.             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  250.             try{
  251.                 GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
  252.                 gzipOutputStream.write(content);
  253.                 gzipOutputStream.close();
  254.             } catch(IOException e){
  255.                 throw new RuntimeException(e);
  256.             }
  257.             return byteArrayOutputStream.toByteArray();
  258.         }
  259.  
  260.         public static byte[] decompress(byte[] contentBytes){          
  261.             java.io.ByteArrayInputStream bytein = new java.io.ByteArrayInputStream(contentBytes);
  262.             java.util.zip.GZIPInputStream gzin = null;
  263.             try {
  264.                 gzin = new java.util.zip.GZIPInputStream(bytein);
  265.             } catch (IOException e) {
  266.                 e.printStackTrace();
  267.             }
  268.             java.io.ByteArrayOutputStream byteout = new java.io.ByteArrayOutputStream();
  269.  
  270.             int res = 0;
  271.             byte buf[] = new byte[1024];
  272.             while (res >= 0) {
  273.                 try {
  274.                     res = gzin.read(buf, 0, buf.length);
  275.                 } catch (IOException e) {
  276.                     e.printStackTrace();
  277.                 }
  278.                 if (res > 0) {
  279.                     byteout.write(buf, 0, res);
  280.                 }
  281.             }
  282.             return byteout.toByteArray();
  283.         }
  284.    
  285.    
  286.  
  287.    
  288.    
  289. }
  290.  
  291. package io.github.mikey.TrustedGamesBattle.Backend;
  292.  
  293. import java.sql.Connection;
  294. import java.sql.DatabaseMetaData;
  295. import java.sql.DriverManager;
  296. import java.sql.ResultSet;
  297. import java.sql.SQLException;
  298. import java.sql.Statement;
  299.  
  300. import org.bukkit.plugin.java.JavaPlugin;
  301. import org.bukkit.scheduler.BukkitRunnable;
  302.  
  303. public class MySQL {
  304.    
  305.     public MySQL(JavaPlugin plugin, String host, int port, String database, String table, String username, String password)
  306.     {
  307.         strUri = "jdbc:mysql://" + host + ":" + port + "/" + database;
  308.         strUser = username;
  309.         strPassword = password;
  310.         this.plugin = plugin;
  311.         strTable = table;
  312.     }
  313.      
  314.     public Connection conn = null;
  315.     public Statement stmt = null;
  316.     public boolean dbConnSuccess = false;
  317.    
  318.     public String strUri = "jdbc:mysql://localhost:3300/database";
  319.     public String strUser;
  320.     public String strPassword;
  321.     public String strTable;
  322.     private JavaPlugin plugin;
  323.    
  324.     public void dbConnect(){
  325.         new ConnectTask().runTaskAsynchronously(this.plugin);
  326.     }
  327.    
  328.     public ResultSet dbStm(String s){
  329.         ResultSet results = null;
  330.         try {
  331.             results = stmt.executeQuery(s);
  332.         } catch (SQLException e) {
  333.             e.printStackTrace();
  334.         }
  335.         return results;
  336.     }
  337.    
  338.     public Connection getConnection()
  339.     {
  340.         return conn;
  341.     }
  342.    
  343.     public void executeUpdate(String s){
  344.         try {
  345.             stmt.executeUpdate(s);
  346.         } catch (SQLException e) {
  347.             e.printStackTrace();
  348.         }
  349.     }
  350.    
  351.     public void checkConnection()
  352.     {
  353.         try {
  354.             if(this.conn.isClosed())
  355.             {
  356.                 dbConnect();
  357.             }
  358.         } catch (SQLException e) {
  359.             e.printStackTrace();
  360.         }
  361.     }
  362.    
  363.     public boolean isConnected()
  364.     {
  365.         try {
  366.             return !this.conn.isClosed();
  367.         } catch (SQLException e) {
  368.         }
  369.         return false;
  370.     }
  371.    
  372.     private class ConnectTask extends BukkitRunnable {
  373.         public void run() {
  374.             try {
  375.                 Class.forName("com.mysql.jdbc.Driver");
  376.             } catch (ClassNotFoundException e) {
  377.                 System.out.print("[MySQLInventories] Fatal error connecting to MySQL:");
  378.                 e.printStackTrace();
  379.                 return;
  380.             }
  381.             try {
  382.                 conn = DriverManager.getConnection(strUri, strUser, strPassword);
  383.             } catch (SQLException e) {
  384.                 System.out.print("[MySQLInventories] Fatal error connecting to MySQL:");
  385.                 e.printStackTrace();
  386.                 return;
  387.             }
  388.             try {
  389.                 stmt = conn.createStatement();
  390.             } catch (SQLException e) {
  391.                 System.out.print("[MySQLInventories] Fatal error connecting to MySQL:");
  392.                 e.printStackTrace();
  393.                 return;
  394.             }
  395.             System.out.print("[MySQLInventories] Successfully connected to MySQL.");
  396.             dbConnSuccess = true;
  397.            
  398.             try {
  399.                 DatabaseMetaData metadata = conn.getMetaData();
  400.                 ResultSet resultSet;
  401.                 resultSet = metadata.getTables(null, null, "MySQLInventories", null);
  402.                 if(!resultSet.next())
  403.                 {
  404.                     System.out.print("[MySQLInventories] Creating new MySQL table.");
  405.                     executeUpdate("CREATE TABLE MySQLInventories (Player VARCHAR(16), Inventory BLOB, Armor BLOB);");
  406.                 }
  407.                
  408.             } catch (SQLException e) {
  409.                 System.out.print("[MySQLInventories] Fatal error creating MySQL table:");
  410.                 e.printStackTrace();
  411.             }
  412.            
  413.         }
  414.     }
  415.  
  416. }
  417.  
  418.  
  419. package io.github.mikey.TrustedGamesBattle.Backend;
  420.  
  421. import java.io.UnsupportedEncodingException;
  422.  
  423. import org.bukkit.configuration.InvalidConfigurationException;
  424. import org.bukkit.configuration.file.YamlConfiguration;
  425. import org.bukkit.inventory.ItemStack;
  426.  
  427. public class Serializer {
  428.    
  429.     public static byte[] Serialize(ItemStack[] items)
  430.     {
  431.         String converted = "";
  432.         YamlConfiguration config = new YamlConfiguration();
  433.         if(items.length > 0)
  434.         {
  435.             int num = 0;
  436.             for(ItemStack item : items)
  437.             {
  438.                 if(item != null)
  439.                 {
  440.                     config.set(Integer.toString(num), item);
  441.                 }
  442.                 num += 1;
  443.             }
  444.         }
  445.         converted = config.saveToString();
  446.         byte[] compressed;
  447.         try {
  448.             compressed = Compression.compress(converted.getBytes("ASCII"));
  449.             return compressed;
  450.         } catch (UnsupportedEncodingException e) {
  451.             e.printStackTrace();
  452.         }
  453.         return null;
  454.     }
  455.    
  456.     public static ItemStack[] Deserialize(byte[] data, boolean armor)
  457.     {
  458.         byte[] decompressed = Compression.decompress(data);
  459.         String text = "";
  460.         try {
  461.             text = new String(decompressed, "ASCII");
  462.         } catch (UnsupportedEncodingException e1) {
  463.             e1.printStackTrace();
  464.         }
  465.         YamlConfiguration config = new YamlConfiguration();
  466.         try {
  467.             config.loadFromString(text);
  468.         } catch (InvalidConfigurationException e) {
  469.             e.printStackTrace();
  470.         }
  471.         ItemStack[] items = null;
  472.         if(config.getKeys(false).size() > 0)
  473.         {
  474.             if(armor)
  475.             {
  476.                 items = new ItemStack[4];
  477.             }
  478.             else
  479.             {
  480.                 items = new ItemStack[36];
  481.             }
  482.        
  483.             for(String key : config.getKeys(false))
  484.             {
  485.                 items[Integer.parseInt(key)] = config.getItemStack(key);
  486.             }
  487.         }
  488.         return items;
  489.     }
  490.  
  491. }
  492.  
  493. package io.github.mikey.TrustedGamesBattle.Config;
  494.  
  495. import java.io.File;
  496. import java.io.IOException;
  497.  
  498. import org.bukkit.plugin.java.JavaPlugin;
  499.  
  500. public class ConfigManager {
  501.    
  502.     private JavaPlugin plugin;
  503.     private File configFile;
  504.    
  505.     public ConfigManager(JavaPlugin plugin)
  506.     {
  507.         this.plugin = plugin;
  508.         if(!plugin.getDataFolder().exists())
  509.         {
  510.             plugin.getDataFolder().mkdir();
  511.         }
  512.         configFile = new File(plugin.getDataFolder() + "/config.yml");
  513.         if(!configFile.exists())
  514.         {
  515.             try {
  516.                 configFile.createNewFile();
  517.             } catch (IOException e) {
  518.                 e.printStackTrace();
  519.             }
  520.             setDefaults();
  521.             saveConfig();
  522.         }
  523.     }
  524.    
  525.     public void saveConfig()
  526.     {
  527.         try {
  528.             this.plugin.getConfig().save(configFile);
  529.         } catch (IOException e) {
  530.             e.printStackTrace();
  531.         }
  532.     }
  533.    
  534.     public void setDefaults()
  535.     {
  536.         setMySQLAddress("localhost");
  537.         setMySQLPort(3306);
  538.         setMySQLDatabaseName("inventories");
  539.         setMySQLUsername("root");
  540.         setMySQLPassword("password");
  541.         setSaveOnRegionEnter(true);
  542.         setUpdateDelay(300);
  543.     }
  544.    
  545.     public void setMySQLAddress(String value)
  546.     {
  547.         this.plugin.getConfig().set("mysql.address", value);
  548.     }
  549.    
  550.     public void setMySQLPort(int value)
  551.     {
  552.         this.plugin.getConfig().set("mysql.port", value);
  553.     }
  554.    
  555.     public void setMySQLDatabaseName(String value)
  556.     {
  557.         this.plugin.getConfig().set("mysql.database", value);
  558.     }
  559.    
  560.     public void setMySQLUsername(String value)
  561.     {
  562.         this.plugin.getConfig().set("mysql.username", value);
  563.     }
  564.    
  565.     public void setMySQLPassword(String value)
  566.     {
  567.         this.plugin.getConfig().set("mysql.password", value);
  568.     }
  569.    
  570.     public void setSaveOnRegionEnter(boolean value)
  571.     {
  572.         this.plugin.getConfig().set("save-on-quit", value);
  573.     }
  574.    
  575.     public void setUpdateDelay(int value)
  576.     {
  577.         this.plugin.getConfig().set("auto-upload-delay", value);
  578.     }
  579.    
  580.     public String getMySQLAddress()
  581.     {
  582.         return this.plugin.getConfig().getString("mysql.address");
  583.     }
  584.    
  585.     public int getMySQLPort()
  586.     {
  587.         return this.plugin.getConfig().getInt("mysql.port");
  588.     }
  589.    
  590.     public String getMySQLDatabaseName()
  591.     {
  592.         return this.plugin.getConfig().getString("mysql.database");
  593.     }
  594.    
  595.     public String getMySQLUsername()
  596.     {
  597.         return this.plugin.getConfig().getString("mysql.username");
  598.     }
  599.    
  600.     public String getMySQLPassword()
  601.     {
  602.         return this.plugin.getConfig().getString("mysql.password");
  603.     }
  604.    
  605.     public boolean getSaveOnRegionEnter()
  606.     {
  607.         return this.plugin.getConfig().getBoolean("save-on-quit");
  608.     }
  609.    
  610.     public int getUpdateDelay()
  611.     {
  612.         return this.plugin.getConfig().getInt("auto-upload-delay");
  613.     }
  614.  
  615. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement