diff --git a/Plugins/Libraries/craftbukkit.jar b/Plugins/Libraries/craftbukkit.jar index f5492b351..b1aca90e2 100644 Binary files a/Plugins/Libraries/craftbukkit.jar and b/Plugins/Libraries/craftbukkit.jar differ diff --git a/Plugins/Mineplex.Core/src/mineplex/core/RankBenefitsGiver9000.java b/Plugins/Mineplex.Core/src/mineplex/core/RankBenefitsGiver9000.java new file mode 100644 index 000000000..e8d8e7615 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/RankBenefitsGiver9000.java @@ -0,0 +1,82 @@ +package mineplex.core; + +import java.util.HashSet; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.account.event.RetrieveClientInformationEvent; +import mineplex.core.common.Rank; +import mineplex.core.inventory.InventoryManager; + +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.java.JavaPlugin; + +public class RankBenefitsGiver9000 extends MiniPlugin +{ + private CoreClientManager _clientManager; + private InventoryManager _inventoryManager; + private RankBenefitsGiver9000Repository _repository; + + private HashSet _playersNeedingBenefit = new HashSet(); + + public RankBenefitsGiver9000(JavaPlugin plugin, CoreClientManager clientManager, InventoryManager inventoryManager) + { + super("RankBenefitsGiver9000", plugin); + + _clientManager = clientManager; + _inventoryManager = inventoryManager; + _repository = new RankBenefitsGiver9000Repository(plugin); + } + + @EventHandler + public void loadPlayer(RetrieveClientInformationEvent event) + { + boolean treasureUpdate = false; + + for (String benefit : _repository.retrievePlayerBenefits(event.getUniqueId().toString())) + { + if (benefit.equalsIgnoreCase("TreasureUpdate")) + treasureUpdate = true; + } + + if (!treasureUpdate) + { + _playersNeedingBenefit.add(event.getPlayerName()); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void giveBenefit(final PlayerJoinEvent event) + { + if (!_playersNeedingBenefit.contains(event.getPlayer().getName())) + return; + + if (_clientManager.Get(event.getPlayer()).GetRank() == Rank.ALL) + { + _inventoryManager.addItemToInventory(event.getPlayer(), "Utility", "Treasure Chest", 1); + _inventoryManager.addItemToInventory(event.getPlayer(), "Treasure", "Treasure Key", 1); + } + else if (_clientManager.Get(event.getPlayer()).GetRank() == Rank.ULTRA) + { + _inventoryManager.addItemToInventory(event.getPlayer(), "Utility", "Treasure Chest", 20); + _inventoryManager.addItemToInventory(event.getPlayer(), "Treasure", "Treasure Key", 5); + } + else + { + _inventoryManager.addItemToInventory(event.getPlayer(), "Utility", "Treasure Chest", 40); + _inventoryManager.addItemToInventory(event.getPlayer(), "Treasure", "Treasure Key", 10); + } + + Bukkit.getServer().getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable() + { + public void run() + { + _repository.addBenefit(event.getPlayer().getUniqueId().toString(), "TreasureUpdate"); + } + }); + + _playersNeedingBenefit.remove(event.getPlayer().getName()); + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/RankBenefitsGiver9000Repository.java b/Plugins/Mineplex.Core/src/mineplex/core/RankBenefitsGiver9000Repository.java new file mode 100644 index 000000000..a7abdbb4b --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/RankBenefitsGiver9000Repository.java @@ -0,0 +1,59 @@ +package mineplex.core; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import mineplex.core.database.RepositoryBase; +import mineplex.core.database.ResultSetCallable; +import mineplex.core.database.column.ColumnVarChar; + +import org.bukkit.plugin.java.JavaPlugin; + +public class RankBenefitsGiver9000Repository extends RepositoryBase +{ + private static String CREATE_BENEFIT_TABLE = "CREATE TABLE IF NOT EXISTS rankBenefits (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(100), benefit VARCHAR(100), PRIMARY KEY (id), INDEX rankUuid (uuid));"; + + private static String INSERT_BENEFIT = "INSERT INTO rankBenefits (uuid, benefit) VALUES (?, ?);"; + private static String RETRIEVE_BENEFITS = "SELECT benefit FROM rankBenefits WHERE uuid = ?;"; + + public RankBenefitsGiver9000Repository(JavaPlugin plugin) + { + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + } + + @Override + protected void initialize() + { + executeUpdate(CREATE_BENEFIT_TABLE); + } + + @Override + protected void update() + { + } + + public List retrievePlayerBenefits(String uuid) + { + final List benefits = new ArrayList(); + + executeQuery(RETRIEVE_BENEFITS, new ResultSetCallable() + { + public void processResultSet(ResultSet resultSet) throws SQLException + { + while (resultSet.next()) + { + benefits.add(resultSet.getString(1)); + } + } + }, new ColumnVarChar("uuid", 100, uuid)); + + return benefits; + } + + public void addBenefit(String uuid, String benefit) + { + executeUpdate(INSERT_BENEFIT, new ColumnVarChar("uuid", 100, uuid), new ColumnVarChar("benefit", 100, benefit)); + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/account/CoreClientManager.java b/Plugins/Mineplex.Core/src/mineplex/core/account/CoreClientManager.java index fffa1202c..75cfb0a48 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/account/CoreClientManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/account/CoreClientManager.java @@ -168,9 +168,38 @@ public class CoreClientManager extends MiniPlugin client.SetAccountId(token.AccountId); client.SetRank(Rank.valueOf(token.Rank)); + final RetrieveClientInformationEvent clientInformationEvent = new RetrieveClientInformationEvent(client.GetPlayerName(), uuid); + clientInformationEvent.incrementProcessingCount(); + + Bukkit.getServer().getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable() + { + public void run() + { + _mysqlRepository.login(uuid.toString(), client.GetPlayerName()); + + Bukkit.getServer().getPluginManager().callEvent(clientInformationEvent); + clientInformationEvent.decreaseProcessingCount(); + } + }); + // JSON sql response Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(response)); + // Load client in miniplugins + Bukkit.getServer().getPluginManager().callEvent(new AsyncClientLoadEvent(token, client)); + + while (clientInformationEvent.processing()) + { + try + { + Thread.sleep(1); + } + catch (InterruptedException e) + { + e.printStackTrace(); + } + } + Bukkit.getServer().getScheduler().runTask(GetPlugin(), new Runnable() { public void run() diff --git a/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/button/CloseButton.java b/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/button/CloseButton.java index 2f7073c37..ed48a635a 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/button/CloseButton.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/button/CloseButton.java @@ -10,13 +10,11 @@ public class CloseButton implements IButton public void ClickedLeft(Player player) { player.closeInventory(); - System.out.println(this.getClass().getName() + " 13"); } @Override public void ClickedRight(Player player) { player.closeInventory(); - System.out.println(this.getClass().getName() + " 19"); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/page/Menu.java b/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/page/Menu.java index c82f98edd..7d4af6353 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/page/Menu.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/page/Menu.java @@ -48,7 +48,18 @@ public class Menu extends ShopPageBase @Override protected void BuildPage() { - AddItem(2, new ShopItem(175, DonationManager.Get(Player.getName()).getCoins() + " Coins", 1, false)); + AddItem(2, new ShopItem(175, DonationManager.Get(Player.getName()).getCoins() + " Coins", new String[] + { + " ", + ChatColor.RESET + C.cYellow + "Purchase Coins", + ChatColor.RESET + "www.mineplex.com/shop", + " ", + ChatColor.RESET + C.cAqua + "Ultra Rank", + ChatColor.RESET + "Receives 7500 Coins per Month", + " ", + ChatColor.RESET + C.cPurple + "Hero Rank", + ChatColor.RESET + "Receives 15000 Coins per Month", + }, 1, false)); int treasureChestCount = Plugin.getInventoryManager().Get(Player).getItemCount("Treasure Chest"); int treasureKeyCount = Plugin.getInventoryManager().Get(Player).getItemCount("Treasure Key"); @@ -63,7 +74,8 @@ public class Menu extends ShopPageBase if (treasureChestCount > 0 && treasureKeyCount > 0) { lore.add(ChatColor.RESET + C.cGreen + "Left-Click to open Treasure Chest"); - lore.add(ChatColor.RESET + "This uses 1 Treasure Key and 1 Treasure Chest"); + lore.add(ChatColor.RESET + "Uses 1 Treasure Key"); + lore.add(ChatColor.RESET + "Uses 1 Treasure Chest"); } else if (treasureChestCount > 0) @@ -306,7 +318,6 @@ public class Menu extends ShopPageBase { public void run() { - System.out.println("Added treasure key"); Plugin.getInventoryManager().addItemToInventory(Player, "Treasure", "Treasure Key", 1); Refresh(); } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/gadget/GadgetManager.java b/Plugins/Mineplex.Core/src/mineplex/core/gadget/GadgetManager.java index 445da7ec8..4dcb47eea 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/gadget/GadgetManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/gadget/GadgetManager.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -405,4 +406,20 @@ public class GadgetManager extends MiniPlugin } } } + + public boolean canPlaySongAt(Location location) + { + for (Gadget gadget : _gadgets.get(GadgetType.MusicDisc)) + { + if (gadget instanceof MusicGadget) + { + if (!((MusicGadget)gadget).canPlayAt(location)) + { + return false; + } + } + } + + return true; + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/gadget/gadgets/SongData.java b/Plugins/Mineplex.Core/src/mineplex/core/gadget/gadgets/SongData.java index 44017a98a..de334ad2a 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/gadget/gadgets/SongData.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/gadget/gadgets/SongData.java @@ -23,7 +23,9 @@ public class SongData { if (System.currentTimeMillis() > EndTime) { - Block.setType(Material.AIR); + if (Block.getType() == Material.JUKEBOX) + Block.setType(Material.AIR); + return true; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/gadget/types/MusicGadget.java b/Plugins/Mineplex.Core/src/mineplex/core/gadget/types/MusicGadget.java index 9912e6800..d3dbf7b03 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/gadget/types/MusicGadget.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/gadget/types/MusicGadget.java @@ -4,9 +4,12 @@ import java.util.ArrayList; import java.util.Iterator; import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; import mineplex.core.gadget.GadgetManager; import mineplex.core.gadget.event.GadgetActivateEvent; +import mineplex.core.gadget.event.GadgetBlockEvent; import mineplex.core.gadget.gadgets.SongData; import mineplex.core.recharge.Recharge; import mineplex.core.updater.UpdateType; @@ -14,10 +17,11 @@ import mineplex.core.updater.event.UpdateEvent; import org.bukkit.Bukkit; import org.bukkit.Effect; +import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; public class MusicGadget extends Gadget { @@ -46,8 +50,20 @@ public class MusicGadget extends Gadget return; } - if (!Recharge.Instance.use(player, "Play Disc", _duration, true, false)) + if (!Manager.canPlaySongAt(player.getLocation())) + { + UtilPlayer.message(player, F.main("Music", "There is already a song playing.")); return; + } + + for (Block block : UtilBlock.getInRadius(player.getLocation(), 3).keySet()) + { + if (block.getType() == Material.PORTAL) + { + UtilPlayer.message(player, F.main("Music", "Cannot play songs near Portals.")); + return; + } + } player.getWorld().playEffect(player.getLocation(), Effect.RECORD_PLAY, _id); @@ -82,4 +98,38 @@ public class MusicGadget extends Gadget songIterator.remove(); } } + + @EventHandler + public void gadgetBlockChange(GadgetBlockEvent event) + { + for (Iterator iterator = event.getBlocks().iterator(); iterator.hasNext();) + { + Block block = iterator.next(); + + for (SongData data : _songs) + { + if (data.Block.equals(block)) + { + iterator.remove(); + break; + } + } + } + } + + public boolean canPlayAt(Location location) + { + if (!_songs.isEmpty()) + return false; + +// for (SongData data : _songs) +// { +// if (UtilMath.offset(data.Block.getLocation(), location) < 48) +// { +// return false; +// } +// } + + return true; + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/portal/Commands/SendCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/portal/Commands/SendCommand.java index 4b29c5343..162e475e0 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/portal/Commands/SendCommand.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/portal/Commands/SendCommand.java @@ -50,7 +50,7 @@ public class SendCommand extends CommandBase return; } - Plugin.AddTransferRecord(playerTarget, serverTarget); + Portal.transferPlayer(playerTarget, serverTarget); UtilPlayer.message(player, F.main(Plugin.GetName(), C.cGray + "You have sent player: " + C.cGold + playerTarget + C.cGray + " to server: " + C.cGold + serverTarget + C.cGray + "!")); return; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/portal/Commands/ServerCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/portal/Commands/ServerCommand.java index 88a578a95..8f71b331d 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/portal/Commands/ServerCommand.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/portal/Commands/ServerCommand.java @@ -63,7 +63,7 @@ public class ServerCommand extends CommandBase else deniedAccess = true; } - else if (servUp.contains("ULTRA") || servUp.contains("BETA") || servUp.contains("T_")) + else if (servUp.contains("ULTRA") || servUp.contains("BETA")) { if (playerRank.Has(Rank.ULTRA)) Plugin.SendPlayerToServerWithMessage(player, args[0]); @@ -93,7 +93,7 @@ public class ServerCommand extends CommandBase { UtilPlayer.message( player, - F.main(Plugin.GetName(), C.cRed + "You don't have permission to join " + C.cGold + args[0] + " with /server")); + F.main(Plugin.GetName(), C.cRed + "You don't have permission to join " + C.cGold + args[0])); } } }); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/portal/Portal.java b/Plugins/Mineplex.Core/src/mineplex/core/portal/Portal.java index 1c99c7134..0da30b552 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/portal/Portal.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/portal/Portal.java @@ -25,14 +25,18 @@ import mineplex.core.portal.Commands.*; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.serverdata.Region; +import mineplex.serverdata.ServerCommandManager; import mineplex.serverdata.ServerManager; public class Portal extends MiniPlugin { - private HashSet _connectingPlayers = new HashSet(); - //private PortalRepository _repositorysitory = new PortalRepository(); - private PortalRepository _repository; + // The singleton instance of Portal + private static Portal instance; + public static Portal getInstance() { return instance; } + + private HashSet _connectingPlayers = new HashSet(); + private Region _region; private boolean _retrieve = true; private String _serverName; @@ -41,12 +45,15 @@ public class Portal extends MiniPlugin { super("Portal", plugin); + instance = this; + this._serverName = serverName; this._region = plugin.getConfig().getBoolean("serverstatus.us") ? Region.US : Region.EU; Bukkit.getMessenger().registerOutgoingPluginChannel(GetPlugin(), "BungeeCord"); - _repository = new PortalRepository(); + // Register the server command type for future use + ServerCommandManager.getInstance().registerCommandType(TransferCommand.class); } public void SendAllPlayers(String serverName) @@ -111,15 +118,11 @@ public class Portal extends MiniPlugin }, 20L); } - public void AddTransferRecord(final String playerName, final String serverName) + public static void transferPlayer(String playerName, String serverName) { - Bukkit.getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable() - { - public void run() - { - _repository.addServerTransfer(new ServerTransfer(playerName, serverName)); - } - }); + ServerTransfer serverTransfer = new ServerTransfer(playerName, serverName); + TransferCommand transferCommand = new TransferCommand(serverTransfer); + transferCommand.publish(); } public void DoesServerExist(final String serverName, final Callback callback) @@ -149,51 +152,4 @@ public class Portal extends MiniPlugin AddCommand(new ServerCommand(this)); AddCommand(new SendCommand(this)); } - - @EventHandler - public void checkForServerTransfers(UpdateEvent event) - { - if (event.getType() != UpdateType.SEC || Bukkit.getOnlinePlayers().size() == 0) - return; - - _retrieve = !_retrieve; - - if (_retrieve) - { - Bukkit.getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable() - { - public void run() - { - final Collection serverTransfers = _repository.getServerTransfers(); - - for (Iterator iterator = serverTransfers.iterator(); iterator.hasNext();) - { - ServerTransfer serverTransfer = iterator.next(); - - if (serverTransfer.getServerName().equalsIgnoreCase(_serverName)) - { - _repository.removeServerTransfer(serverTransfer.getPlayerName()); - iterator.remove(); - } - } - - Bukkit.getScheduler().runTask(GetPlugin(), new Runnable() - { - public void run() - { - for (ServerTransfer serverTransfer : serverTransfers) - { - Player player = GetPlugin().getServer().getPlayer(serverTransfer.getPlayerName()); - - if (player != null) - { - SendPlayerToServer(player, serverTransfer.getServerName()); - } - } - } - }); - } - }); - } - } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/portal/PortalRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/portal/PortalRepository.java deleted file mode 100644 index 986ac287c..000000000 --- a/Plugins/Mineplex.Core/src/mineplex/core/portal/PortalRepository.java +++ /dev/null @@ -1,177 +0,0 @@ -package mineplex.core.portal; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import mineplex.serverdata.ServerManager; -import mineplex.serverdata.Utility; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.Pipeline; -import redis.clients.jedis.Response; -import redis.clients.jedis.Transaction; -import redis.clients.jedis.exceptions.JedisConnectionException; - -public class PortalRepository -{ - - // The delimiter character used for redis key paths - public final char KEY_DELIMITER = '.'; - - // The access portal for jedis resources - private JedisPool _jedisPool; - - /** - * Class constructor - */ - public PortalRepository() - { - this._jedisPool = new JedisPool(new JedisPoolConfig(), ServerManager.DEFAULT_REDIS_HOST, - ServerManager.DEFAULT_REDIS_PORT); - } - - /** - * @return the {@link Set} of all ongoing {@link ServerTransfer}s available in this repository. - */ - public Collection getServerTransfers() - { - Set serverTransfers = new HashSet(); - Jedis jedis = _jedisPool.getResource(); - - try - { - String setKey = "servertransfers"; - Set playerNames = jedis.smembers(setKey); - - Pipeline pipeline = jedis.pipelined(); - - List> responses = new ArrayList>(); - for (String playerName : playerNames) - { - String dataKey = concatenate(setKey, playerName); - responses.add(pipeline.get(dataKey)); - } - - pipeline.sync(); - - for (Response response : responses) - { - String serializedData = response.get(); - ServerTransfer serverTransfer = Utility.deserialize(serializedData, ServerTransfer.class); - serverTransfers.add(serverTransfer); - } - } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _jedisPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _jedisPool.returnResource(jedis); - } - } - - return serverTransfers; - } - - /** - * Add a new {@link ServerTransfer} to this repository. - * @param serverTransfer - the {@link ServerTransfer} to be added in. - */ - public void addServerTransfer(ServerTransfer serverTransfer) - { - Jedis jedis = _jedisPool.getResource(); - - try - { - String setKey = "servertransfers"; - String dataKey = concatenate(setKey, serverTransfer.getPlayerName()); - String serializedTransfer = Utility.serialize(serverTransfer); - - Transaction transaction = jedis.multi(); - transaction.sadd(setKey, serverTransfer.getPlayerName()); - transaction.set(dataKey, serializedTransfer); - transaction.exec(); - } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _jedisPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _jedisPool.returnResource(jedis); - } - } - } - - /** - * Remove an existing {@link ServerTransfer} from this repository whose - * stored {@code playerName} matches the passed in name. - * @param playerName - the name of the player whose active {@link ServerTransfer} - * is to be removed. - * @return true, if the {@link ServerTransfer} belonging to player with matching - * {@code playerName} was successfully removed, false otherwise. - */ - public boolean removeServerTransfer(String playerName) - { - boolean removedTransfer = false; - Jedis jedis = _jedisPool.getResource(); - - try - { - String setKey = "servertransfers"; - String dataKey = concatenate(setKey, playerName); - - if (jedis.sismember(setKey, playerName)) - { - Transaction transaction = jedis.multi(); - transaction.srem(setKey, playerName); - transaction.del(dataKey); - transaction.exec(); - removedTransfer = true; - } - } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _jedisPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _jedisPool.returnResource(jedis); - } - } - - return removedTransfer; - } - - /** - * @param elements - the elements to concatenate together - * @return the concatenated form of all {@code elements} - * separated by the delimiter {@value KEY_DELIMITER}. - */ - protected String concatenate(String... elements) - { - return Utility.concatenate(KEY_DELIMITER, elements); - } - - /* - * 'servertransfers' contains a set of player names for players with an active server transfer - * 'servertransfers.' contains the JSON serialized 'ServerTransfer' object holding info. - */ -} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/portal/TransferCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/portal/TransferCommand.java new file mode 100644 index 000000000..1c1a70ada --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/portal/TransferCommand.java @@ -0,0 +1,40 @@ +package mineplex.core.portal; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import mineplex.serverdata.ServerCommand; + +/** + * The TransferCommand is sent across the server network to notify + * servers to transfer players to other destinations. + * @author Ty + * + */ +public class TransferCommand extends ServerCommand +{ + + // The ServerTransfer to be sent to another server for enactment + private ServerTransfer transfer; + + /** + * Class constructor + * @param transfer - the {@link ServerTransfer} to notify another server of + */ + public TransferCommand(ServerTransfer transfer) + { + this.transfer = transfer; + } + + @Override + public void run() + { + Player player = Bukkit.getPlayer(transfer.getPlayerName()); + + if (player != null && player.isOnline()) + { + Portal.getInstance().SendPlayerToServer(player, transfer.getServerName()); + } + } + +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/punish/UI/PunishPage.java b/Plugins/Mineplex.Core/src/mineplex/core/punish/UI/PunishPage.java index c20389707..1f1d62099 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/punish/UI/PunishPage.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/punish/UI/PunishPage.java @@ -426,7 +426,6 @@ public class PunishPage extends CraftInventoryCustom implements Listener { _plugin.AddPunishment(_target, category, _reason, _player, severity, ban, punishTime); _player.closeInventory(); - System.out.println(this.getClass().getName() + " 429"); ClosePunish(); } @@ -452,7 +451,6 @@ public class PunishPage extends CraftInventoryCustom implements Listener { punishment.Remove(_player.getName(), _reason); _player.closeInventory(); - System.out.println(this.getClass().getName() + " 455"); ClosePunish(); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/reward/RewardManager.java b/Plugins/Mineplex.Core/src/mineplex/core/reward/RewardManager.java index fecd68378..03f00d87a 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/reward/RewardManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/reward/RewardManager.java @@ -67,8 +67,8 @@ public class RewardManager //Increase Value if (_doubleGadgetValue) { - minValue *= 2; - maxValue *= 2; + minValue *= 1.5; + maxValue *= 1.5; } // Gadgets @@ -111,8 +111,8 @@ public class RewardManager //Increase Value if (_doubleGadgetValue) { - minValue *= 2; - maxValue *= 2; + minValue *= 1.5; + maxValue *= 1.5; } // Gadgets diff --git a/Plugins/Mineplex.Core/src/mineplex/core/shop/ShopBase.java b/Plugins/Mineplex.Core/src/mineplex/core/shop/ShopBase.java index 9c4b27a94..a5bb35ac0 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/shop/ShopBase.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/shop/ShopBase.java @@ -195,7 +195,6 @@ public abstract class ShopBase implements Listene PlayerPageMap.get(event.getPlayer().getName()).Dispose(); event.getPlayer().closeInventory(); - System.out.println(this.getClass().getName() + " 184"); CloseShopForPlayer(event.getPlayer()); PlayerPageMap.remove(event.getPlayer().getName()); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/shop/page/ConfirmationPage.java b/Plugins/Mineplex.Core/src/mineplex/core/shop/page/ConfirmationPage.java index fac8be755..e37605cf3 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/shop/page/ConfirmationPage.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/shop/page/ConfirmationPage.java @@ -106,7 +106,6 @@ public class ConfirmationPage _wallsBlockInfo = new HashSet<>(); private HashSet _outerRingBlockInfo = new HashSet<>(); @@ -55,9 +57,11 @@ public class Treasure private TreasureStyle _style; - public Treasure(Player player, Reward[] rewards) + public Treasure(Player player, Reward[] rewards, BlockRestore blockRestore) { this(player, new Random(), rewards); + + _blockRestore = blockRestore; } public Treasure(Player player, Random seed, Reward[] rewards) @@ -88,6 +92,9 @@ public class Treasure if (Math.abs(x) == 1 || Math.abs(z) == 1) { Block block = _centerBlock.getRelative(x, 0, z); + + _blockRestore.Restore(block); + _centerBlockInfo.add(new BlockInfo(block)); setBlock(block, _style.getPrimaryMaterial(), _style.getPrimaryData()); } @@ -101,12 +108,18 @@ public class Treasure { { Block block = _centerBlock.getRelative(x, 0, -2); + + _blockRestore.Restore(block); + _outerRingBlockInfo.add(new BlockInfo(block)); setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData()); } { Block block = _centerBlock.getRelative(x, 0, 2); + + _blockRestore.Restore(block); + _outerRingBlockInfo.add(new BlockInfo(block)); setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData()); } @@ -116,12 +129,18 @@ public class Treasure { { Block block = _centerBlock.getRelative(-2, 0, z); + + _blockRestore.Restore(block); + _outerRingBlockInfo.add(new BlockInfo(block)); setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData()); } { Block block = _centerBlock.getRelative(2, 0, z); + + _blockRestore.Restore(block); + _outerRingBlockInfo.add(new BlockInfo(block)); setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData()); } @@ -138,6 +157,9 @@ public class Treasure { Block playerBlock = getPlayerBlock(); Block block = playerBlock.getRelative(x, 0, z); + + _blockRestore.Restore(block); + _wallsBlockInfo.add(new BlockInfo(block)); setBlock(block, _style.getWallMaterial(), _style.getWallData()); } @@ -160,6 +182,9 @@ public class Treasure if (_tickCount == 5) { Block block = _centerBlock; + + _blockRestore.Restore(block); + _centerBlockInfo.add(new BlockInfo(block)); _centerBlockInfo.add(new BlockInfo(block.getRelative(BlockFace.DOWN))); setBlock(block, Material.REDSTONE_LAMP_ON, (byte) 0); @@ -388,17 +413,21 @@ public class Treasure public boolean containsBlock(Block block) { - if (_wallsBlockInfo.contains(block)) - return true; - - if (_outerRingBlockInfo.contains(block)) - return true; - - if (_centerBlockInfo.contains(block)) - return true; - - if (_chestBlockInfo.contains(block)) - return true; + for (BlockInfo info : _wallsBlockInfo) + if (info.getBlock().equals(block)) + return true; + + for (BlockInfo info : _outerRingBlockInfo) + if (info.getBlock().equals(block)) + return true; + + for (BlockInfo info : _centerBlockInfo) + if (info.getBlock().equals(block)) + return true; + + for (BlockInfo info : _chestBlockInfo) + if (info.getBlock().equals(block)) + return true; return false; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureKey.java b/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureKey.java index e87b0ab64..801921c0d 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureKey.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureKey.java @@ -14,7 +14,7 @@ public class TreasureKey extends SalesPackageBase { public TreasureKey() { - super("Treasure Key", Material.LEVER, (byte) 0, new String[] { ChatColor.RESET + "Used to open Treasure Chests" }, 1000); + super("Treasure Key", Material.TRIPWIRE_HOOK, (byte) 0, new String[] { ChatColor.RESET + "Used to open Treasure Chests" }, 1000); KnownPackage = false; OneTimePurchaseOnly = false; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureManager.java b/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureManager.java index 11a0fdafe..5692b8964 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureManager.java @@ -23,6 +23,7 @@ import org.bukkit.event.player.PlayerVelocityEvent; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.MiniPlugin; +import mineplex.core.blockrestore.BlockRestore; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.NautHashMap; @@ -53,14 +54,16 @@ public class TreasureManager extends MiniPlugin private NautHashMap _playerTreasureMap; private RewardManager _rewardManager; private InventoryManager _inventoryManager; + private BlockRestore _blockRestore; - public TreasureManager(JavaPlugin plugin, DonationManager donationManager, InventoryManager inventoryManager, PetManager petManager) + public TreasureManager(JavaPlugin plugin, DonationManager donationManager, InventoryManager inventoryManager, PetManager petManager, BlockRestore blockRestore) { super("Treasure", plugin); _playerTreasureMap = new NautHashMap(); _inventoryManager = inventoryManager; - _rewardManager = new RewardManager(donationManager, inventoryManager, petManager, + _blockRestore = blockRestore; + _rewardManager = new RewardManager(donationManager, inventoryManager, petManager, 250, 500, 750, 1500, 2000, 3000, @@ -105,7 +108,7 @@ public class TreasureManager extends MiniPlugin Bukkit.broadcastMessage(F.main("Treasure", F.name(player.getName()) + " is opening a " + C.cGreen + "Treasure Chest")); Reward[] rewards = _rewardManager.getRewards(player, true); - Treasure treasure = new Treasure(player, rewards); + Treasure treasure = new Treasure(player, rewards, _blockRestore); _playerTreasureMap.put(player, treasure); Location teleportLocation = treasure.getPlayerBlock().getLocation().add(0.5, 0, 0.5); @@ -361,11 +364,11 @@ public class TreasureManager extends MiniPlugin public void preventGadgetBlockEvent(GadgetBlockEvent event) { List blocks = event.getBlocks(); - + for (Block block : blocks) { for (Treasure treasure : _playerTreasureMap.values()) - { + { if (treasure.containsBlock(block)) { event.setCancelled(true); diff --git a/Plugins/Mineplex.Hub/.externalToolBuilders/Hub Builder.launch b/Plugins/Mineplex.Hub/.externalToolBuilders/Hub Builder.launch index 66529a78c..887eb7125 100644 --- a/Plugins/Mineplex.Hub/.externalToolBuilders/Hub Builder.launch +++ b/Plugins/Mineplex.Hub/.externalToolBuilders/Hub Builder.launch @@ -12,7 +12,7 @@ - + diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/HubManager.java b/Plugins/Mineplex.Hub/src/mineplex/hub/HubManager.java index 264d08406..d35aec971 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/HubManager.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/HubManager.java @@ -38,6 +38,7 @@ import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; import mineplex.core.MiniClientPlugin; +import mineplex.core.RankBenefitsGiver9000; import mineplex.core.account.CoreClient; import mineplex.core.account.CoreClientManager; import mineplex.core.account.event.RetrieveClientInformationEvent; @@ -159,8 +160,9 @@ public class HubManager extends MiniClientPlugin _mountManager = new MountManager(_plugin, clientManager, donationManager, blockRestore, _disguiseManager); _inventoryManager = new InventoryManager(plugin); + new RankBenefitsGiver9000(plugin, clientManager, _inventoryManager); _gadgetManager = new GadgetManager(_plugin, clientManager, donationManager, _inventoryManager, _mountManager, petManager, preferences, disguiseManager, blockRestore, new ProjectileManager(plugin)); - _treasureManager = new TreasureManager(_plugin, donationManager, _inventoryManager, petManager); + _treasureManager = new TreasureManager(_plugin, donationManager, _inventoryManager, petManager, _blockRestore); new CosmeticManager(_plugin, clientManager, donationManager, _inventoryManager, _gadgetManager, _mountManager, petManager, false, _treasureManager); _partyManager = partyManager; diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/modules/ParkourManager.java b/Plugins/Mineplex.Hub/src/mineplex/hub/modules/ParkourManager.java index 92dbe42f2..6ef2652e3 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/modules/ParkourManager.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/modules/ParkourManager.java @@ -400,9 +400,11 @@ public class ParkourManager extends MiniPlugin { for (Iterator iterator = event.getBlocks().iterator(); iterator.hasNext();) { + Block block = iterator.next(); + for (ParkourData data : _parkour) { - if (data.InBoundary(iterator.next().getLocation())) + if (data.InBoundary(block.getLocation())) { iterator.remove(); break; diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/poll/PollManager.java b/Plugins/Mineplex.Hub/src/mineplex/hub/poll/PollManager.java index 937497aec..9da95a10d 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/poll/PollManager.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/poll/PollManager.java @@ -85,7 +85,7 @@ public class PollManager extends MiniClientPlugin if (event.getType() != UpdateType.SLOW) return; - if (_polls.size() == 0) + if (_polls == null || _polls.size() == 0) return; for (Player player : _plugin.getServer().getOnlinePlayers()) diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/ServerNpcPage.java b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/ServerNpcPage.java index 50f34ac1e..c45bda048 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/ServerNpcPage.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/ServerNpcPage.java @@ -185,9 +185,9 @@ public class ServerNpcPage extends ShopPageBase im int greenStartSlot = 18 + ((9 - serversToShow) / 2); boolean showGreen = true; - boolean beta = serverList.size() > 0 && serverList.get(0).Name.contains("BETA"); + boolean beta = serverList.size() > 0 && (serverList.get(0).Name.contains("BETA") || serverList.get(0).Name.contains("MS-")); boolean tournament = serverList.size() > 0 && serverList.get(0).Name.contains("T_"); - boolean ownsUltraPackage = DonationManager.Get(Player.getName()).OwnsUnknownPackage(serverList.get(0).ServerType + " ULTRA") || Client.GetRank().Has(Rank.ULTRA); + boolean ownsUltraPackage = Client.GetRank().Has(Rank.ULTRA) || (serverList.size() > 0 && DonationManager.Get(Player.getName()).OwnsUnknownPackage(serverList.get(0).ServerType + " ULTRA")); long portalTime = Plugin.getMillisecondsUntilPortal(Player, beta); if (portalTime > 0) diff --git a/Plugins/Mineplex.Queuer/.classpath b/Plugins/Mineplex.Queuer/.classpath index 3e7f9b554..aedde4fb1 100644 --- a/Plugins/Mineplex.Queuer/.classpath +++ b/Plugins/Mineplex.Queuer/.classpath @@ -6,5 +6,8 @@ + + + diff --git a/Plugins/Mineplex.Queuer/src/mineplex/queuer/EloPlayerSorter.java b/Plugins/Mineplex.Queuer/src/mineplex/queuer/EloPlayerSorter.java deleted file mode 100644 index ceb9e7441..000000000 --- a/Plugins/Mineplex.Queuer/src/mineplex/queuer/EloPlayerSorter.java +++ /dev/null @@ -1,29 +0,0 @@ -package mineplex.queuer; - -import java.util.Comparator; - -import repository.PlayerMatchStatus; - -public class EloPlayerSorter implements Comparator -{ - public int EloMark = -1; - - public EloPlayerSorter(int eloMark) - { - EloMark = eloMark; - } - - public int compare(PlayerMatchStatus playerA, PlayerMatchStatus playerB) - { - if (playerA.Elo - EloMark < playerB.Elo - EloMark) - return -1; - - if (playerB.Elo - EloMark < playerA.Elo - EloMark) - return 1; - - if (playerA.Id < playerB.Id) - return -1; - - return 1; - } -} \ No newline at end of file diff --git a/Plugins/Mineplex.Queuer/src/mineplex/queuer/Match.java b/Plugins/Mineplex.Queuer/src/mineplex/queuer/Match.java new file mode 100644 index 000000000..747c8e5a4 --- /dev/null +++ b/Plugins/Mineplex.Queuer/src/mineplex/queuer/Match.java @@ -0,0 +1,75 @@ +package mineplex.queuer; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +public class Match +{ + private int _id; + public int getId() { return _id; } + + private Set _parties; + public Set getParties() { return _parties; } + + private boolean _waitingForInvites; + public boolean isWaitingForInvites() { return _waitingForInvites; } + + private long _waitingStartTime; + public long getWaitDuration() { return System.currentTimeMillis() - _waitingStartTime; } + + private int _averageElo; + public int getAverageElo() { return _averageElo; } + + public Match(int id, int averageElo, QueueParty... parties) + { + this._id = id; + this._averageElo = averageElo; + + for (QueueParty party : parties) + { + joinQueueParty(party); + } + } + + /** + * Add a {@link QueueParty} to this match. + * @param queueParty + */ + public void joinQueueParty(QueueParty queueParty) + { + _parties.add(queueParty); + } + + /** + * Remove a {@link QueueParty} from this match. + * @param queueParty + */ + public void quitQueueParty(QueueParty queueParty) + { + _parties.remove(queueParty); + } + + public int getPlayerCount() + { + int playerCount = 0; + + for (QueueParty party : _parties) + { + playerCount += party.getPlayerCount(); + } + + return playerCount; + } + + public void setWaitingForInvites(boolean waitingForInvites) + { + this._waitingForInvites = waitingForInvites; + + if (waitingForInvites) + { + this._waitingStartTime = System.currentTimeMillis(); + } + } +} diff --git a/Plugins/Mineplex.Queuer/src/mineplex/queuer/PlayerMatch.java b/Plugins/Mineplex.Queuer/src/mineplex/queuer/PlayerMatch.java deleted file mode 100644 index 77d55ea20..000000000 --- a/Plugins/Mineplex.Queuer/src/mineplex/queuer/PlayerMatch.java +++ /dev/null @@ -1,42 +0,0 @@ -package mineplex.queuer; - -import java.util.Collection; -import java.util.HashMap; - -import repository.PlayerMatchStatus; - -public class PlayerMatch -{ - private HashMap _players = new HashMap(); - private int _playerCount = 0; - - public boolean WaitingForInvites = false; - public long WaitingStarted = 0; - public int MatchId = -1; - public int Elo = 0; - - - public void addPlayerRecord(PlayerMatchStatus record) - { - _players.put(record.Id, record); - - _playerCount += record.PlayerCount; - } - - public void removePlayerRecord(PlayerMatchStatus record) - { - _players.remove(record.Id); - - _playerCount -= record.PlayerCount; - } - - public int getPlayerCount() - { - return _playerCount; - } - - public Collection getPlayerRecords() - { - return _players.values(); - } -} diff --git a/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueueParty.java b/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueueParty.java new file mode 100644 index 000000000..54791737c --- /dev/null +++ b/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueueParty.java @@ -0,0 +1,78 @@ +package mineplex.queuer; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import mineplex.serverdata.Data; +import mineplex.serverdata.Region; + +public class QueueParty implements Data +{ + + private int _id; + public int getId() { return _id; } + + private String _state; + public String getState() { return _state; } + public void setState(String state) { this._state = state; } + + private Set _players; + public Set getPlayers() { return _players; } + + private int _assignedMatch; + public int getAssignedMatch () { return _assignedMatch; } + public void setAssignedMatch(int assignedMatch) { this._assignedMatch = assignedMatch; } + + private int _variance; + private String _gameType; + + private int _averageElo; + public int getAverageElo() { return _averageElo; } + + private int _playerCount; + public int getPlayerCount() { return _playerCount; } + + private long _queueStartTime; + + private boolean _prompted; + public boolean isPrompted() { return _prompted; } + public void setPrompted(boolean prompted) { this._prompted = prompted; } + + private Region _region; + + private Set _otherPartyStates; + public Set getOtherPartyStates() { return _otherPartyStates; } + public void setOtherPartyStates(Set otherPartyStates) { this._otherPartyStates = otherPartyStates; } + + public QueueParty() + { + this._id = -1; + this._state = "Awaiting Match"; + this._assignedMatch = -1; + this._variance = 25; + this._prompted = false; + this._region = Region.US; + this._players = new HashSet(); + this._otherPartyStates = new HashSet(); + this._queueStartTime = System.currentTimeMillis(); + } + + public QueueParty(Collection players, String gameType, int averageElo) + { + this._players.addAll(players); + this._gameType = gameType; + this._averageElo = averageElo; + } + + public boolean hasAssignedMatch() + { + return _assignedMatch != -1; + } + + @Override + public String getDataId() + { + return Integer.toString(_id); + } +} diff --git a/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueuePartySorter.java b/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueuePartySorter.java new file mode 100644 index 000000000..7ce9d4b47 --- /dev/null +++ b/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueuePartySorter.java @@ -0,0 +1,21 @@ +package mineplex.queuer; + +import java.util.Comparator; + +public class QueuePartySorter implements Comparator +{ + + public int compare(QueueParty party1, QueueParty party2) + { + if (party1.getAverageElo() < party2.getAverageElo()) + return -1; + + if (party2.getAverageElo() < party1.getAverageElo()) + return 1; + + if (party1.getId() < party2.getId()) + return -1; + + return 1; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueueRepository.java b/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueueRepository.java new file mode 100644 index 000000000..6be115ca6 --- /dev/null +++ b/Plugins/Mineplex.Queuer/src/mineplex/queuer/QueueRepository.java @@ -0,0 +1,164 @@ +package mineplex.queuer; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import mineplex.core.portal.Portal; +import mineplex.core.portal.ServerTransfer; +import mineplex.serverdata.DataRepository; +import mineplex.serverdata.MinecraftServer; +import mineplex.serverdata.RedisDataRepository; +import mineplex.serverdata.Region; +import mineplex.serverdata.ServerManager; +import mineplex.serverdata.ServerRepository; + +public class QueueRepository +{ + + private DataRepository _partyRepository; + + /** + * Class constructor + * @param host - the host to connect the QueueRepository to + * @param port - the designated port of the QueueRepository database + * @param region - the region of server queues to manage + */ + public QueueRepository(String host, int port, Region region) + { + this._partyRepository = new RedisDataRepository(host, port, region, + QueueParty.class, "queue-parties"); + } + + /** + * {@code host} defaults to {@value ServerManager#DEFAULT_REDIS_HOST} and + * {@code port} defaults to {@value ServerManager#DEFAULT_REDIS_PORT} + * + * @see #QueueRepository(String, int, Region) + */ + public QueueRepository(Region region) + { + this(ServerManager.DEFAULT_REDIS_HOST, ServerManager.DEFAULT_REDIS_PORT, region); + } + + public QueueParty getQueueParty(int partyId) + { + return _partyRepository.getElement(Integer.toString(partyId)); + } + + public QueueParty createQueueParty(Collection players, String gameType, int averageElo) + { + QueueParty queueParty = new QueueParty(players, gameType, averageElo); + updateQueueParty(queueParty); + return queueParty; + } + + public void updateQueueParty(QueueParty queueParty) + { + _partyRepository.addElement(queueParty); + } + + public void deleteQueueParty(int partyId) + { + _partyRepository.removeElement(Integer.toString(partyId)); + } + + public void deleteQueueParty(QueueParty party) + { + deleteQueueParty(party.getId()); + } + + public void deleteAssignedParties(int matchId) + { + for (QueueParty queueParty : getJoinedQueueParties(matchId)) + { + deleteQueueParty(queueParty); + } + } + + public Collection getQueueParties() + { + return _partyRepository.getElements(); + } + + public Collection getJoinedQueueParties(int matchId) + { + Collection queueParties = new HashSet(); + + for (QueueParty queueParty : getQueueParties()) + { + if (queueParty.getAssignedMatch() == matchId) + { + queueParties.add(queueParty); + } + } + + return queueParties; + } + + public Map getMappedQueueParties() + { + Map queueParties = new HashMap(); + + for (QueueParty queueParty : getQueueParties()) + { + queueParties.put(queueParty.getId(), queueParty); + } + + return queueParties; + } + + public void assignMatch(QueueParty queueParty, Match match) + { + queueParty.setAssignedMatch(match.getId()); + queueParty.setState("Awaiting Confirmation"); + updateQueueParty(queueParty); + } + + public void startMatch(int matchId) + { + MinecraftServer emptyServer = getEmptyServer(); + + if (emptyServer != null) + { + for (QueueParty queueParty : getJoinedQueueParties(matchId)) + { + for (String playerName : queueParty.getPlayers()) + { + Portal.transferPlayer(playerName, emptyServer.getName()); + } + } + } + } + + protected MinecraftServer getEmptyServer() + { + ServerRepository serverRepository = ServerManager.getServerRepository(Region.US); + Collection servers = serverRepository.getServersByGroup("DominateElo"); + + for (MinecraftServer server : servers) + { + if (server.getPlayerCount() == 0) + { + return server; + } + } + + return null; + } + + public void deleteMatch(int matchId) + { + for (QueueParty queueParty : getJoinedQueueParties(matchId)) + { + queueParty.setAssignedMatch(-1); + queueParty.setState("Awaiting Match"); + updateQueueParty(queueParty); + } + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Queuer/src/mineplex/queuer/Queuer.java b/Plugins/Mineplex.Queuer/src/mineplex/queuer/Queuer.java index 20e62d704..331d025a2 100644 --- a/Plugins/Mineplex.Queuer/src/mineplex/queuer/Queuer.java +++ b/Plugins/Mineplex.Queuer/src/mineplex/queuer/Queuer.java @@ -2,29 +2,32 @@ package mineplex.queuer; import java.io.File; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Map; +import java.util.Set; -import repository.PlayerMatchStatus; -import repository.Repository; +import mineplex.serverdata.Region; public class Queuer { - private static Repository _repository = new Repository(); + private static QueueRepository _repo; public static void main (String args[]) { - boolean us = !new File("eu.dat").exists(); + Region region = (!new File("eu.dat").exists()) ? Region.US : Region.EU; - _repository.initialize(us); + _repo = new QueueRepository(region); HashMap playerVarianceMap = new HashMap(); - HashMap playerPrepMatchMap = new HashMap(); - List matchList = new ArrayList(); + HashMap playerPrepMatchMap = new HashMap(); + Set matches = new HashSet(); - EloPlayerSorter playerSorter = new EloPlayerSorter(1250); + QueuePartySorter partySorter = new QueuePartySorter(); int matchId = 1; @@ -34,135 +37,132 @@ public class Queuer matchId %= 1500; List assignedMatchIdChecked = new ArrayList(); - HashMap queueRecords = _repository.retrieveQueuedRecords(); + Map queueParties = _repo.getMappedQueueParties(); int matchPlayerCount = 2; - System.out.println("Checking " + queueRecords.size() + " queues..."); - for (PlayerMatchStatus queueRecord : queueRecords.values()) + System.out.println("Checking " + queueParties.size() + " queues..."); + for (QueueParty queueParty : queueParties.values()) { - Integer keyId = queueRecord.Id; + int partyId = queueParty.getId(); + int variance = playerVarianceMap.containsKey(partyId) ? playerVarianceMap.get(partyId) : 0; + variance += 25; + playerVarianceMap.put(partyId, variance); - // Add or increase variance mapping - if (playerVarianceMap.containsKey(keyId)) - playerVarianceMap.put(keyId, playerVarianceMap.get(keyId) + 25); - else - playerVarianceMap.put(keyId, 25); - - int playerVariance = playerVarianceMap.get(keyId); - - if (queueRecord.AssignedMatch == -1) + if (queueParty.hasAssignedMatch()) { - for (PlayerMatch match : matchList) + for (Match match : matches) { - if (Math.abs(match.Elo - queueRecord.Elo) <= playerVariance) + if (Math.abs(match.getAverageElo() - queueParty.getAverageElo()) <= variance) { - if (playerPrepMatchMap.containsKey(keyId)) + if (playerPrepMatchMap.containsKey(partyId)) { - if (playerPrepMatchMap.get(keyId) == match) + if (playerPrepMatchMap.get(partyId) == match) break; - playerPrepMatchMap.get(keyId).removePlayerRecord(queueRecord); + playerPrepMatchMap.get(partyId).quitQueueParty(queueParty); } - - match.addPlayerRecord(queueRecord); - playerPrepMatchMap.put(keyId, match); - System.out.println("Found prep match for '" + queueRecord.Id + "'"); + match.joinQueueParty(queueParty); + playerPrepMatchMap.put(partyId, match); + log("Found prep match for '" + queueParty.getId() + "'"); break; } } - if (!playerPrepMatchMap.containsKey(keyId)) + if (!playerPrepMatchMap.containsKey(partyId)) { - PlayerMatch match = new PlayerMatch(); - match.Elo = queueRecord.Elo; - match.MatchId = matchId; - match.addPlayerRecord(queueRecord); + Match match = new Match(matchId++, queueParty.getAverageElo(), queueParty); - playerPrepMatchMap.put(keyId, match); - matchList.add(match); - - matchId++; + playerPrepMatchMap.put(partyId, match); + matches.add(match); } } - else if (!assignedMatchIdChecked.contains(queueRecord.AssignedMatch)) + else if (!assignedMatchIdChecked.contains(queueParty.getAssignedMatch())) { - System.out.println("Checking if match '" + queueRecord.AssignedMatch + "' is ready."); - List matchStatuses = _repository.getMatchStatuses(queueRecord.AssignedMatch); + int assignedMatchId = queueParty.getAssignedMatch(); + log("Checking if match '" + assignedMatchId + "' is ready."); + //List matchStatuses = _repo.getMatchStatuses(queueRecord.AssignedMatch); + Collection joinedParties = _repo.getJoinedQueueParties(assignedMatchId); boolean matchReady = true; boolean matchDeny = false; - for (String matchStatus : matchStatuses) + for (QueueParty joinedParty : joinedParties) { - if (matchStatus.equalsIgnoreCase("Deny")) + String partyState = joinedParty.getState(); + if (partyState.equalsIgnoreCase("Deny")) { matchDeny = true; matchReady = false; break; } - else if (!matchStatus.equalsIgnoreCase("Ready")) + else if (!partyState.equalsIgnoreCase("Ready")) + { matchReady = false; + } } if (matchReady) { - _repository.startMatch(queueRecord.AssignedMatch); - _repository.deleteQueuesByAssignedMatch(queueRecord.AssignedMatch); + _repo.startMatch(assignedMatchId); + _repo.deleteAssignedParties(assignedMatchId); - System.out.println("Starting match '" + queueRecord.AssignedMatch + "'"); + System.out.println("Starting match '" + assignedMatchId + "'"); } else if (matchDeny) - { - _repository.removeAssignedMatch(queueRecord.AssignedMatch); + { + _repo.deleteMatch(assignedMatchId); } - assignedMatchIdChecked.add(queueRecord.AssignedMatch); + assignedMatchIdChecked.add(assignedMatchId); } } - System.out.println("Checking " + matchList.size() + " matches..."); + System.out.println("Checking " + matches.size() + " matches..."); // Check for and kick off invites for ready matches - for (Iterator matchIterator = matchList.iterator(); matchIterator.hasNext();) + for (Iterator matchIterator = matches.iterator(); matchIterator.hasNext();) { - PlayerMatch match = matchIterator.next(); + Match match = matchIterator.next(); // Don't give me crap about not using iterator...can't cuz of stupid thing. - List matchStatusesToRemove = new ArrayList(); + Set partiesToRemove = new HashSet(); - for (PlayerMatchStatus matchStatus : match.getPlayerRecords()) + for (QueueParty queueParty : match.getParties()) { - if (!queueRecords.containsKey(matchStatus.Id)) + if (!queueParties.containsKey(queueParty.getId())) { - System.out.println("Removing matchStatus : " + matchStatus.Id); - matchStatusesToRemove.add(matchStatus); + log("Removing matchStatus : " + queueParty.getId()); + partiesToRemove.add(queueParty); - if (match.WaitingForInvites) + if (match.isWaitingForInvites()) { - _repository.removeAssignedMatch(match.MatchId); - match.WaitingForInvites = false; + _repo.deleteMatch(match.getId()); + match.setWaitingForInvites(false); } } } - for (PlayerMatchStatus matchStatus : matchStatusesToRemove) + for (QueueParty party : partiesToRemove) { - match.removePlayerRecord(matchStatus); + match.quitQueueParty(party); } - if (match.WaitingForInvites) + if (match.isWaitingForInvites()) { - if ((System.currentTimeMillis() - match.WaitingStarted) > 15000) + if ((match.getWaitDuration()) > 15000) { - for (PlayerMatchStatus matchStatus : match.getPlayerRecords()) + for (QueueParty queueParty : match.getParties()) { - if (!matchStatus.State.equalsIgnoreCase("Ready")) - _repository.deleteQueuesById(matchStatus.Id); + if (!queueParty.getState().equalsIgnoreCase("Ready")) + { + _repo.deleteQueueParty(queueParty.getId()); + } } - _repository.removeAssignedMatch(match.MatchId); - match.WaitingForInvites = false; + + _repo.deleteMatch(match.getId()); + match.setWaitingForInvites(false); } continue; @@ -170,52 +170,43 @@ public class Queuer if (match.getPlayerCount() >= matchPlayerCount) { - playerSorter.EloMark = match.Elo; - - List playerList = new ArrayList(); - playerList.addAll(match.getPlayerRecords()); - - Collections.sort(playerList, playerSorter); + List partyList = new ArrayList(match.getParties()); + Collections.sort(partyList, partySorter); int playerCount = 0; - - for (int i = 0; i < playerList.size(); i++) + for (QueueParty party : partyList) { - PlayerMatchStatus player = playerList.get(i); - - if (playerCount + player.PlayerCount > matchPlayerCount) + if (playerCount + party.getPlayerCount() > matchPlayerCount) { - match.removePlayerRecord(player); - playerPrepMatchMap.remove(player.Id); - - System.out.println("Oops hit player cap, can't fit you in this match."); + match.quitQueueParty(party); + playerPrepMatchMap.remove(party.getId()); + log("Oops hit player cap, can't fit you in this match."); continue; } - playerCount += player.PlayerCount; + playerCount += party.getPlayerCount(); } if (playerCount == matchPlayerCount) { - System.out.println("Sent match invites for '" + match.MatchId + "'"); + log("Sent match invites for '" + match.getId() + "'"); - for (PlayerMatchStatus player : match.getPlayerRecords()) + for (QueueParty party : match.getParties()) { - playerPrepMatchMap.remove(player.Id); - _repository.assignMatch(player.Id, match.MatchId); + playerPrepMatchMap.remove(party.getId()); + _repo.assignMatch(party, match); } - match.WaitingForInvites = true; - match.WaitingStarted = System.currentTimeMillis(); - matchesMade += 1; + match.setWaitingForInvites(true); + matchesMade++; } } else if (match.getPlayerCount() == 0) + { matchIterator.remove(); + } } - _repository.clearOldServerTransfers(); - try { if (matchesMade > 0) @@ -228,5 +219,12 @@ public class Queuer e.printStackTrace(); } } + + + } + + private static void log(String message) + { + System.out.println(message); } } diff --git a/Plugins/Mineplex.Queuer/src/repository/PlayerMatchStatus.java b/Plugins/Mineplex.Queuer/src/repository/PlayerMatchStatus.java deleted file mode 100644 index d78bee329..000000000 --- a/Plugins/Mineplex.Queuer/src/repository/PlayerMatchStatus.java +++ /dev/null @@ -1,19 +0,0 @@ -package repository; - -public class PlayerMatchStatus -{ - public int Id = -1; - public String State = "Awaiting Match"; - public int AssignedMatch = -1; - public int Variance = 25; - public String GameType; - public int Elo; - public int PlayerCount; - public long QueuedStartTime; - - - public void printInfo() - { - System.out.println("PlayerMatchStatus: Id=" + Id + " State=" + State + " AssignedMatch=" + AssignedMatch + " Variance=" + Variance + " GameType=" + GameType + " Elo=" + Elo + " PlayerCount=" + PlayerCount + " QueuedStartTime=" + QueuedStartTime); - } -} diff --git a/Plugins/Mineplex.Queuer/src/repository/Repository.java b/Plugins/Mineplex.Queuer/src/repository/Repository.java deleted file mode 100644 index 38fbb9ac2..000000000 --- a/Plugins/Mineplex.Queuer/src/repository/Repository.java +++ /dev/null @@ -1,644 +0,0 @@ -package repository; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -public class Repository -{ - private static Object _connectionLock = new Object(); - - private String _connectionString = "jdbc:mysql://db.mineplex.com:3306/Queue?autoReconnect=true&failOverReadOnly=false&maxReconnects=10"; - private String _serverStatusConnectionString = "jdbc:mysql://db.mineplex.com:3306/ServerStatus?autoReconnect=true&failOverReadOnly=false&maxReconnects=10"; - private String _userName = "root"; - private String _password = "tAbechAk3wR7tuTh"; - - private boolean _us = true; - - private static String CREATE_TRANSFER_TABLE = "CREATE TABLE IF NOT EXISTS playerServerTransfer (id INT NOT NULL AUTO_INCREMENT, playerName VARCHAR(256), serverName VARCHAR(256), updated LONG, PRIMARY KEY (id));"; - private static String INSERT_TRANSFER_RECORD = "INSERT INTO playerServerTransfer (playerName, serverName, updated) VALUES (?, ?, now());"; - private static String DELETE_OLD_TRANSFER_RECORDS = "DELETE FROM playerServerTransfer WHERE TIME_TO_SEC(TIMEDIFF(now(), updated)) > 15;"; - - private static String CREATE_ELO_QUEUE_TABLE = "CREATE TABLE IF NOT EXISTS playerQueue (id INT NOT NULL AUTO_INCREMENT, playerList VARCHAR(256), gameType VARCHAR(256), elo INT, state VARCHAR(256), time LONG, assignedMatch INT, us BOOLEAN NOT NULL DEFAULT 'true', PRIMARY KEY (id));"; - private static String SAVE_STATE_VALUE = "UPDATE playerQueue SET state = ? WHERE id = ?;"; - private static String DELETE_ASSIGNED_QUEUE_RECORDS = "DELETE FROM playerQueue WHERE assignedMatch = ?;"; - private static String DELETE_QUEUE_RECORD = "DELETE FROM playerQueue WHERE id = ?;"; - private static String RESET_MATCH_RECORDS = "UPDATE playerQueue SET assignedMatch = -1, state = 'Awaiting Match' WHERE assignedMatch = ?;"; - private static String RETRIEVE_QUEUE_RECORDS = "SELECT id, gameType, elo, playerCount, assignedMatch, time, us FROM playerQueue WHERE us = ?;"; - private static String RETRIEVE_MATCH_STATUS = "SELECT state, playerList FROM playerQueue WHERE assignedMatch = ?;"; - private static String UPDATE_MATCH_STATUS = "UPDATE playerQueue SET assignedMatch = ?, state = ? WHERE id = ?;"; - - private static String RETRIEVE_SERVERGROUP_STATUSES = "SELECT serverName, now(), updated FROM ServerStatus WHERE players = 0 AND serverGroup = ?"; - - private Connection _connection = null; - private Connection _serverStatusConnection = null; - - public void initialize(boolean us) - { - _us = us; - - PreparedStatement preparedStatement = null; - - try - { - Class.forName("com.mysql.jdbc.Driver"); - - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - - // Create table - preparedStatement = _connection.prepareStatement(CREATE_ELO_QUEUE_TABLE); - preparedStatement.execute(); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - - try - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - // Create table - preparedStatement = _connection.prepareStatement(CREATE_TRANSFER_TABLE); - preparedStatement.execute(); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - } - - public void updateState(PlayerMatchStatus matchStatus) - { - PreparedStatement preparedStatement = null; - - try - { - synchronized (_connectionLock) - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - preparedStatement = _connection.prepareStatement(SAVE_STATE_VALUE); - preparedStatement.setString(1, matchStatus.State); - preparedStatement.setInt(2, matchStatus.Id); - - if (preparedStatement.executeUpdate() == 0) - { - System.out.println("Error updating state."); - } - } - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - } - - public PlayerMatchStatus checkForAssignedMatch(int id) - { - ResultSet resultSet = null; - PreparedStatement preparedStatement = null; - PlayerMatchStatus matchStatus = new PlayerMatchStatus(); - - try - { - synchronized (_connectionLock) - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - preparedStatement = _connection.prepareStatement(RETRIEVE_MATCH_STATUS); - preparedStatement.setInt(1, id); - - resultSet = preparedStatement.getGeneratedKeys(); - - while (resultSet.next()) - { - matchStatus.Id = id; - matchStatus.State = resultSet.getString(1); - matchStatus.AssignedMatch = resultSet.getInt(2); - } - } - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - if (resultSet != null) - { - try - { - resultSet.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - - return matchStatus; - } - - public HashMap retrieveQueuedRecords() - { - ResultSet resultSet = null; - PreparedStatement preparedStatement = null; - HashMap queueRecords = new HashMap(); - - try - { - synchronized (_connectionLock) - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - preparedStatement = _connection.prepareStatement(RETRIEVE_QUEUE_RECORDS); - preparedStatement.setBoolean(1, _us); - - resultSet = preparedStatement.executeQuery(); - - while (resultSet.next()) - { - PlayerMatchStatus matchStatus = new PlayerMatchStatus(); - - matchStatus.Id = resultSet.getInt(1); - matchStatus.GameType = resultSet.getString(2); - matchStatus.Elo = resultSet.getInt(3); - matchStatus.PlayerCount = resultSet.getInt(4); - matchStatus.AssignedMatch = resultSet.getInt(5); - matchStatus.QueuedStartTime = resultSet.getLong(6); - - queueRecords.put(matchStatus.Id, matchStatus); - } - } - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - if (resultSet != null) - { - try - { - resultSet.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - - return queueRecords; - } - - public List getMatchStatuses(int assignedMatch) - { - ResultSet resultSet = null; - PreparedStatement preparedStatement = null; - List matchStatuses = new ArrayList(); - - try - { - synchronized (_connectionLock) - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - preparedStatement = _connection.prepareStatement(RETRIEVE_MATCH_STATUS); - preparedStatement.setInt(1, assignedMatch); - - resultSet = preparedStatement.executeQuery(); - - while (resultSet.next()) - { - matchStatuses.add(resultSet.getString(1)); - } - } - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - if (resultSet != null) - { - try - { - resultSet.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - - return matchStatuses; - } - - public void deleteQueuesByAssignedMatch(int matchId) - { - PreparedStatement preparedStatement = null; - - try - { - synchronized (_connectionLock) - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - preparedStatement = _connection.prepareStatement(DELETE_ASSIGNED_QUEUE_RECORDS); - - preparedStatement.setInt(1, matchId); - - if (preparedStatement.executeUpdate() == 0) - { - System.out.println("Error deleting queue records."); - } - } - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - } - - public void deleteQueuesById(int id) - { - PreparedStatement preparedStatement = null; - - try - { - synchronized (_connectionLock) - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - preparedStatement = _connection.prepareStatement(DELETE_QUEUE_RECORD); - - preparedStatement.setInt(1, id); - - if (preparedStatement.executeUpdate() == 0) - { - System.out.println("Error deleting queue record."); - } - } - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - } - - public void clearOldServerTransfers() - { - PreparedStatement preparedStatement = null; - - try - { - if (_connection == null || _connection.isClosed()) - _connection = DriverManager.getConnection(_serverStatusConnectionString, _userName, _password); - - preparedStatement = _connection.prepareStatement(DELETE_OLD_TRANSFER_RECORDS); - - preparedStatement.executeUpdate(); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - } - - public void startMatch(int assignedMatch) - { - ResultSet resultSet = null; - PreparedStatement preparedStatement = null; - PreparedStatement addTransferStatement = null; - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - String serverName = ""; - - try - { - if (_serverStatusConnection == null || _serverStatusConnection.isClosed()) - _serverStatusConnection = DriverManager.getConnection(_serverStatusConnectionString, _userName, _password); - - preparedStatement = _serverStatusConnection.prepareStatement(RETRIEVE_SERVERGROUP_STATUSES); - preparedStatement.setString(1, "DominateElo"); - - resultSet = preparedStatement.executeQuery(); - - while (resultSet.next()) - { - long current = dateFormat.parse(resultSet.getString(2)).getTime(); - long updated = dateFormat.parse(resultSet.getString(3)).getTime(); - - if (current - updated < 15000) - { - serverName = resultSet.getString(1); - break; - } - } - - resultSet.close(); - preparedStatement.close(); - - if (_connection == null || _connection.isClosed()) - _connection = DriverManager.getConnection(_serverStatusConnectionString, _userName, _password); - - preparedStatement = _connection.prepareStatement(RETRIEVE_MATCH_STATUS); - preparedStatement.setInt(1, assignedMatch); - - addTransferStatement = _connection.prepareStatement(INSERT_TRANSFER_RECORD); - - resultSet = preparedStatement.executeQuery(); - - while (resultSet.next()) - { - for (String name : Arrays.asList(resultSet.getString(2).split("\\s*,\\s*"))) - { - addTransferStatement.setString(1, name); - addTransferStatement.setString(2, serverName); - addTransferStatement.addBatch(); - } - } - - addTransferStatement.executeBatch(); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - if (resultSet != null) - { - try - { - resultSet.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - } - - public void assignMatch(int id, int matchId) - { - ResultSet resultSet = null; - PreparedStatement preparedStatement = null; - - try - { - synchronized (_connectionLock) - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - preparedStatement = _connection.prepareStatement(UPDATE_MATCH_STATUS); - preparedStatement.setInt(1, matchId); - preparedStatement.setString(2, "Awaiting Confirmation"); - preparedStatement.setInt(3, id); - - preparedStatement.executeUpdate(); - } - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - if (resultSet != null) - { - try - { - resultSet.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - } - - public void removeAssignedMatch(int assignedMatch) - { - System.out.println("Resetting Records for " + assignedMatch); - - PreparedStatement preparedStatement = null; - - try - { - synchronized (_connectionLock) - { - if (_connection.isClosed()) - { - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - - preparedStatement = _connection.prepareStatement(RESET_MATCH_RECORDS); - preparedStatement.setInt(1, assignedMatch); - - preparedStatement.executeUpdate(); - } - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } - } -} diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Data.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Data.java new file mode 100644 index 000000000..a69049c3b --- /dev/null +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Data.java @@ -0,0 +1,9 @@ +package mineplex.serverdata; + +public interface Data +{ + /** + * @return the unique id key representing this {@link Data} object in {@link DataRepository}s. + */ + public String getDataId(); +} diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/DataRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/DataRepository.java new file mode 100644 index 000000000..e2940f8df --- /dev/null +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/DataRepository.java @@ -0,0 +1,30 @@ +package mineplex.serverdata; + +import java.util.Collection; + +/** + * DataRepository is used to store {@link Data} objects in a central database + * for real-time fetching/modification. + * @author Ty + * + * @param - the type of {@link Data} object stored in this repository. + */ +public interface DataRepository +{ + + public Collection getElements(); + + public T getElement(String dataId); + + public void addElement(T element, int timeout); + + public void addElement(T element); + + public void removeElement(T element); + + public void removeElement(String dataId); + + public boolean elementExists(String dataId); + + public int clean(); +} diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisDataRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisDataRepository.java new file mode 100644 index 000000000..ed9221b0b --- /dev/null +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisDataRepository.java @@ -0,0 +1,344 @@ +package mineplex.serverdata; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.Pipeline; +import redis.clients.jedis.Response; +import redis.clients.jedis.Transaction; +import redis.clients.jedis.exceptions.JedisConnectionException; + +public class RedisDataRepository implements DataRepository +{ + + // The delimiter character used for redis key paths + public final char KEY_DELIMITER = '.'; + + // The pool used to retrieve jedis instances. + private JedisPool _jedisPool; + public JedisPool getJedisPool() { return _jedisPool; } + + // The geographical region of the servers stored by this ServerRepository + private Region _region; + + private Class elementType; + + private String elementLabel; + + /** + * Class constructor + * @param host + * @param port + * @param region + */ + public RedisDataRepository(String host, int port, Region region, + Class elementType, String elementLabel) + { + this._jedisPool = new JedisPool(new JedisPoolConfig(), host, port); + this._region = region; + this.elementType = elementType; + this.elementLabel = elementLabel; + } + + public RedisDataRepository(Region region, Class elementType, String elementLabel) + { + this(ServerManager.DEFAULT_REDIS_HOST, ServerManager.DEFAULT_REDIS_PORT, region, + elementType, elementLabel); + } + + public String getElementSetKey() + { + return concatenate("data", elementLabel, _region.toString()); + } + + public String generateKey(T element) + { + return generateKey(element.getDataId()); + } + + public String generateKey(String dataId) + { + return concatenate(getElementSetKey(), dataId); + } + + @Override + public Collection getElements() + { + Collection elements = new HashSet(); + Jedis jedis = _jedisPool.getResource(); + + try + { + Pipeline pipeline = jedis.pipelined(); + + List> responses = new ArrayList>(); + for (String dataId : getActiveElements()) + { + responses.add(pipeline.get(generateKey(dataId))); + } + + pipeline.sync(); + + for (Response response : responses) + { + String serializedData = response.get(); + T element = deserialize(serializedData); + + if (element != null) + { + elements.add(element); + } + } + } + catch (JedisConnectionException exception) + { + exception.printStackTrace(); + _jedisPool.returnBrokenResource(jedis); + jedis = null; + } + finally + { + if (jedis != null) + { + _jedisPool.returnResource(jedis); + } + } + + return elements; + } + + @Override + public T getElement(String dataId) + { + T element = null; + Jedis jedis = _jedisPool.getResource(); + + try + { + String key = generateKey(dataId); + String serializedData = jedis.get(key); + element = deserialize(serializedData); + } + catch (JedisConnectionException exception) + { + exception.printStackTrace(); + _jedisPool.returnBrokenResource(jedis); + jedis = null; + } + finally + { + if (jedis != null) + { + _jedisPool.returnResource(jedis); + } + } + + return element; + } + + @Override + public void addElement(T element, int timeout) + { + Jedis jedis = _jedisPool.getResource(); + + try + { + String serializedData = serialize(element); + String dataId = element.getDataId(); + String setKey = getElementSetKey(); + String dataKey = generateKey(element); + long expiry = currentTime() + timeout; + + Transaction transaction = jedis.multi(); + transaction.set(dataKey, serializedData); + transaction.zadd(setKey, expiry, dataId.toString()); + transaction.exec(); + } + catch (JedisConnectionException exception) + { + exception.printStackTrace(); + _jedisPool.returnBrokenResource(jedis); + jedis = null; + } + finally + { + if (jedis != null) + { + _jedisPool.returnResource(jedis); + } + } + } + + @Override + public void addElement(T element) + { + addElement(element, 1000 * 60 * 60 * 24 * 7 * 4 * 12 * 10); // Set the timeout to 10 years + } + + @Override + public void removeElement(T element) + { + removeElement(element.getDataId()); + } + + @Override + public void removeElement(String dataId) + { + Jedis jedis = _jedisPool.getResource(); + + try + { + String setKey = getElementSetKey(); + String dataKey = generateKey(dataId); + + Transaction transaction = jedis.multi(); + transaction.set(dataKey, null); + transaction.zrem(setKey, dataId); + transaction.exec(); + } + catch (JedisConnectionException exception) + { + exception.printStackTrace(); + _jedisPool.returnBrokenResource(jedis); + jedis = null; + } + finally + { + if (jedis != null) + { + _jedisPool.returnResource(jedis); + } + } + } + + @Override + public boolean elementExists(String dataId) + { + return getElement(dataId) != null; + } + + @Override + public int clean() + { + Jedis jedis = _jedisPool.getResource(); + + try + { + for (String dataId : getDeadElements()) + { + String dataKey = generateKey(dataId); + + Transaction transaction = jedis.multi(); + transaction.del(dataKey); + transaction.zrem(getElementSetKey(), dataId); + transaction.exec(); + } + } + catch (JedisConnectionException exception) + { + exception.printStackTrace(); + _jedisPool.returnBrokenResource(jedis); + jedis = null; + } + finally + { + if (jedis != null) + { + _jedisPool.returnResource(jedis); + } + } + + return 0; + } + + protected Set getActiveElements() + { + Set dataIds = new HashSet(); + Jedis jedis = _jedisPool.getResource(); + + try + { + String min = "(" + currentTime(); + String max = "+inf"; + dataIds = jedis.zrangeByScore(getElementSetKey(), min, max); + } + catch (JedisConnectionException exception) + { + exception.printStackTrace(); + _jedisPool.returnBrokenResource(jedis); + jedis = null; + } + finally + { + if (jedis != null) + { + _jedisPool.returnResource(jedis); + } + } + + return dataIds; + } + + protected Set getDeadElements() + { + Set dataIds = new HashSet(); + Jedis jedis = _jedisPool.getResource(); + + try + { + String min = "-inf"; + String max = currentTime() + ""; + dataIds = jedis.zrangeByScore(getElementSetKey(), min, max); + } + catch (JedisConnectionException exception) + { + exception.printStackTrace(); + _jedisPool.returnBrokenResource(jedis); + jedis = null; + } + finally + { + if (jedis != null) + { + _jedisPool.returnResource(jedis); + } + } + + return dataIds; + } + + protected T deserialize(String serializedData) + { + return Utility.deserialize(serializedData, elementType); + } + + protected String serialize(T element) + { + return Utility.serialize(element); + } + + protected Long currentTime() + { + return Utility.currentTimeMillis(); + } + + /** + * @param elements - the elements to concatenate together + * @return the concatenated form of all {@code elements} + * separated by the delimiter {@value KEY_DELIMITER}. + */ + protected String concatenate(String... elements) + { + return Utility.concatenate(KEY_DELIMITER, elements); + } + + +} diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java index cf85f808a..ba74708a0 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java @@ -17,6 +17,9 @@ import redis.clients.jedis.Transaction; import redis.clients.jedis.Tuple; import redis.clients.jedis.exceptions.JedisConnectionException; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + /** * RedisServerRepository offers a Redis-based implementation of {@link ServerRepository} * using a mixture of hash and JSON encoded storage. @@ -69,12 +72,7 @@ public class RedisServerRepository implements ServerRepository for (Response response : responses) { String serializedData = response.get(); - MinecraftServer server = Utility.deserialize(serializedData, MinecraftServer.class); - - if (server != null) - { - servers.add(server); - } + servers.add(Utility.deserialize(serializedData, MinecraftServer.class)); } } catch (JedisConnectionException exception) @@ -94,6 +92,22 @@ public class RedisServerRepository implements ServerRepository return servers; } + @Override + public Collection getServersByGroup(String serverGroup) + { + Collection servers = new HashSet(); + + for (MinecraftServer server : getServerStatuses()) + { + if (server.getGroup().equalsIgnoreCase(serverGroup)) + { + servers.add(server); + } + } + + return servers; + } + @Override public MinecraftServer getServerStatus(String serverName) { @@ -135,8 +149,8 @@ public class RedisServerRepository implements ServerRepository String serverName = serverData.getName(); String setKey = concatenate("serverstatus", "minecraft", _region.toString()); String dataKey = concatenate(setKey, serverName); - long expiry = Long.parseLong(jedis.time().get(0)) + timeout; - + long expiry = Utility.currentTimeMillis() + timeout; + Transaction transaction = jedis.multi(); transaction.set(dataKey, serializedData); transaction.zadd(setKey, expiry, serverName); @@ -169,7 +183,7 @@ public class RedisServerRepository implements ServerRepository String dataKey = concatenate(setKey, serverName); Transaction transaction = jedis.multi(); - transaction.del(dataKey); + transaction.set(dataKey, null); transaction.zrem(setKey, serverName); transaction.exec(); } @@ -253,7 +267,7 @@ public class RedisServerRepository implements ServerRepository { for (MinecraftServer minecraftServer : getServerStatuses()) { - if (serverGroups.containsKey(minecraftServer.getGroup()) && minecraftServer.getPublicAddress().equalsIgnoreCase(server.getPrivateAddress())) + if (serverGroups.containsKey(minecraftServer.getGroup())) { ServerGroup serverGroup = serverGroups.get(minecraftServer.getGroup()); server.incrementServerCount(serverGroup); @@ -311,7 +325,7 @@ public class RedisServerRepository implements ServerRepository try { - String min = "(" + jedis.time().get(0); + String min = "(" + Utility.currentTimeMillis(); String max = "+inf"; names = jedis.zrangeByScore(key, min, max); } @@ -332,6 +346,38 @@ public class RedisServerRepository implements ServerRepository return names; } + /** + * @param key - the key where the sorted set of server sessions is stored + * @return the {@link Set} of dead (expired) server names stored at {@code key}. + */ + protected Set getDeadNames(String key) + { + Set names = new HashSet(); + Jedis jedis = _jedisPool.getResource(); + + try + { + String min = "-inf"; + String max = Utility.currentTimeMillis() + ""; + names = jedis.zrangeByScore(key, min, max); + } + catch (JedisConnectionException exception) + { + exception.printStackTrace(); + _jedisPool.returnBrokenResource(jedis); + jedis = null; + } + finally + { + if (jedis != null) + { + _jedisPool.returnResource(jedis); + } + } + + return names; + } + /** * @param elements - the elements to concatenate together * @return the concatenated form of all {@code elements} @@ -341,7 +387,7 @@ public class RedisServerRepository implements ServerRepository { return Utility.concatenate(KEY_DELIMITER, elements); } - + @Override public Collection getDeadServers() { diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Region.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Region.java index 53086a28e..dda067632 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Region.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Region.java @@ -10,4 +10,5 @@ public enum Region { US, EU, + ALL; } diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommand.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommand.java new file mode 100644 index 000000000..a442a5af6 --- /dev/null +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommand.java @@ -0,0 +1,51 @@ +package mineplex.serverdata; + +public abstract class ServerCommand +{ + + // The names of servers targetted to receive this ServerCommand. + private String[] targetServers; + + /** + * Class constructor + * @param targetServers + */ + public ServerCommand(String... targetServers) + { + this.targetServers = targetServers; + } + + /** + * Run the command on it's destination target server. + */ + public abstract void run(); + + /** + * @param serverName - the name of the server to be checked for whether they are a target + * @return true, if {@code serverName} is one of the {@code targetServers} of this + * {@link ServerCommand}, false otherwise. + */ + public boolean isTargetServer(String serverName) + { + if (targetServers == null || targetServers.length == 0) // Targets all online servers + return true; + + for (String targetServer : targetServers) + { + if (targetServer.equalsIgnoreCase(serverName)) + { + return true; + } + } + + return false; + } + + /** + * Publish the {@link ServerCommand} across the network to {@code targetServers}. + */ + public void publish() + { + ServerCommandManager.getInstance().publishCommand(this); + } +} diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommandListener.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommandListener.java new file mode 100644 index 000000000..e763feba5 --- /dev/null +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommandListener.java @@ -0,0 +1,60 @@ +package mineplex.serverdata; + +import redis.clients.jedis.JedisPubSub; + +/** + * The ServerCommandListener listens for published Redis network messages + * and deserializes them into their {@link ServerCommand} form, then registers + * it's arrival at the {@link ServerCommandManager}. + * @author Ty + * + */ +public class ServerCommandListener extends JedisPubSub +{ + + @Override + public void onPMessage(String pattern, String channelName, String message) + { + try + { + String commandType = message.split(":")[1]; + ServerCommandManager.getInstance().handleCommand(commandType, message); + } + catch (Exception exception) + { + exception.printStackTrace(); + } + } + + + @Override + public void onMessage(String channelName, String message) + { + + } + + @Override + public void onPSubscribe(String pattern, int subscribedChannels) + { + + } + + @Override + public void onPUnsubscribe(String pattern, int subscribedChannels) + { + + } + + @Override + public void onSubscribe(String channelName, int subscribedChannels) + { + + } + + @Override + public void onUnsubscribe(String channelName, int subscribedChannels) + { + + } + +} diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommandManager.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommandManager.java new file mode 100644 index 000000000..9f3542113 --- /dev/null +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerCommandManager.java @@ -0,0 +1,133 @@ +package mineplex.serverdata; + +import java.util.HashMap; +import java.util.Map; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +public class ServerCommandManager +{ + + // The singleton instance of ServerCommandManager + private static ServerCommandManager instance; + + public final String SERVER_COMMANDS_CHANNEL = "commands.server"; + + private JedisPool _jedisPool; + private Map> commandTypes; + + /** + * Private class constructor to prevent non-singleton instances. + */ + private ServerCommandManager() + { + this._jedisPool = new JedisPool(new JedisPoolConfig(), ServerManager.DEFAULT_REDIS_HOST, + ServerManager.DEFAULT_REDIS_PORT); + this.commandTypes = new HashMap>(); + + initialize(); + } + + /** + * Initialize the ServerCommandManager by subscribing to the + * redis network. + */ + private void initialize() + { + final Jedis jedis = _jedisPool.getResource(); + + // Spin up a new thread and subscribe to the Redis pubsub network + Thread thread = new Thread(new Runnable() + { + public void run() + { + try + { + jedis.psubscribe(new ServerCommandListener(), SERVER_COMMANDS_CHANNEL + ":*"); + } + catch (Exception exception) + { + exception.printStackTrace(); + } + finally + { + _jedisPool.returnResource(jedis); + } + } + }); + + thread.start(); + } + + /** + * Publish a {@link ServerCommand} across the network to all live servers. + * @param serverCommand - the {@link ServerCommand} to issue to all servers. + */ + public void publishCommand(ServerCommand serverCommand) + { + Jedis jedis = _jedisPool.getResource(); + + try + { + String commandType = serverCommand.getClass().toString(); + String serializedCommand = Utility.serialize(serverCommand); + jedis.publish(SERVER_COMMANDS_CHANNEL + ":" + commandType, serializedCommand); + } + catch (Exception exception) + { + exception.printStackTrace(); + } + finally + { + _jedisPool.returnResource(jedis); + } + } + + /** + * Handle an incoming (serialized) {@link ServerCommand}. + * @param commandType - the type of command being received + * @param serializedCommand - the serialized {@link ServerCommand} data. + */ + public void handleCommand(String commandType, String serializedCommand) + { + if (commandTypes.containsKey(commandType)) + { + ServerCommand serverCommand = Utility.deserialize(serializedCommand, commandTypes.get(commandType)); + + if (serverCommand.isTargetServer("THIS SERVER NAME HERE")) // TODO: Find server name ref + { + // TODO: Run synchronously? + serverCommand.run(); // Run the server command + } + } + } + + /** + * Register a new type of {@link ServerCommand}. + * @param commandType - the {@link ServerCommand} type to register. + */ + public void registerCommandType(Class commandType) + { + String commandName = commandType.toString(); + + if (!commandTypes.containsKey(commandName)) + { + commandTypes.put(commandName, commandType); + } + } + + /** + * @return the singleton instance of ServerCommandManager + */ + public static ServerCommandManager getInstance() + { + if (instance == null) + { + instance = new ServerCommandManager(); + } + + return instance; + } +} diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerGroup.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerGroup.java index 3d96de6c7..78e942305 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerGroup.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerGroup.java @@ -51,13 +51,13 @@ public class ServerGroup public boolean getArcadeGroup() { return _arcadeGroup; } private String _worldZip; - public String getWorldZip() { return _serverType; } + public String getWorldZip() { return _worldZip; } private String _plugin; - public String getPlugin() { return _serverType; } + public String getPlugin() { return _plugin; } private String _configPath; - public String getConfigPath() { return _serverType; } + public String getConfigPath() { return _configPath; } private int _minPlayers; public int getMinPlayers() { return _minPlayers; } @@ -71,6 +71,42 @@ public class ServerGroup private boolean _tournament; public boolean getTournament() { return _tournament; } + private boolean _teamRejoin; + public boolean getTeamRejoin() { return _teamRejoin; } + + private boolean _teamAutoJoin; + public boolean getTeamAutoJoin() { return _teamAutoJoin; } + + private boolean _teamForceBalance; + public boolean getTeamForceBalance() { return _teamForceBalance; } + + private boolean _gameAutoStart; + public boolean getGameAutoStart() { return _gameAutoStart; } + + private boolean _gameTimeout; + public boolean getGameTimeout() { return _gameTimeout; } + + private boolean _rewardGems; + public boolean getRewardGems() { return _rewardGems; } + + private boolean _rewardItems; + public boolean getRewardItems() { return _rewardItems; } + + private boolean _rewardStats; + public boolean getRewardStats() { return _rewardStats; } + + private boolean _rewardAchievements; + public boolean getRewardAchievements() { return _rewardAchievements; } + + private boolean _hotbarInventory; + public boolean getHotbarInventory() { return _hotbarInventory; } + + private boolean _hotbarHubClock; + public boolean getHotbarHubClock() { return _hotbarHubClock; } + + private boolean _playerKickIdle; + public boolean getPlayerKickIdle() { return _playerKickIdle; } + private boolean _generateFreeVersions; public boolean getGenerateFreeVersions() { return _generateFreeVersions; } @@ -84,7 +120,8 @@ public class ServerGroup public boolean getAddNoCheat() { return _addNoCheat; } // The set of active MinecraftServers that belong to this server group - private Set servers; + private Set _servers; + public Set getServers() { return _servers; } /** * Class constructor @@ -94,26 +131,38 @@ public class ServerGroup */ public ServerGroup(Map data, Region region) { - this._name = data.get("name"); - this._prefix = data.get("prefix"); - this._scriptName = data.get("scriptName"); - this._requiredRam = Integer.valueOf(data.get("ram")); - this._requiredCpu = Integer.valueOf(data.get("cpu")); - this._requiredTotalServers = Integer.valueOf(data.get("totalServers")); - this._requiredJoinableServers = Integer.valueOf(data.get("joinableServers")); - this._portSection = Integer.valueOf(data.get("portSection")); - this._arcadeGroup = Boolean.valueOf(data.get("arcadeGroup")); - this._worldZip = data.get("worldZip"); - this._plugin = data.get("plugin"); - this._configPath = data.get("configPath"); - this._minPlayers = Integer.valueOf(data.get("minPlayers")); - this._maxPlayers = Integer.valueOf(data.get("maxPlayers")); - this._pvp = Boolean.valueOf(data.get("pvp")); - this._tournament = Boolean.valueOf(data.get("tournament")); - this._generateFreeVersions = Boolean.valueOf(data.get("generateFreeVersions")); - this._games = data.get("games"); - this._serverType = data.get("serverType"); - this._addNoCheat = Boolean.valueOf(data.get("addNoCheat")); + _name = data.get("name"); + _prefix = data.get("prefix"); + _scriptName = data.get("scriptName"); + _requiredRam = Integer.valueOf(data.get("ram")); + _requiredCpu = Integer.valueOf(data.get("cpu")); + _requiredTotalServers = Integer.valueOf(data.get("totalServers")); + _requiredJoinableServers = Integer.valueOf(data.get("joinableServers")); + _portSection = Integer.valueOf(data.get("portSection")); + _arcadeGroup = Boolean.valueOf(data.get("arcadeGroup")); + _worldZip = data.get("worldZip"); + _plugin = data.get("plugin"); + _configPath = data.get("configPath"); + _minPlayers = Integer.valueOf(data.get("minPlayers")); + _maxPlayers = Integer.valueOf(data.get("maxPlayers")); + _pvp = Boolean.valueOf(data.get("pvp")); + _tournament = Boolean.valueOf(data.get("tournament")); + _generateFreeVersions = Boolean.valueOf(data.get("generateFreeVersions")); + _games = data.get("games"); + _serverType = data.get("serverType"); + _addNoCheat = Boolean.valueOf(data.get("addNoCheat")); + _teamRejoin = Boolean.valueOf(data.get("teamRejoin")); + _teamAutoJoin = Boolean.valueOf(data.get("teamAutoJoin")); + _teamForceBalance = Boolean.valueOf(data.get("teamForceBalance")); + _gameAutoStart = Boolean.valueOf(data.get("gameAutoStart")); + _gameTimeout = Boolean.valueOf(data.get("gameTimeout")); + _rewardGems = Boolean.valueOf(data.get("rewardGems")); + _rewardItems = Boolean.valueOf(data.get("rewardItems")); + _rewardStats = Boolean.valueOf(data.get("rewardStats")); + _rewardAchievements = Boolean.valueOf(data.get("rewardAchievements")); + _hotbarInventory = Boolean.valueOf(data.get("hotbarInventory")); + _hotbarHubClock = Boolean.valueOf(data.get("hotbarHubClock")); + _playerKickIdle = Boolean.valueOf(data.get("playerKickIdle")); fetchServers(region); } @@ -124,7 +173,7 @@ public class ServerGroup */ public int getServerCount() { - return servers.size(); + return _servers.size(); } /** @@ -135,7 +184,7 @@ public class ServerGroup { int joinable = 0; - for (MinecraftServer server : servers) + for (MinecraftServer server : _servers) { if (server.isJoinable()) { @@ -154,7 +203,7 @@ public class ServerGroup { int playerCount = 0; - for (MinecraftServer server : servers) + for (MinecraftServer server : _servers) { playerCount += server.getPlayerCount(); } @@ -170,7 +219,7 @@ public class ServerGroup { int maxPlayerCount = 0; - for (MinecraftServer server : servers) + for (MinecraftServer server : _servers) { maxPlayerCount += server.getMaxPlayerCount(); } @@ -186,7 +235,7 @@ public class ServerGroup { Collection emptyServers = new HashSet(); - for (MinecraftServer server : servers) + for (MinecraftServer server : _servers) { if (server.isEmpty() && server.getUptime() <= 150) // Only return empty servers that have been online for >150 seconds { @@ -203,14 +252,14 @@ public class ServerGroup */ private void fetchServers(Region region) { - this.servers = new HashSet(); + this._servers = new HashSet(); ServerRepository repository = ServerManager.getServerRepository(region); for (MinecraftServer server : repository.getServerStatuses()) { - if (_name.equals(server.getGroup())) + if (_name.equalsIgnoreCase(server.getGroup())) { - servers.add(server); + _servers.add(server); } } } @@ -218,15 +267,15 @@ public class ServerGroup /** * @return a unique server name suffix id, unique to any servers in this ServerGroup. */ - public int generateUniqueId() + public int generateUniqueId(int startId) { - int id = 0; + int id = startId; while (true) { boolean uniqueId = true; - for (MinecraftServer server : servers) + for (MinecraftServer server : _servers) { String serverName = server.getName(); try @@ -255,5 +304,4 @@ public class ServerGroup } } } - } diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerRepository.java index a9ebc5ad9..c0e2a50af 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerRepository.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerRepository.java @@ -1,7 +1,6 @@ package mineplex.serverdata; import java.util.Collection; -import java.util.Set; /** * The ServerRepository is used for storing/retrieving active sessions @@ -19,6 +18,8 @@ public interface ServerRepository */ public Collection getServerStatuses(); + public Collection getServersByGroup(String serverGroup); + /** * @param serverName - the name of the {@link MinecraftServer} to be fetched. * @return the currently active {@link MinecraftServer} with a matching {@code serverName}, @@ -61,6 +62,7 @@ public interface ServerRepository * currently active {@link ServerGroup}s in the repository. */ public Collection getServerGroups(); + + public Collection getDeadServers(); - Collection getDeadServers(); } diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Utility.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Utility.java index a7b3df1e1..122c71b2e 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Utility.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Utility.java @@ -1,5 +1,9 @@ package mineplex.serverdata; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -15,6 +19,9 @@ public class Utility private static Gson _gson = new GsonBuilder().create(); public static Gson getGson() { return _gson; } + // Public static jedis pool for interacting with central default jedis repo. + private static JedisPool _jedisPool; + /** * @param object - the (non-null) object to serialize * @return the serialized form of {@code object}. @@ -51,4 +58,36 @@ public class Utility return result; } + + /** + * @return the current timestamp (in milliseconds) fetched from the central jedis repository + * for synced timestamps. + */ + public static long currentTimeMillis() + { + long currentTime = 0; + Jedis jedis = getPool().getResource(); + + try + { + currentTime = Long.parseLong(jedis.time().get(0)); + } + finally + { + getPool().returnResource(jedis); + } + + return currentTime; + } + + public static JedisPool getPool() + { + if (_jedisPool == null) + { + _jedisPool = new JedisPool(new JedisPoolConfig(), + ServerManager.DEFAULT_REDIS_HOST, ServerManager.DEFAULT_REDIS_PORT); + } + + return _jedisPool; + } } diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java index e314d1d12..7e8e7cc55 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java @@ -6,7 +6,6 @@ import mineplex.core.command.CommandCenter; import mineplex.core.creature.Creature; import mineplex.core.donation.DonationManager; import mineplex.core.inventory.InventoryManager; -import mineplex.core.join.JoinQuit; import mineplex.core.memory.MemoryFix; import mineplex.core.monitor.LagMeter; import mineplex.core.npc.NpcManager; diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupport.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupport.java index 4dcc23100..1edc83080 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupport.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupport.java @@ -19,6 +19,7 @@ import mineplex.core.MiniPlugin; import mineplex.core.account.CoreClient; import mineplex.core.account.CoreClientManager; import mineplex.core.common.Rank; +import mineplex.core.common.jsonchat.JsonMessage; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.NautHashMap; @@ -99,21 +100,49 @@ public class CustomerSupport extends MiniPlugin caller.sendMessage(C.cDGreen + C.Strike + "============================================="); caller.sendMessage(C.cBlue + "Name : " + C.cYellow + playerName); caller.sendMessage(C.cBlue + "Rank : " + C.cYellow + (client.GetRank().Name.isEmpty() ? "Regular" : client.GetRank().Name)); - caller.sendMessage(C.cBlue + "Transactions : "); + caller.sendMessage(C.cBlue + "Coins : " + C.cYellow + donor.getCoins()); + caller.sendMessage(C.cBlue + "Gems : " + C.cYellow + donor.GetGems()); + int coinTransactionTotal = 0; + int enjinCoinsReceived = 0; + int coinSpentTotal = 0; + + int enjinBoostersReceived = 0; + for (CoinTransactionToken transaction : donor.getCoinTransactions()) { - if (transaction.Source.equalsIgnoreCase("Poll") || transaction.Source.equalsIgnoreCase("Coin Party Bomb Pickup") || transaction.Source.contains("Reward")) - continue; - - caller.sendMessage(C.cYellow + _date.format(transaction.Date) + C.cGray + " - " + C.cYellow + transaction.Amount + " Coins - Applied via " + transaction.Source); + if (transaction.Source.equalsIgnoreCase("Poll") || transaction.Source.equalsIgnoreCase("Coin Party Bomb Pickup") || transaction.Source.contains("Reward") || transaction.Source.contains("purchase")) + { + coinTransactionTotal += transaction.Amount; + + if (transaction.Source.contains("purchase")) + enjinCoinsReceived += transaction.Amount; + } } for (TransactionToken transaction : donor.getTransactions()) { - if (transaction.Coins == 0 && transaction.Gems == 0 && transaction.SalesPackageName.contains("Gem Booster")) - caller.sendMessage(C.cYellow + _date.format(transaction.Date) + C.cGray + " - " + C.cYellow + transaction.SalesPackageName); + coinSpentTotal += transaction.Coins; + + if (transaction.SalesPackageName.contains("Gem Booster")) + { + if (transaction.SalesPackageName.startsWith("Gem Booster") && transaction.Coins == 0 && transaction.Gems == 0 && transaction.SalesPackageName.split(" ").length == 3) + enjinBoostersReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); + } } + + caller.sendMessage(C.cBlue + "Enjin Coin Total Received : " + C.cYellow + enjinCoinsReceived); + caller.sendMessage(C.cBlue + "Enjin Booster Total Received : " + C.cYellow + enjinBoostersReceived); + + int coinsMissing = coinTransactionTotal - (donor.getCoins() + coinSpentTotal); + + if (coinsMissing > 0) + { + caller.sendMessage(C.cRed + "Coins missing!"); + new JsonMessage("[").color("blue").extra(C.cGreen + "Apply Missing Coins").color("green").click("run_command", "/sales coin " + playerName + " " + coinsMissing) + .add("] ").color("blue").add("Missing Coins.").color("yellow").sendToPlayer(caller); + } + caller.sendMessage(C.cDGreen + C.Strike + "============================================="); _salesPackageManager.displaySalesPackages(caller, playerName); caller.sendMessage(C.cDGreen + C.Strike + "============================================="); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/ArcadeManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/ArcadeManager.java index 6307602dc..3e8621b4c 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/ArcadeManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/ArcadeManager.java @@ -95,6 +95,7 @@ import nautilus.game.arcade.managers.GameLobbyManager; import nautilus.game.arcade.managers.GameLootManager; import nautilus.game.arcade.managers.GameManager; import nautilus.game.arcade.managers.GamePlayerManager; +import nautilus.game.arcade.managers.GameStatManager; import nautilus.game.arcade.managers.GameWorldManager; import nautilus.game.arcade.managers.IdleManager; import nautilus.game.arcade.managers.MiscManager; @@ -246,6 +247,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation new GameFlagManager(this); _gamePlayerManager = new GamePlayerManager(this); new GameAchievementManager(this); + new GameStatManager(this); new GameLootManager(this, petManager); _gameWorldManager = new GameWorldManager(this); new MiscManager(this); @@ -1000,6 +1002,9 @@ public class ArcadeManager extends MiniPlugin implements IRelation public void saveBasicStats(final Game game) { + if (!IsTournamentServer()) + return; + final Map data = new HashMap<>(); for (Player loser : game.getLosers()) diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/addons/TeamArmorAddon.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/addons/TeamArmorAddon.java index ce3d94de8..d0820dadf 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/addons/TeamArmorAddon.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/addons/TeamArmorAddon.java @@ -95,6 +95,5 @@ public class TeamArmorAddon extends MiniPlugin event.setCancelled(true); event.getWhoClicked().closeInventory(); - System.out.println(this.getClass().getName() + " 103"); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java index 73b4409a3..ef78410a5 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java @@ -926,8 +926,9 @@ public abstract class Game implements Listener if (!IsLive()) return; - String winnerText = ChatColor.WHITE + "§lNobody won the game..."; - + String winnerText = ChatColor.WHITE + "Nobody"; + ChatColor subColor = ChatColor.WHITE; + for (Player player : UtilServer.getPlayers()) { player.playSound(player.getLocation(), Sound.LEVEL_UP, 2f, 1f); @@ -944,12 +945,14 @@ public abstract class Game implements Listener WinnerTeam = team; Winner = team.GetName() + " Team"; - winnerText = team.GetColor() + C.Bold + team.GetName() + " won the game!"; - UtilPlayer.message(player, winnerText); + winnerText = team.GetColor() + team.GetName(); + subColor = team.GetColor(); + + UtilPlayer.message(player, team.GetColor() + C.Bold + team.GetName() + " won the game!"); } else { - UtilPlayer.message(player, winnerText); + UtilPlayer.message(player, "Nobody won the game!"); } @@ -960,7 +963,7 @@ public abstract class Game implements Listener UtilPlayer.message(player, ArcadeFormat.Line); } - UtilTitle.display(winnerText, _customWinLine, 20, 120, 20); + UtilTitle.display(winnerText, subColor + "won the game", 20, 120, 20); if (AnnounceSilence) Manager.GetChat().Silence(5000, false); @@ -969,6 +972,7 @@ public abstract class Game implements Listener public void AnnounceEnd(List places) { String winnerText = ChatColor.WHITE + "§lNobody won the game..."; + ChatColor subColor = ChatColor.WHITE; for (Player player : UtilServer.getPlayers()) { @@ -992,7 +996,8 @@ public abstract class Game implements Listener { Winner = places.get(0).getName(); - winnerText = C.cYellow + C.Bold + places.get(0).getName() + " won the game!"; + winnerText = C.cYellow + places.get(0).getName(); + subColor = ChatColor.YELLOW; UtilPlayer.message(player, C.cRed + C.Bold + "1st Place" + C.cWhite + " - " + places.get(0).getName()); } @@ -1016,7 +1021,7 @@ public abstract class Game implements Listener UtilPlayer.message(player, ArcadeFormat.Line); } - UtilTitle.display(winnerText, null, 20, 120, 20); + UtilTitle.display(winnerText, subColor + "won the game", 20, 120, 20); if (AnnounceSilence) Manager.GetChat().Silence(5000, false); @@ -1179,23 +1184,7 @@ public abstract class Game implements Listener } } - @EventHandler - public void onGameEnd(GameStateChangeEvent event) - { - if (event.GetState() == GameState.End) - { - for (StatTracker tracker : getStatTrackers()) - HandlerList.unregisterAll(tracker); - - if (CanAddStats) - { - Manager.saveBasicStats(this); - - if (Manager.IsTournamentServer()) - Manager.saveLeaderboardStats(this); - } - } - } + public Collection> getStatTrackers() { diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsDominate.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsDominate.java index fb5679abf..269118570 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsDominate.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsDominate.java @@ -74,7 +74,6 @@ public class ChampionsDominate extends Domination { SetKit(player, GetKits()[2], true); player.closeInventory(); - System.out.println(this.getClass().getName() + " 64"); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsTDM.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsTDM.java index 990301a99..0ed74d64a 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsTDM.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsTDM.java @@ -74,7 +74,6 @@ public class ChampionsTDM extends TeamDeathmatch { SetKit(player, GetKits()[2], true); player.closeInventory(); - System.out.println(this.getClass().getName() + " 61"); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/TeamDeathmatch.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/TeamDeathmatch.java index 3446fcc0b..3efce21ac 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/TeamDeathmatch.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/TeamDeathmatch.java @@ -164,7 +164,6 @@ public class TeamDeathmatch extends TeamGame { SetKit(player, GetKits()[2], true); player.closeInventory(); - System.out.println(this.getClass().getName() + " 167"); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minestrike/MineStrike.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minestrike/MineStrike.java index 25e7f3a0e..437395bb8 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minestrike/MineStrike.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minestrike/MineStrike.java @@ -1175,8 +1175,6 @@ public class MineStrike extends TeamGame public int getArrowHitArea(Player damagee, Location origin, Vector trajectory) { - System.out.println("Getting Area"); - //Move to near-player Location start = origin.clone().add(trajectory.clone().multiply(UtilMath.offset(origin, damagee.getEyeLocation()) - 2)); @@ -1189,19 +1187,15 @@ public class MineStrike extends TeamGame if (hitHead(damagee, loc)) { - System.out.println("Head"); return 1; } if (hitBody(damagee, loc)) { - System.out.println("Body"); return 0; } - - System.out.println("Miss"); return -1; } @@ -1217,11 +1211,11 @@ public class MineStrike extends TeamGame loc.add(snowball.getVelocity().clone().multiply(0.1)); } - if (hitHead(damagee, loc)) - return 1; - if (hitBody(damagee, loc)) return 0; + + if (hitHead(damagee, loc)) + return 1; return -1; } @@ -1230,13 +1224,13 @@ public class MineStrike extends TeamGame { return UtilMath.offset2d(loc, player.getLocation()) < 0.6 && //0.6 is ideal loc.getY() > player.getLocation().getY() && - loc.getY() < player.getEyeLocation().getY() - 0.2; + loc.getY() < player.getEyeLocation().getY() - 0.1; } public boolean hitHead(Player player, Location loc) { return UtilMath.offset2d(loc, player.getLocation()) < 0.3 && //0.3 is ideal - loc.getY() >= player.getEyeLocation().getY() - 0.2 && + loc.getY() >= player.getEyeLocation().getY() - 0.1 && loc.getY() < player.getEyeLocation().getY() + 0.2; } @@ -1399,7 +1393,7 @@ public class MineStrike extends TeamGame if (_bombPlanter == null) return; - if (!_bombPlanter.isBlocking()) + if (!_bombPlanter.isBlocking() || !_bombPlanter.isOnline()) { _bombPlanter.setExp(0f); UtilTitle.clear(_bombPlanter); @@ -1508,7 +1502,7 @@ public class MineStrike extends TeamGame Block block = _bombDefuser.getTargetBlock(null, 5); - if (block == null || !_bomb.isBlock(block) || UtilMath.offset(_bombDefuser.getLocation(), block.getLocation().add(0.5, 0, 0.5)) > 3) + if (block == null || !_bomb.isBlock(block) || !_bombDefuser.isOnline() || UtilMath.offset(_bombDefuser.getLocation(), block.getLocation().add(0.5, 0, 0.5)) > 3) { _bombDefuser.setExp(0f); _bombDefuser = null; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/paintball/Paintball.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/paintball/Paintball.java index e686d7692..f728822b2 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/paintball/Paintball.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/paintball/Paintball.java @@ -473,14 +473,12 @@ public class Paintball extends TeamGame for (ItemStack stack : player.getEquipment().getArmorContents()) { - System.out.println("Type:" + stack.getType() + " Meta:" + stack.getItemMeta()); if (!(stack.getItemMeta() instanceof LeatherArmorMeta)) continue; LeatherArmorMeta meta = (LeatherArmorMeta)stack.getItemMeta(); meta.setColor(color); stack.setItemMeta(meta); - System.out.println("Changed leather meta for " + player.getName()); } } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/paintball/kits/KitRifle.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/paintball/kits/KitRifle.java index d2c082e5f..f97d5c5fc 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/paintball/kits/KitRifle.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/paintball/kits/KitRifle.java @@ -65,7 +65,5 @@ public class KitRifle extends Kit metaBoots.setColor(Color.WHITE); boots.setItemMeta(metaBoots); player.getInventory().setBoots(boots); - - System.out.println("Game kit items to " + player.getName()); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java index 560aaa26a..ecab40ff3 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java @@ -292,7 +292,6 @@ public class GameFlagManager implements Listener { event.setCancelled(true); event.getWhoClicked().closeInventory(); - System.out.println(this.getClass().getName() + " 267"); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java index d25e1550f..306fa99e1 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java @@ -1194,7 +1194,6 @@ public class GameLobbyManager implements Listener, IPacketHandler { event.setCancelled(true); event.getWhoClicked().closeInventory(); - System.out.println(this.getClass().getName() + " 1150"); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLootManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLootManager.java index a4867621c..f50c15413 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLootManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLootManager.java @@ -7,6 +7,7 @@ import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.Material; +import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -18,6 +19,7 @@ import org.bukkit.inventory.ItemStack; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilFirework; +import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTitle; import mineplex.core.pet.PetManager; @@ -55,11 +57,11 @@ public class GameLootManager implements Listener //Chest _rewardManager.addReward(new InventoryReward(_rewardManager, Manager.getInventoryManager(), "Treasure Chest", "Treasure Chest", 1, 1, - new ItemStack(Material.CHEST), RewardRarity.COMMON, 2)); + new ItemStack(Material.CHEST), RewardRarity.COMMON, 3)); //Key _rewardManager.addReward(new InventoryReward(_rewardManager, Manager.getInventoryManager(), "Treasure Key", "Treasure Key", 1, 1, - new ItemStack(Material.DIAMOND), RewardRarity.UNCOMMON, 500)); + new ItemStack(Material.DIAMOND), RewardRarity.UNCOMMON, 600)); } @EventHandler @@ -120,18 +122,24 @@ public class GameLootManager implements Listener String outputName = reward.getRarity().getColor() + rewardData.getFriendlyName(); + String rarityName = ""; + if (reward.getRarity() != RewardRarity.COMMON) + rarityName = " " + reward.getRarity().getColor() + reward.getRarity().getName(); + //Log - System.out.println(F.name(player.getName()) + " found " + reward.getRarity().getName() + " treasure " + outputName); + System.out.println(F.name(player.getName()) + " found" + rarityName + " " + outputName); //Self Display - UtilTitle.display(C.cDGreen + C.Bold + "Loot", "You found " + outputName, 20, 120, 20, player); + UtilTitle.display(C.cGreen + "Game Loot", "You found " + outputName, 20, 120, 20, player); + //if (reward.getRarity() == RewardRarity.COMMON) + // UtilPlayer.message(player, F.main("Loot", "You found " + rarityName + outputName)); Random _random = new Random(); //Announce - if (reward.getRarity() != RewardRarity.COMMON) + //if (reward.getRarity() != RewardRarity.COMMON) { - Bukkit.broadcastMessage(F.main("Loot", F.name(player.getName()) + " found " + reward.getRarity().getName() + " treasure " + outputName)); + Bukkit.broadcastMessage(F.main("Loot", F.name(player.getName()) + " found" + rarityName + " " + outputName)); } //Effect @@ -148,11 +156,15 @@ public class GameLootManager implements Listener { FireworkEffect effect = FireworkEffect.builder().with(FireworkEffect.Type.BALL).withColor(Color.YELLOW).withFade(Color.WHITE).build(); UtilFirework.playFirework(player.getEyeLocation(), effect); + + player.getWorld().playSound(player.getEyeLocation().add(0.5, 0.5, 0.5), Sound.WITHER_SPAWN, 5F, 1.2F); } else if (reward.getRarity() == RewardRarity.LEGENDARY) { FireworkEffect effect = FireworkEffect.builder().with(FireworkEffect.Type.BALL_LARGE).withColor(Color.RED).withFade(Color.BLACK).build(); UtilFirework.playFirework(player.getEyeLocation(), effect); + + player.getWorld().playSound(player.getEyeLocation().add(0.5, 0.5, 0.5), Sound.ENDERDRAGON_DEATH, 10F, 2.0F); } } @@ -169,5 +181,26 @@ public class GameLootManager implements Listener giveReward(event.getPlayer()); event.setCancelled(true); } + + if (event.getMessage().startsWith("/lootdebug100")) + { + event.getPlayer().sendMessage(C.cGreen + C.Bold + "Loot Debug 100..."); + + final Player fPlayer = event.getPlayer(); + + for (int i=0 ; i<100 ; i++) + { + UtilServer.getServer().getScheduler().runTaskLater(Manager.GetPlugin(), new Runnable() + { + @Override + public void run() + { + giveReward(fPlayer); + } + }, 2 * i); + } + + event.setCancelled(true); + } } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameManager.java index 6b98e65f0..bb2bb1323 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameManager.java @@ -26,6 +26,7 @@ import nautilus.game.arcade.game.Game; import nautilus.game.arcade.game.GameTeam; import nautilus.game.arcade.game.Game.GameState; import nautilus.game.arcade.game.GameTeam.PlayerState; +import nautilus.game.arcade.stats.StatTracker; import org.bukkit.ChatColor; import org.bukkit.Color; @@ -36,6 +37,7 @@ import org.bukkit.FireworkEffect.Type; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; public class GameManager implements Listener @@ -281,40 +283,7 @@ public class GameManager implements Listener event.GetGame().deRegisterStats(); } - @EventHandler - public void StatEnableDisable(GameStateChangeEvent event) - { - if (!Manager.IsRewardStats()) - return; - - if (event.GetState() != GameState.Live) - return; - - int requirement = (int)((double)event.GetGame().Manager.GetPlayerFull() * 0.75d); - - event.GetGame().CanAddStats = (double)event.GetGame().GetPlayers(true).size() >= requirement; - - if (!event.GetGame().CanAddStats) - event.GetGame().Announce(C.Bold + "Stats/Achievements Disabled. Requires " + requirement + " Players."); - } - - @EventHandler - public void StatRegister(GameStateChangeEvent event) - { - if (!Manager.IsRewardStats()) - return; - - if (event.GetState() != GameState.Dead) - return; - - for (Player player : event.GetGame().GetStats().keySet()) - { - for (String stat : event.GetGame().GetStats().get(player).keySet()) - { - Manager.GetStatsManager().incrementStat(player, stat, event.GetGame().GetStats().get(player).get(stat)); - } - } - } + @EventHandler public void ScoreboardTitle(UpdateEvent event) diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GamePlayerManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GamePlayerManager.java index 189399c12..9e1f90640 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GamePlayerManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GamePlayerManager.java @@ -26,10 +26,12 @@ import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; import mineplex.core.donation.Donor; +import mineplex.core.recharge.Recharge; import mineplex.core.shop.page.ConfirmationPage; import mineplex.minecraft.game.core.combat.event.CombatDeathEvent; import mineplex.minecraft.game.core.damage.CustomDamageEvent; import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.events.PlayerStateChangeEvent; import nautilus.game.arcade.game.Game; import nautilus.game.arcade.game.Game.GameState; import nautilus.game.arcade.game.GameTeam; @@ -139,6 +141,12 @@ public class GamePlayerManager implements Listener } } + @EventHandler + public void PlayerStateChange(PlayerStateChangeEvent event) + { + Recharge.Instance.useForce(event.GetPlayer(), "Return to Hub", 4000); + } + @EventHandler public void InventoryClick(InventoryClickEvent event) { diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/MiscManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/MiscManager.java index a52a8db5b..71c6729a4 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/MiscManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/MiscManager.java @@ -5,6 +5,7 @@ import java.util.List; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; +import mineplex.core.recharge.Recharge; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import nautilus.game.arcade.ArcadeManager; @@ -148,6 +149,9 @@ public class MiscManager implements Listener if (player.getItemInHand().getType() != Material.WATCH) return; + if (!Recharge.Instance.usable(event.getPlayer(), "Return to Hub")) + return; + Manager.GetPortal().SendPlayerToServer(player, "Lobby"); } diff --git a/Website/LOC.Website.Common/Contexts/Repository.cs b/Website/LOC.Website.Common/Contexts/Repository.cs index 9b19981d9..5a842faa1 100644 --- a/Website/LOC.Website.Common/Contexts/Repository.cs +++ b/Website/LOC.Website.Common/Contexts/Repository.cs @@ -52,7 +52,14 @@ const string PREFIX = "CommitChanges() failed because: "; try { - Context.SaveChanges(); + if (Context.SaveChanges() == 0) + Log("WARNING", "No entities to save: " + Environment.StackTrace); + /* + * List modifiedOrAddedEntities = context.ChangeTracker.Entries() + .Where(x => x.State == System.Data.EntityState.Modified + || x.State == System.Data.EntityState.Added) + .Select(x=>x.Entity).ToList(); + * */ } catch (DbEntityValidationException ex) { diff --git a/Website/LOC.Website.Common/Models/AccountAdministrator.cs b/Website/LOC.Website.Common/Models/AccountAdministrator.cs index 96a6b8824..d97655952 100644 --- a/Website/LOC.Website.Common/Models/AccountAdministrator.cs +++ b/Website/LOC.Website.Common/Models/AccountAdministrator.cs @@ -559,17 +559,12 @@ if (rank == null) return account.Rank.ToString(); - repository.Attach(account); - repository.Edit(account); - var expire = DateTime.Now.AddMonths(1).AddMilliseconds(-DateTime.Now.Millisecond); account.Rank = rank; account.RankExpire = expire; account.RankPerm = token.Perm; - repository.CommitChanges(); - repository.Edit(account); if ((rank.Name == "HERO" || rank.Name == "ULTRA") && token.Perm) diff --git a/Website/LOC.Website.Common/Models/PetAdministrator.cs b/Website/LOC.Website.Common/Models/PetAdministrator.cs index a4f23362d..15507f4c5 100644 --- a/Website/LOC.Website.Common/Models/PetAdministrator.cs +++ b/Website/LOC.Website.Common/Models/PetAdministrator.cs @@ -21,12 +21,15 @@ { using (var repository = _repositoryFactory.CreateRepository()) { + bool added = false; foreach (var item in petTokens.Where(item => !repository.Any(x => x.PetType == item.PetType))) { repository.Add(item); + added = true; } - repository.CommitChanges(); + if (added) + repository.CommitChanges(); return repository.GetAll().Include(x => x.SalesPackage).ToList(); } @@ -36,12 +39,15 @@ { using (var repository = _repositoryFactory.CreateRepository()) { + bool added = false; foreach (var item in petExtraTokens.Where(item => !repository.Any(x => x.Name == item.Name && x.Material == item.Material))) { repository.Add(item); + added = true; } - repository.CommitChanges(); + if (added) + repository.CommitChanges(); return repository.GetAll().Include(x => x.SalesPackage).ToList(); } @@ -72,10 +78,12 @@ return; var pet = account.Pets.FirstOrDefault(x => x.PetType.Equals(token.PetType)); - + if (pet == null) return; + account.Pets.RemoveAll(x => x.PetType.Equals(token.PetType) && x.OwnedPetId != pet.OwnedPetId); + pet.PetName = token.PetName; repository.Edit(pet); diff --git a/Website/LOC.Website.Common/Models/PvpAdministrator.cs b/Website/LOC.Website.Common/Models/PvpAdministrator.cs index 3f9854326..d14ee5e07 100644 --- a/Website/LOC.Website.Common/Models/PvpAdministrator.cs +++ b/Website/LOC.Website.Common/Models/PvpAdministrator.cs @@ -35,12 +35,15 @@ { using (var repository = RepositoryFactory.CreateRepository()) { + bool added = false; foreach (var skill in skills.Where(skill => !repository.Any(x => x.Name == skill.Name && x.Level == skill.Level))) { repository.Add(skill); + added = true; } - repository.CommitChanges(); + if (added) + repository.CommitChanges(); return repository.GetAll().Include(x => x.SalesPackage).ToList(); } diff --git a/Website/LOC.Website.Web/LOC.Website.Web.Publish.xml b/Website/LOC.Website.Web/LOC.Website.Web.Publish.xml index bdefbafe8..dc38d1feb 100644 --- a/Website/LOC.Website.Web/LOC.Website.Web.Publish.xml +++ b/Website/LOC.Website.Web/LOC.Website.Web.Publish.xml @@ -1,13 +1,11 @@  - - @@ -20,17 +18,15 @@ - - + + - - @@ -44,27 +40,25 @@ - - - - + - - + + + @@ -75,24 +69,25 @@ - - + - + + + - + + - @@ -100,7 +95,7 @@ - + @@ -108,40 +103,42 @@ + + + - - - + + - + + - - - + + + - @@ -152,19 +149,23 @@ - + - - + + + + + + @@ -173,6 +174,7 @@ + @@ -183,93 +185,91 @@ - + - + + - - - + - + - - + + - + - + - + + - + - + - - + - + - - + - - + + - + - - + + - - + + - + - + @@ -280,22 +280,24 @@ - + - + + - + + @@ -303,6 +305,7 @@ + @@ -310,18 +313,16 @@ - + - - @@ -332,21 +333,22 @@ + - - + + + - - + @@ -354,8 +356,6 @@ - - @@ -363,11 +363,13 @@ - + - + + + @@ -375,97 +377,94 @@ + - - + + + - - + + + - - + - - + - - - - + - - + - + - - - + - + - + - + + + - + @@ -473,329 +472,330 @@ - + - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - + + - + - + - - - + + + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -808,15 +808,15 @@ - + + - - + @@ -830,7 +830,6 @@ - @@ -838,8 +837,8 @@ - + @@ -849,7 +848,6 @@ - @@ -860,29 +858,30 @@ + - - + + - + + - - + @@ -890,17 +889,18 @@ - - + + + @@ -908,22 +908,23 @@ - - + - + - + + + - + @@ -934,65 +935,61 @@ - + - - - - + - - + - + + - - - + - + - + - - + + + - + @@ -1000,56 +997,59 @@ - - + + - + + - + + - + - + + - - + + - - + + - + - - - - - + + + + + - + \ No newline at end of file diff --git a/Website/LOCWebsite.suo b/Website/LOCWebsite.suo index 6a1f5de2e..18194052c 100644 Binary files a/Website/LOCWebsite.suo and b/Website/LOCWebsite.suo differ