Merge branch 'master' of ssh://184.154.0.242:7999/min/Mineplex

This commit is contained in:
CoderTim 2014-09-22 02:53:55 -04:00
commit 77e21c0d99
72 changed files with 2200 additions and 1707 deletions

Binary file not shown.

View File

@ -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<String> _playersNeedingBenefit = new HashSet<String>();
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());
}
}

View File

@ -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<String> retrievePlayerBenefits(String uuid)
{
final List<String> benefits = new ArrayList<String>();
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));
}
}

View File

@ -168,9 +168,38 @@ public class CoreClientManager extends MiniPlugin
client.SetAccountId(token.AccountId); client.SetAccountId(token.AccountId);
client.SetRank(Rank.valueOf(token.Rank)); 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 // JSON sql response
Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(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() Bukkit.getServer().getScheduler().runTask(GetPlugin(), new Runnable()
{ {
public void run() public void run()

View File

@ -10,13 +10,11 @@ public class CloseButton implements IButton
public void ClickedLeft(Player player) public void ClickedLeft(Player player)
{ {
player.closeInventory(); player.closeInventory();
System.out.println(this.getClass().getName() + " 13");
} }
@Override @Override
public void ClickedRight(Player player) public void ClickedRight(Player player)
{ {
player.closeInventory(); player.closeInventory();
System.out.println(this.getClass().getName() + " 19");
} }
} }

View File

@ -48,7 +48,18 @@ public class Menu extends ShopPageBase<CosmeticManager, CosmeticShop>
@Override @Override
protected void BuildPage() 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 treasureChestCount = Plugin.getInventoryManager().Get(Player).getItemCount("Treasure Chest");
int treasureKeyCount = Plugin.getInventoryManager().Get(Player).getItemCount("Treasure Key"); int treasureKeyCount = Plugin.getInventoryManager().Get(Player).getItemCount("Treasure Key");
@ -63,7 +74,8 @@ public class Menu extends ShopPageBase<CosmeticManager, CosmeticShop>
if (treasureChestCount > 0 && treasureKeyCount > 0) if (treasureChestCount > 0 && treasureKeyCount > 0)
{ {
lore.add(ChatColor.RESET + C.cGreen + "Left-Click to open Treasure Chest"); 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) else if (treasureChestCount > 0)
@ -306,7 +318,6 @@ public class Menu extends ShopPageBase<CosmeticManager, CosmeticShop>
{ {
public void run() public void run()
{ {
System.out.println("Added treasure key");
Plugin.getInventoryManager().addItemToInventory(Player, "Treasure", "Treasure Key", 1); Plugin.getInventoryManager().addItemToInventory(Player, "Treasure", "Treasure Key", 1);
Refresh(); Refresh();
} }

View File

@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; 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;
}
} }

View File

@ -23,7 +23,9 @@ public class SongData
{ {
if (System.currentTimeMillis() > EndTime) if (System.currentTimeMillis() > EndTime)
{ {
if (Block.getType() == Material.JUKEBOX)
Block.setType(Material.AIR); Block.setType(Material.AIR);
return true; return true;
} }

View File

@ -4,9 +4,12 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import mineplex.core.common.util.F; 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.common.util.UtilPlayer;
import mineplex.core.gadget.GadgetManager; import mineplex.core.gadget.GadgetManager;
import mineplex.core.gadget.event.GadgetActivateEvent; import mineplex.core.gadget.event.GadgetActivateEvent;
import mineplex.core.gadget.event.GadgetBlockEvent;
import mineplex.core.gadget.gadgets.SongData; import mineplex.core.gadget.gadgets.SongData;
import mineplex.core.recharge.Recharge; import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType; import mineplex.core.updater.UpdateType;
@ -14,10 +17,11 @@ import mineplex.core.updater.event.UpdateEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Effect; import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class MusicGadget extends Gadget public class MusicGadget extends Gadget
{ {
@ -46,8 +50,20 @@ public class MusicGadget extends Gadget
return; 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; 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); player.getWorld().playEffect(player.getLocation(), Effect.RECORD_PLAY, _id);
@ -82,4 +98,38 @@ public class MusicGadget extends Gadget
songIterator.remove(); songIterator.remove();
} }
} }
@EventHandler
public void gadgetBlockChange(GadgetBlockEvent event)
{
for (Iterator<Block> 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;
}
} }

View File

@ -50,7 +50,7 @@ public class SendCommand extends CommandBase<Portal>
return; 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 + "!")); 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; return;

View File

@ -63,7 +63,7 @@ public class ServerCommand extends CommandBase<Portal>
else else
deniedAccess = true; 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)) if (playerRank.Has(Rank.ULTRA))
Plugin.SendPlayerToServerWithMessage(player, args[0]); Plugin.SendPlayerToServerWithMessage(player, args[0]);
@ -93,7 +93,7 @@ public class ServerCommand extends CommandBase<Portal>
{ {
UtilPlayer.message( UtilPlayer.message(
player, 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]));
} }
} }
}); });

View File

@ -25,14 +25,18 @@ import mineplex.core.portal.Commands.*;
import mineplex.core.updater.UpdateType; import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent; import mineplex.core.updater.event.UpdateEvent;
import mineplex.serverdata.Region; import mineplex.serverdata.Region;
import mineplex.serverdata.ServerCommandManager;
import mineplex.serverdata.ServerManager; import mineplex.serverdata.ServerManager;
public class Portal extends MiniPlugin public class Portal extends MiniPlugin
{ {
private HashSet<String> _connectingPlayers = new HashSet<String>();
//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<String> _connectingPlayers = new HashSet<String>();
private Region _region; private Region _region;
private boolean _retrieve = true; private boolean _retrieve = true;
private String _serverName; private String _serverName;
@ -41,12 +45,15 @@ public class Portal extends MiniPlugin
{ {
super("Portal", plugin); super("Portal", plugin);
instance = this;
this._serverName = serverName; this._serverName = serverName;
this._region = plugin.getConfig().getBoolean("serverstatus.us") ? Region.US : Region.EU; this._region = plugin.getConfig().getBoolean("serverstatus.us") ? Region.US : Region.EU;
Bukkit.getMessenger().registerOutgoingPluginChannel(GetPlugin(), "BungeeCord"); 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) public void SendAllPlayers(String serverName)
@ -111,15 +118,11 @@ public class Portal extends MiniPlugin
}, 20L); }, 20L);
} }
public void AddTransferRecord(final String playerName, final String serverName) public static void transferPlayer(String playerName, String serverName)
{ {
Bukkit.getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable() ServerTransfer serverTransfer = new ServerTransfer(playerName, serverName);
{ TransferCommand transferCommand = new TransferCommand(serverTransfer);
public void run() transferCommand.publish();
{
_repository.addServerTransfer(new ServerTransfer(playerName, serverName));
}
});
} }
public void DoesServerExist(final String serverName, final Callback<Boolean> callback) public void DoesServerExist(final String serverName, final Callback<Boolean> callback)
@ -149,51 +152,4 @@ public class Portal extends MiniPlugin
AddCommand(new ServerCommand(this)); AddCommand(new ServerCommand(this));
AddCommand(new SendCommand(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<ServerTransfer> serverTransfers = _repository.getServerTransfers();
for (Iterator<ServerTransfer> 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());
}
}
}
});
}
});
}
}
} }

View File

@ -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<ServerTransfer> getServerTransfers()
{
Set<ServerTransfer> serverTransfers = new HashSet<ServerTransfer>();
Jedis jedis = _jedisPool.getResource();
try
{
String setKey = "servertransfers";
Set<String> playerNames = jedis.smembers(setKey);
Pipeline pipeline = jedis.pipelined();
List<Response<String>> responses = new ArrayList<Response<String>>();
for (String playerName : playerNames)
{
String dataKey = concatenate(setKey, playerName);
responses.add(pipeline.get(dataKey));
}
pipeline.sync();
for (Response<String> 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.<player name>' contains the JSON serialized 'ServerTransfer' object holding info.
*/
}

View File

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

View File

@ -426,7 +426,6 @@ public class PunishPage extends CraftInventoryCustom implements Listener
{ {
_plugin.AddPunishment(_target, category, _reason, _player, severity, ban, punishTime); _plugin.AddPunishment(_target, category, _reason, _player, severity, ban, punishTime);
_player.closeInventory(); _player.closeInventory();
System.out.println(this.getClass().getName() + " 429");
ClosePunish(); ClosePunish();
} }
@ -452,7 +451,6 @@ public class PunishPage extends CraftInventoryCustom implements Listener
{ {
punishment.Remove(_player.getName(), _reason); punishment.Remove(_player.getName(), _reason);
_player.closeInventory(); _player.closeInventory();
System.out.println(this.getClass().getName() + " 455");
ClosePunish(); ClosePunish();
} }
} }

View File

@ -67,8 +67,8 @@ public class RewardManager
//Increase Value //Increase Value
if (_doubleGadgetValue) if (_doubleGadgetValue)
{ {
minValue *= 2; minValue *= 1.5;
maxValue *= 2; maxValue *= 1.5;
} }
// Gadgets // Gadgets
@ -111,8 +111,8 @@ public class RewardManager
//Increase Value //Increase Value
if (_doubleGadgetValue) if (_doubleGadgetValue)
{ {
minValue *= 2; minValue *= 1.5;
maxValue *= 2; maxValue *= 1.5;
} }
// Gadgets // Gadgets

View File

@ -195,7 +195,6 @@ public abstract class ShopBase<PluginType extends MiniPlugin> implements Listene
PlayerPageMap.get(event.getPlayer().getName()).Dispose(); PlayerPageMap.get(event.getPlayer().getName()).Dispose();
event.getPlayer().closeInventory(); event.getPlayer().closeInventory();
System.out.println(this.getClass().getName() + " 184");
CloseShopForPlayer(event.getPlayer()); CloseShopForPlayer(event.getPlayer());
PlayerPageMap.remove(event.getPlayer().getName()); PlayerPageMap.remove(event.getPlayer().getName());

View File

@ -106,7 +106,6 @@ public class ConfirmationPage<PluginType extends MiniPlugin, ShopType extends Sh
else else
{ {
player.closeInventory(); player.closeInventory();
System.out.println(this.getClass().getName() + " 109");
} }
} }
@ -292,7 +291,6 @@ public class ConfirmationPage<PluginType extends MiniPlugin, ShopType extends Sh
else if (Player != null) else if (Player != null)
{ {
Player.closeInventory(); Player.closeInventory();
System.out.println(this.getClass().getName() + " 291");
} }
} }
catch (Exception exception) catch (Exception exception)

View File

@ -2,7 +2,6 @@ package mineplex.core.status;
import java.io.File; import java.io.File;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -18,11 +17,12 @@ import mineplex.serverdata.MinecraftServer;
import mineplex.serverdata.Region; import mineplex.serverdata.Region;
import mineplex.serverdata.ServerManager; import mineplex.serverdata.ServerManager;
import mineplex.serverdata.ServerRepository; import mineplex.serverdata.ServerRepository;
import mineplex.serverdata.Utility;
public class ServerStatusManager extends MiniPlugin public class ServerStatusManager extends MiniPlugin
{ {
// The default timeout (in milliseconds) before the ServerStatus expires. // The default timeout (in seconds) before the ServerStatus expires.
public final int DEFAULT_SERVER_TIMEOUT = 15000; public final int DEFAULT_SERVER_TIMEOUT = 15;
private ServerRepository _repository; private ServerRepository _repository;
private LagMeter _lagMeter; private LagMeter _lagMeter;
@ -30,7 +30,6 @@ public class ServerStatusManager extends MiniPlugin
private String _name; private String _name;
private boolean _us; private boolean _us;
private boolean _alternateSeconds;
private boolean _enabled = true; private boolean _enabled = true;
private long _startUpDate; private long _startUpDate;
@ -39,26 +38,20 @@ public class ServerStatusManager extends MiniPlugin
{ {
super("Server Status Manager", plugin); super("Server Status Manager", plugin);
this._startUpDate = System.currentTimeMillis(); _startUpDate = Utility.currentTimeMillis();
_lagMeter = lagMeter; _lagMeter = lagMeter;
if (new File("IgnoreUpdates.dat").exists()) if (new File("IgnoreUpdates.dat").exists())
_enabled = false; _enabled = false;
ServerListPingEvent event = new ServerListPingEvent(null, plugin.getServer().getMotd(), plugin.getServer().getOnlinePlayers().size(), plugin.getServer().getMaxPlayers());
GetPluginManager().callEvent(event);
setupConfigValues(); setupConfigValues();
String address = Bukkit.getServer().getIp().isEmpty() ? "localhost" : Bukkit.getServer().getIp();
_name = plugin.getConfig().getString("serverstatus.name"); _name = plugin.getConfig().getString("serverstatus.name");
_us = plugin.getConfig().getBoolean("serverstatus.us"); _us = plugin.getConfig().getBoolean("serverstatus.us");
Region region = _us ? Region.US : Region.EU; Region region = _us ? Region.US : Region.EU;
_repository = ServerManager.getServerRepository(region); _repository = ServerManager.getServerRepository(region);
saveServerStatus();
} }
private void setupConfigValues() private void setupConfigValues()
@ -117,11 +110,6 @@ public class ServerStatusManager extends MiniPlugin
if (!_enabled) if (!_enabled)
return; return;
_alternateSeconds = !_alternateSeconds;
if (!_alternateSeconds)
return;
saveServerStatus(); saveServerStatus();
} }
@ -136,7 +124,7 @@ public class ServerStatusManager extends MiniPlugin
{ {
public void run() public void run()
{ {
_repository.updataServerStatus(serverSnapshot, 15000); _repository.updataServerStatus(serverSnapshot, DEFAULT_SERVER_TIMEOUT);
} }
}); });
} }

View File

@ -39,4 +39,10 @@ public class BlockInfo
{ {
return _block.hashCode(); return _block.hashCode();
} }
@Override
public boolean equals(Object obj)
{
return _block.equals(obj);
}
} }

View File

@ -16,6 +16,7 @@ import org.bukkit.craftbukkit.v1_7_R4.util.CraftMagicNumbers;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import net.minecraft.server.v1_7_R4.PacketPlayOutBlockAction; import net.minecraft.server.v1_7_R4.PacketPlayOutBlockAction;
import mineplex.core.blockrestore.BlockRestore;
import mineplex.core.common.util.C; import mineplex.core.common.util.C;
import mineplex.core.common.util.F; import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilParticle; import mineplex.core.common.util.UtilParticle;
@ -35,6 +36,7 @@ import mineplex.core.treasure.animation.UncommonAnimation;
*/ */
public class Treasure public class Treasure
{ {
private BlockRestore _blockRestore;
// Decay Sets // Decay Sets
private HashSet<BlockInfo> _wallsBlockInfo = new HashSet<>(); private HashSet<BlockInfo> _wallsBlockInfo = new HashSet<>();
@ -55,9 +57,11 @@ public class Treasure
private TreasureStyle _style; private TreasureStyle _style;
public Treasure(Player player, Reward[] rewards) public Treasure(Player player, Reward[] rewards, BlockRestore blockRestore)
{ {
this(player, new Random(), rewards); this(player, new Random(), rewards);
_blockRestore = blockRestore;
} }
public Treasure(Player player, Random seed, Reward[] rewards) public Treasure(Player player, Random seed, Reward[] rewards)
@ -88,6 +92,9 @@ public class Treasure
if (Math.abs(x) == 1 || Math.abs(z) == 1) if (Math.abs(x) == 1 || Math.abs(z) == 1)
{ {
Block block = _centerBlock.getRelative(x, 0, z); Block block = _centerBlock.getRelative(x, 0, z);
_blockRestore.Restore(block);
_centerBlockInfo.add(new BlockInfo(block)); _centerBlockInfo.add(new BlockInfo(block));
setBlock(block, _style.getPrimaryMaterial(), _style.getPrimaryData()); setBlock(block, _style.getPrimaryMaterial(), _style.getPrimaryData());
} }
@ -101,12 +108,18 @@ public class Treasure
{ {
{ {
Block block = _centerBlock.getRelative(x, 0, -2); Block block = _centerBlock.getRelative(x, 0, -2);
_blockRestore.Restore(block);
_outerRingBlockInfo.add(new BlockInfo(block)); _outerRingBlockInfo.add(new BlockInfo(block));
setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData()); setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData());
} }
{ {
Block block = _centerBlock.getRelative(x, 0, 2); Block block = _centerBlock.getRelative(x, 0, 2);
_blockRestore.Restore(block);
_outerRingBlockInfo.add(new BlockInfo(block)); _outerRingBlockInfo.add(new BlockInfo(block));
setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData()); setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData());
} }
@ -116,12 +129,18 @@ public class Treasure
{ {
{ {
Block block = _centerBlock.getRelative(-2, 0, z); Block block = _centerBlock.getRelative(-2, 0, z);
_blockRestore.Restore(block);
_outerRingBlockInfo.add(new BlockInfo(block)); _outerRingBlockInfo.add(new BlockInfo(block));
setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData()); setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData());
} }
{ {
Block block = _centerBlock.getRelative(2, 0, z); Block block = _centerBlock.getRelative(2, 0, z);
_blockRestore.Restore(block);
_outerRingBlockInfo.add(new BlockInfo(block)); _outerRingBlockInfo.add(new BlockInfo(block));
setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData()); setBlock(block, _style.getSecondaryMaterial(), _style.getSecondaryData());
} }
@ -138,6 +157,9 @@ public class Treasure
{ {
Block playerBlock = getPlayerBlock(); Block playerBlock = getPlayerBlock();
Block block = playerBlock.getRelative(x, 0, z); Block block = playerBlock.getRelative(x, 0, z);
_blockRestore.Restore(block);
_wallsBlockInfo.add(new BlockInfo(block)); _wallsBlockInfo.add(new BlockInfo(block));
setBlock(block, _style.getWallMaterial(), _style.getWallData()); setBlock(block, _style.getWallMaterial(), _style.getWallData());
} }
@ -160,6 +182,9 @@ public class Treasure
if (_tickCount == 5) if (_tickCount == 5)
{ {
Block block = _centerBlock; Block block = _centerBlock;
_blockRestore.Restore(block);
_centerBlockInfo.add(new BlockInfo(block)); _centerBlockInfo.add(new BlockInfo(block));
_centerBlockInfo.add(new BlockInfo(block.getRelative(BlockFace.DOWN))); _centerBlockInfo.add(new BlockInfo(block.getRelative(BlockFace.DOWN)));
setBlock(block, Material.REDSTONE_LAMP_ON, (byte) 0); setBlock(block, Material.REDSTONE_LAMP_ON, (byte) 0);
@ -388,16 +413,20 @@ public class Treasure
public boolean containsBlock(Block block) public boolean containsBlock(Block block)
{ {
if (_wallsBlockInfo.contains(block)) for (BlockInfo info : _wallsBlockInfo)
if (info.getBlock().equals(block))
return true; return true;
if (_outerRingBlockInfo.contains(block)) for (BlockInfo info : _outerRingBlockInfo)
if (info.getBlock().equals(block))
return true; return true;
if (_centerBlockInfo.contains(block)) for (BlockInfo info : _centerBlockInfo)
if (info.getBlock().equals(block))
return true; return true;
if (_chestBlockInfo.contains(block)) for (BlockInfo info : _chestBlockInfo)
if (info.getBlock().equals(block))
return true; return true;
return false; return false;

View File

@ -14,7 +14,7 @@ public class TreasureKey extends SalesPackageBase
{ {
public TreasureKey() 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; KnownPackage = false;
OneTimePurchaseOnly = false; OneTimePurchaseOnly = false;

View File

@ -23,6 +23,7 @@ import org.bukkit.event.player.PlayerVelocityEvent;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin; import mineplex.core.MiniPlugin;
import mineplex.core.blockrestore.BlockRestore;
import mineplex.core.common.util.C; import mineplex.core.common.util.C;
import mineplex.core.common.util.F; import mineplex.core.common.util.F;
import mineplex.core.common.util.NautHashMap; import mineplex.core.common.util.NautHashMap;
@ -53,13 +54,15 @@ public class TreasureManager extends MiniPlugin
private NautHashMap<Player, Treasure> _playerTreasureMap; private NautHashMap<Player, Treasure> _playerTreasureMap;
private RewardManager _rewardManager; private RewardManager _rewardManager;
private InventoryManager _inventoryManager; 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); super("Treasure", plugin);
_playerTreasureMap = new NautHashMap<Player, Treasure>(); _playerTreasureMap = new NautHashMap<Player, Treasure>();
_inventoryManager = inventoryManager; _inventoryManager = inventoryManager;
_blockRestore = blockRestore;
_rewardManager = new RewardManager(donationManager, inventoryManager, petManager, _rewardManager = new RewardManager(donationManager, inventoryManager, petManager,
250, 500, 250, 500,
750, 1500, 750, 1500,
@ -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")); Bukkit.broadcastMessage(F.main("Treasure", F.name(player.getName()) + " is opening a " + C.cGreen + "Treasure Chest"));
Reward[] rewards = _rewardManager.getRewards(player, true); Reward[] rewards = _rewardManager.getRewards(player, true);
Treasure treasure = new Treasure(player, rewards); Treasure treasure = new Treasure(player, rewards, _blockRestore);
_playerTreasureMap.put(player, treasure); _playerTreasureMap.put(player, treasure);
Location teleportLocation = treasure.getPlayerBlock().getLocation().add(0.5, 0, 0.5); Location teleportLocation = treasure.getPlayerBlock().getLocation().add(0.5, 0, 0.5);

View File

@ -12,7 +12,7 @@
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/> <booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value=""/> <stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value=""/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="true"/> <booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${BUILD_FILES}\common.xml"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${build_files}${BUILD_FILES}\common.xml"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,clean"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,clean"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/> <booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/Mineplex.Hub}"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/Mineplex.Hub}"/>

View File

@ -38,6 +38,7 @@ import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Scoreboard;
import mineplex.core.MiniClientPlugin; import mineplex.core.MiniClientPlugin;
import mineplex.core.RankBenefitsGiver9000;
import mineplex.core.account.CoreClient; import mineplex.core.account.CoreClient;
import mineplex.core.account.CoreClientManager; import mineplex.core.account.CoreClientManager;
import mineplex.core.account.event.RetrieveClientInformationEvent; import mineplex.core.account.event.RetrieveClientInformationEvent;
@ -159,8 +160,9 @@ public class HubManager extends MiniClientPlugin<HubClient>
_mountManager = new MountManager(_plugin, clientManager, donationManager, blockRestore, _disguiseManager); _mountManager = new MountManager(_plugin, clientManager, donationManager, blockRestore, _disguiseManager);
_inventoryManager = new InventoryManager(plugin); _inventoryManager = new InventoryManager(plugin);
new RankBenefitsGiver9000(plugin, clientManager, _inventoryManager);
_gadgetManager = new GadgetManager(_plugin, clientManager, donationManager, _inventoryManager, _mountManager, petManager, preferences, disguiseManager, blockRestore, new ProjectileManager(plugin)); _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); new CosmeticManager(_plugin, clientManager, donationManager, _inventoryManager, _gadgetManager, _mountManager, petManager, false, _treasureManager);
_partyManager = partyManager; _partyManager = partyManager;

View File

@ -400,9 +400,11 @@ public class ParkourManager extends MiniPlugin
{ {
for (Iterator<Block> iterator = event.getBlocks().iterator(); iterator.hasNext();) for (Iterator<Block> iterator = event.getBlocks().iterator(); iterator.hasNext();)
{ {
Block block = iterator.next();
for (ParkourData data : _parkour) for (ParkourData data : _parkour)
{ {
if (data.InBoundary(iterator.next().getLocation())) if (data.InBoundary(block.getLocation()))
{ {
iterator.remove(); iterator.remove();
break; break;

View File

@ -85,7 +85,7 @@ public class PollManager extends MiniClientPlugin<PlayerPollData>
if (event.getType() != UpdateType.SLOW) if (event.getType() != UpdateType.SLOW)
return; return;
if (_polls.size() == 0) if (_polls == null || _polls.size() == 0)
return; return;
for (Player player : _plugin.getServer().getOnlinePlayers()) for (Player player : _plugin.getServer().getOnlinePlayers())

View File

@ -185,9 +185,9 @@ public class ServerNpcPage extends ShopPageBase<ServerManager, ServerNpcShop> im
int greenStartSlot = 18 + ((9 - serversToShow) / 2); int greenStartSlot = 18 + ((9 - serversToShow) / 2);
boolean showGreen = true; 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 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); long portalTime = Plugin.getMillisecondsUntilPortal(Player, beta);
if (portalTime > 0) if (portalTime > 0)

View File

@ -6,5 +6,8 @@
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.Core.Common"/> <classpathentry combineaccessrules="false" kind="src" path="/Mineplex.Core.Common"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpclient-4.2.jar"/> <classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpclient-4.2.jar"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpcore-4.2.jar"/> <classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpcore-4.2.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.ServerData"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/jedis-2.4.2.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.Core"/>
<classpathentry kind="output" path="bin"/> <classpathentry kind="output" path="bin"/>
</classpath> </classpath>

View File

@ -1,29 +0,0 @@
package mineplex.queuer;
import java.util.Comparator;
import repository.PlayerMatchStatus;
public class EloPlayerSorter implements Comparator<PlayerMatchStatus>
{
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;
}
}

View File

@ -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<QueueParty> _parties;
public Set<QueueParty> 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();
}
}
}

View File

@ -1,42 +0,0 @@
package mineplex.queuer;
import java.util.Collection;
import java.util.HashMap;
import repository.PlayerMatchStatus;
public class PlayerMatch
{
private HashMap<Integer, PlayerMatchStatus> _players = new HashMap<Integer, PlayerMatchStatus>();
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<PlayerMatchStatus> getPlayerRecords()
{
return _players.values();
}
}

View File

@ -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<String> _players;
public Set<String> 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<String> _otherPartyStates;
public Set<String> getOtherPartyStates() { return _otherPartyStates; }
public void setOtherPartyStates(Set<String> 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<String>();
this._otherPartyStates = new HashSet<String>();
this._queueStartTime = System.currentTimeMillis();
}
public QueueParty(Collection<String> 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);
}
}

View File

@ -0,0 +1,21 @@
package mineplex.queuer;
import java.util.Comparator;
public class QueuePartySorter implements Comparator<QueueParty>
{
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;
}
}

View File

@ -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<QueueParty> _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<QueueParty>(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<String> 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<QueueParty> getQueueParties()
{
return _partyRepository.getElements();
}
public Collection<QueueParty> getJoinedQueueParties(int matchId)
{
Collection<QueueParty> queueParties = new HashSet<QueueParty>();
for (QueueParty queueParty : getQueueParties())
{
if (queueParty.getAssignedMatch() == matchId)
{
queueParties.add(queueParty);
}
}
return queueParties;
}
public Map<Integer, QueueParty> getMappedQueueParties()
{
Map<Integer, QueueParty> queueParties = new HashMap<Integer, QueueParty>();
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<MinecraftServer> 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);
}
}
}

View File

@ -2,29 +2,32 @@ package mineplex.queuer;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set;
import repository.PlayerMatchStatus; import mineplex.serverdata.Region;
import repository.Repository;
public class Queuer public class Queuer
{ {
private static Repository _repository = new Repository(); private static QueueRepository _repo;
public static void main (String args[]) 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<Integer, Integer> playerVarianceMap = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> playerVarianceMap = new HashMap<Integer, Integer>();
HashMap<Integer, PlayerMatch> playerPrepMatchMap = new HashMap<Integer, PlayerMatch>(); HashMap<Integer, Match> playerPrepMatchMap = new HashMap<Integer, Match>();
List<PlayerMatch> matchList = new ArrayList<PlayerMatch>(); Set<Match> matches = new HashSet<Match>();
EloPlayerSorter playerSorter = new EloPlayerSorter(1250); QueuePartySorter partySorter = new QueuePartySorter();
int matchId = 1; int matchId = 1;
@ -34,135 +37,132 @@ public class Queuer
matchId %= 1500; matchId %= 1500;
List<Integer> assignedMatchIdChecked = new ArrayList<Integer>(); List<Integer> assignedMatchIdChecked = new ArrayList<Integer>();
HashMap<Integer, PlayerMatchStatus> queueRecords = _repository.retrieveQueuedRecords(); Map<Integer, QueueParty> queueParties = _repo.getMappedQueueParties();
int matchPlayerCount = 2; int matchPlayerCount = 2;
System.out.println("Checking " + queueRecords.size() + " queues..."); System.out.println("Checking " + queueParties.size() + " queues...");
for (PlayerMatchStatus queueRecord : queueRecords.values()) 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 (queueParty.hasAssignedMatch())
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)
{ {
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; break;
playerPrepMatchMap.get(keyId).removePlayerRecord(queueRecord); playerPrepMatchMap.get(partyId).quitQueueParty(queueParty);
} }
match.addPlayerRecord(queueRecord); match.joinQueueParty(queueParty);
playerPrepMatchMap.put(keyId, match); playerPrepMatchMap.put(partyId, match);
System.out.println("Found prep match for '" + queueRecord.Id + "'");
log("Found prep match for '" + queueParty.getId() + "'");
break; break;
} }
} }
if (!playerPrepMatchMap.containsKey(keyId)) if (!playerPrepMatchMap.containsKey(partyId))
{ {
PlayerMatch match = new PlayerMatch(); Match match = new Match(matchId++, queueParty.getAverageElo(), queueParty);
match.Elo = queueRecord.Elo;
match.MatchId = matchId;
match.addPlayerRecord(queueRecord);
playerPrepMatchMap.put(keyId, match); playerPrepMatchMap.put(partyId, match);
matchList.add(match); matches.add(match);
matchId++;
} }
} }
else if (!assignedMatchIdChecked.contains(queueRecord.AssignedMatch)) else if (!assignedMatchIdChecked.contains(queueParty.getAssignedMatch()))
{ {
System.out.println("Checking if match '" + queueRecord.AssignedMatch + "' is ready."); int assignedMatchId = queueParty.getAssignedMatch();
List<String> matchStatuses = _repository.getMatchStatuses(queueRecord.AssignedMatch); log("Checking if match '" + assignedMatchId + "' is ready.");
//List<String> matchStatuses = _repo.getMatchStatuses(queueRecord.AssignedMatch);
Collection<QueueParty> joinedParties = _repo.getJoinedQueueParties(assignedMatchId);
boolean matchReady = true; boolean matchReady = true;
boolean matchDeny = false; 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; matchDeny = true;
matchReady = false; matchReady = false;
break; break;
} }
else if (!matchStatus.equalsIgnoreCase("Ready")) else if (!partyState.equalsIgnoreCase("Ready"))
{
matchReady = false; matchReady = false;
} }
}
if (matchReady) if (matchReady)
{ {
_repository.startMatch(queueRecord.AssignedMatch); _repo.startMatch(assignedMatchId);
_repository.deleteQueuesByAssignedMatch(queueRecord.AssignedMatch); _repo.deleteAssignedParties(assignedMatchId);
System.out.println("Starting match '" + queueRecord.AssignedMatch + "'"); System.out.println("Starting match '" + assignedMatchId + "'");
} }
else if (matchDeny) 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 // Check for and kick off invites for ready matches
for (Iterator<PlayerMatch> matchIterator = matchList.iterator(); matchIterator.hasNext();) for (Iterator<Match> 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. // Don't give me crap about not using iterator...can't cuz of stupid thing.
List<PlayerMatchStatus> matchStatusesToRemove = new ArrayList<PlayerMatchStatus>(); Set<QueueParty> partiesToRemove = new HashSet<QueueParty>();
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); log("Removing matchStatus : " + queueParty.getId());
matchStatusesToRemove.add(matchStatus); partiesToRemove.add(queueParty);
if (match.WaitingForInvites) if (match.isWaitingForInvites())
{ {
_repository.removeAssignedMatch(match.MatchId); _repo.deleteMatch(match.getId());
match.WaitingForInvites = false; 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")) if (!queueParty.getState().equalsIgnoreCase("Ready"))
_repository.deleteQueuesById(matchStatus.Id); {
_repo.deleteQueueParty(queueParty.getId());
} }
_repository.removeAssignedMatch(match.MatchId); }
match.WaitingForInvites = false;
_repo.deleteMatch(match.getId());
match.setWaitingForInvites(false);
} }
continue; continue;
@ -170,51 +170,42 @@ public class Queuer
if (match.getPlayerCount() >= matchPlayerCount) if (match.getPlayerCount() >= matchPlayerCount)
{ {
playerSorter.EloMark = match.Elo; List<QueueParty> partyList = new ArrayList<QueueParty>(match.getParties());
Collections.sort(partyList, partySorter);
List<PlayerMatchStatus> playerList = new ArrayList<PlayerMatchStatus>();
playerList.addAll(match.getPlayerRecords());
Collections.sort(playerList, playerSorter);
int playerCount = 0; int playerCount = 0;
for (QueueParty party : partyList)
for (int i = 0; i < playerList.size(); i++)
{ {
PlayerMatchStatus player = playerList.get(i); if (playerCount + party.getPlayerCount() > matchPlayerCount)
if (playerCount + player.PlayerCount > matchPlayerCount)
{ {
match.removePlayerRecord(player); match.quitQueueParty(party);
playerPrepMatchMap.remove(player.Id); playerPrepMatchMap.remove(party.getId());
log("Oops hit player cap, can't fit you in this match.");
System.out.println("Oops hit player cap, can't fit you in this match.");
continue; continue;
} }
playerCount += player.PlayerCount; playerCount += party.getPlayerCount();
} }
if (playerCount == matchPlayerCount) 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); playerPrepMatchMap.remove(party.getId());
_repository.assignMatch(player.Id, match.MatchId); _repo.assignMatch(party, match);
} }
match.WaitingForInvites = true; match.setWaitingForInvites(true);
match.WaitingStarted = System.currentTimeMillis(); matchesMade++;
matchesMade += 1;
} }
} }
else if (match.getPlayerCount() == 0) else if (match.getPlayerCount() == 0)
{
matchIterator.remove(); matchIterator.remove();
} }
}
_repository.clearOldServerTransfers();
try try
{ {
@ -228,5 +219,12 @@ public class Queuer
e.printStackTrace(); e.printStackTrace();
} }
} }
}
private static void log(String message)
{
System.out.println(message);
} }
} }

View File

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

View File

@ -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<Integer, PlayerMatchStatus> retrieveQueuedRecords()
{
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
HashMap<Integer, PlayerMatchStatus> queueRecords = new HashMap<Integer, PlayerMatchStatus>();
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<String> getMatchStatuses(int assignedMatch)
{
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
List<String> matchStatuses = new ArrayList<String>();
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();
}
}
}
}
}

View File

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

View File

@ -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 <T> - the type of {@link Data} object stored in this repository.
*/
public interface DataRepository<T extends Data>
{
public Collection<T> 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();
}

View File

@ -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<T extends Data> implements DataRepository<T>
{
// 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<T> elementType;
private String elementLabel;
/**
* Class constructor
* @param host
* @param port
* @param region
*/
public RedisDataRepository(String host, int port, Region region,
Class<T> 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<T> 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<T> getElements()
{
Collection<T> elements = new HashSet<T>();
Jedis jedis = _jedisPool.getResource();
try
{
Pipeline pipeline = jedis.pipelined();
List<Response<String>> responses = new ArrayList<Response<String>>();
for (String dataId : getActiveElements())
{
responses.add(pipeline.get(generateKey(dataId)));
}
pipeline.sync();
for (Response<String> 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<String> getActiveElements()
{
Set<String> dataIds = new HashSet<String>();
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<String> getDeadElements()
{
Set<String> dataIds = new HashSet<String>();
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);
}
}

View File

@ -17,6 +17,9 @@ import redis.clients.jedis.Transaction;
import redis.clients.jedis.Tuple; import redis.clients.jedis.Tuple;
import redis.clients.jedis.exceptions.JedisConnectionException; 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} * RedisServerRepository offers a Redis-based implementation of {@link ServerRepository}
* using a mixture of hash and JSON encoded storage. * using a mixture of hash and JSON encoded storage.
@ -69,12 +72,7 @@ public class RedisServerRepository implements ServerRepository
for (Response<String> response : responses) for (Response<String> response : responses)
{ {
String serializedData = response.get(); String serializedData = response.get();
MinecraftServer server = Utility.deserialize(serializedData, MinecraftServer.class); servers.add(Utility.deserialize(serializedData, MinecraftServer.class));
if (server != null)
{
servers.add(server);
}
} }
} }
catch (JedisConnectionException exception) catch (JedisConnectionException exception)
@ -94,6 +92,22 @@ public class RedisServerRepository implements ServerRepository
return servers; return servers;
} }
@Override
public Collection<MinecraftServer> getServersByGroup(String serverGroup)
{
Collection<MinecraftServer> servers = new HashSet<MinecraftServer>();
for (MinecraftServer server : getServerStatuses())
{
if (server.getGroup().equalsIgnoreCase(serverGroup))
{
servers.add(server);
}
}
return servers;
}
@Override @Override
public MinecraftServer getServerStatus(String serverName) public MinecraftServer getServerStatus(String serverName)
{ {
@ -135,7 +149,7 @@ public class RedisServerRepository implements ServerRepository
String serverName = serverData.getName(); String serverName = serverData.getName();
String setKey = concatenate("serverstatus", "minecraft", _region.toString()); String setKey = concatenate("serverstatus", "minecraft", _region.toString());
String dataKey = concatenate(setKey, serverName); String dataKey = concatenate(setKey, serverName);
long expiry = Long.parseLong(jedis.time().get(0)) + timeout; long expiry = Utility.currentTimeMillis() + timeout;
Transaction transaction = jedis.multi(); Transaction transaction = jedis.multi();
transaction.set(dataKey, serializedData); transaction.set(dataKey, serializedData);
@ -169,7 +183,7 @@ public class RedisServerRepository implements ServerRepository
String dataKey = concatenate(setKey, serverName); String dataKey = concatenate(setKey, serverName);
Transaction transaction = jedis.multi(); Transaction transaction = jedis.multi();
transaction.del(dataKey); transaction.set(dataKey, null);
transaction.zrem(setKey, serverName); transaction.zrem(setKey, serverName);
transaction.exec(); transaction.exec();
} }
@ -253,7 +267,7 @@ public class RedisServerRepository implements ServerRepository
{ {
for (MinecraftServer minecraftServer : getServerStatuses()) 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()); ServerGroup serverGroup = serverGroups.get(minecraftServer.getGroup());
server.incrementServerCount(serverGroup); server.incrementServerCount(serverGroup);
@ -311,7 +325,7 @@ public class RedisServerRepository implements ServerRepository
try try
{ {
String min = "(" + jedis.time().get(0); String min = "(" + Utility.currentTimeMillis();
String max = "+inf"; String max = "+inf";
names = jedis.zrangeByScore(key, min, max); names = jedis.zrangeByScore(key, min, max);
} }
@ -332,6 +346,38 @@ public class RedisServerRepository implements ServerRepository
return names; 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<String> getDeadNames(String key)
{
Set<String> names = new HashSet<String>();
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 * @param elements - the elements to concatenate together
* @return the concatenated form of all {@code elements} * @return the concatenated form of all {@code elements}

View File

@ -10,4 +10,5 @@ public enum Region
{ {
US, US,
EU, EU,
ALL;
} }

View File

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

View File

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

View File

@ -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<String, Class<? extends ServerCommand>> 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<String, Class<? extends ServerCommand>>();
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<? extends ServerCommand> 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;
}
}

View File

@ -51,13 +51,13 @@ public class ServerGroup
public boolean getArcadeGroup() { return _arcadeGroup; } public boolean getArcadeGroup() { return _arcadeGroup; }
private String _worldZip; private String _worldZip;
public String getWorldZip() { return _serverType; } public String getWorldZip() { return _worldZip; }
private String _plugin; private String _plugin;
public String getPlugin() { return _serverType; } public String getPlugin() { return _plugin; }
private String _configPath; private String _configPath;
public String getConfigPath() { return _serverType; } public String getConfigPath() { return _configPath; }
private int _minPlayers; private int _minPlayers;
public int getMinPlayers() { return _minPlayers; } public int getMinPlayers() { return _minPlayers; }
@ -71,6 +71,42 @@ public class ServerGroup
private boolean _tournament; private boolean _tournament;
public boolean getTournament() { return _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; private boolean _generateFreeVersions;
public boolean getGenerateFreeVersions() { return _generateFreeVersions; } public boolean getGenerateFreeVersions() { return _generateFreeVersions; }
@ -84,7 +120,8 @@ public class ServerGroup
public boolean getAddNoCheat() { return _addNoCheat; } public boolean getAddNoCheat() { return _addNoCheat; }
// The set of active MinecraftServers that belong to this server group // The set of active MinecraftServers that belong to this server group
private Set<MinecraftServer> servers; private Set<MinecraftServer> _servers;
public Set<MinecraftServer> getServers() { return _servers; }
/** /**
* Class constructor * Class constructor
@ -94,26 +131,38 @@ public class ServerGroup
*/ */
public ServerGroup(Map<String, String> data, Region region) public ServerGroup(Map<String, String> data, Region region)
{ {
this._name = data.get("name"); _name = data.get("name");
this._prefix = data.get("prefix"); _prefix = data.get("prefix");
this._scriptName = data.get("scriptName"); _scriptName = data.get("scriptName");
this._requiredRam = Integer.valueOf(data.get("ram")); _requiredRam = Integer.valueOf(data.get("ram"));
this._requiredCpu = Integer.valueOf(data.get("cpu")); _requiredCpu = Integer.valueOf(data.get("cpu"));
this._requiredTotalServers = Integer.valueOf(data.get("totalServers")); _requiredTotalServers = Integer.valueOf(data.get("totalServers"));
this._requiredJoinableServers = Integer.valueOf(data.get("joinableServers")); _requiredJoinableServers = Integer.valueOf(data.get("joinableServers"));
this._portSection = Integer.valueOf(data.get("portSection")); _portSection = Integer.valueOf(data.get("portSection"));
this._arcadeGroup = Boolean.valueOf(data.get("arcadeGroup")); _arcadeGroup = Boolean.valueOf(data.get("arcadeGroup"));
this._worldZip = data.get("worldZip"); _worldZip = data.get("worldZip");
this._plugin = data.get("plugin"); _plugin = data.get("plugin");
this._configPath = data.get("configPath"); _configPath = data.get("configPath");
this._minPlayers = Integer.valueOf(data.get("minPlayers")); _minPlayers = Integer.valueOf(data.get("minPlayers"));
this._maxPlayers = Integer.valueOf(data.get("maxPlayers")); _maxPlayers = Integer.valueOf(data.get("maxPlayers"));
this._pvp = Boolean.valueOf(data.get("pvp")); _pvp = Boolean.valueOf(data.get("pvp"));
this._tournament = Boolean.valueOf(data.get("tournament")); _tournament = Boolean.valueOf(data.get("tournament"));
this._generateFreeVersions = Boolean.valueOf(data.get("generateFreeVersions")); _generateFreeVersions = Boolean.valueOf(data.get("generateFreeVersions"));
this._games = data.get("games"); _games = data.get("games");
this._serverType = data.get("serverType"); _serverType = data.get("serverType");
this._addNoCheat = Boolean.valueOf(data.get("addNoCheat")); _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); fetchServers(region);
} }
@ -124,7 +173,7 @@ public class ServerGroup
*/ */
public int getServerCount() public int getServerCount()
{ {
return servers.size(); return _servers.size();
} }
/** /**
@ -135,7 +184,7 @@ public class ServerGroup
{ {
int joinable = 0; int joinable = 0;
for (MinecraftServer server : servers) for (MinecraftServer server : _servers)
{ {
if (server.isJoinable()) if (server.isJoinable())
{ {
@ -154,7 +203,7 @@ public class ServerGroup
{ {
int playerCount = 0; int playerCount = 0;
for (MinecraftServer server : servers) for (MinecraftServer server : _servers)
{ {
playerCount += server.getPlayerCount(); playerCount += server.getPlayerCount();
} }
@ -170,7 +219,7 @@ public class ServerGroup
{ {
int maxPlayerCount = 0; int maxPlayerCount = 0;
for (MinecraftServer server : servers) for (MinecraftServer server : _servers)
{ {
maxPlayerCount += server.getMaxPlayerCount(); maxPlayerCount += server.getMaxPlayerCount();
} }
@ -186,7 +235,7 @@ public class ServerGroup
{ {
Collection<MinecraftServer> emptyServers = new HashSet<MinecraftServer>(); Collection<MinecraftServer> emptyServers = new HashSet<MinecraftServer>();
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 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) private void fetchServers(Region region)
{ {
this.servers = new HashSet<MinecraftServer>(); this._servers = new HashSet<MinecraftServer>();
ServerRepository repository = ServerManager.getServerRepository(region); ServerRepository repository = ServerManager.getServerRepository(region);
for (MinecraftServer server : repository.getServerStatuses()) 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. * @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) while (true)
{ {
boolean uniqueId = true; boolean uniqueId = true;
for (MinecraftServer server : servers) for (MinecraftServer server : _servers)
{ {
String serverName = server.getName(); String serverName = server.getName();
try try
@ -255,5 +304,4 @@ public class ServerGroup
} }
} }
} }
} }

View File

@ -1,7 +1,6 @@
package mineplex.serverdata; package mineplex.serverdata;
import java.util.Collection; import java.util.Collection;
import java.util.Set;
/** /**
* The ServerRepository is used for storing/retrieving active sessions * The ServerRepository is used for storing/retrieving active sessions
@ -19,6 +18,8 @@ public interface ServerRepository
*/ */
public Collection<MinecraftServer> getServerStatuses(); public Collection<MinecraftServer> getServerStatuses();
public Collection<MinecraftServer> getServersByGroup(String serverGroup);
/** /**
* @param serverName - the name of the {@link MinecraftServer} to be fetched. * @param serverName - the name of the {@link MinecraftServer} to be fetched.
* @return the currently active {@link MinecraftServer} with a matching {@code serverName}, * @return the currently active {@link MinecraftServer} with a matching {@code serverName},
@ -62,5 +63,6 @@ public interface ServerRepository
*/ */
public Collection<ServerGroup> getServerGroups(); public Collection<ServerGroup> getServerGroups();
Collection<MinecraftServer> getDeadServers(); public Collection<MinecraftServer> getDeadServers();
} }

View File

@ -1,5 +1,9 @@
package mineplex.serverdata; 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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -15,6 +19,9 @@ public class Utility
private static Gson _gson = new GsonBuilder().create(); private static Gson _gson = new GsonBuilder().create();
public static Gson getGson() { return _gson; } 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 * @param object - the (non-null) object to serialize
* @return the serialized form of {@code object}. * @return the serialized form of {@code object}.
@ -51,4 +58,36 @@ public class Utility
return result; 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;
}
} }

View File

@ -6,7 +6,6 @@ import mineplex.core.command.CommandCenter;
import mineplex.core.creature.Creature; import mineplex.core.creature.Creature;
import mineplex.core.donation.DonationManager; import mineplex.core.donation.DonationManager;
import mineplex.core.inventory.InventoryManager; import mineplex.core.inventory.InventoryManager;
import mineplex.core.join.JoinQuit;
import mineplex.core.memory.MemoryFix; import mineplex.core.memory.MemoryFix;
import mineplex.core.monitor.LagMeter; import mineplex.core.monitor.LagMeter;
import mineplex.core.npc.NpcManager; import mineplex.core.npc.NpcManager;

View File

@ -19,6 +19,7 @@ import mineplex.core.MiniPlugin;
import mineplex.core.account.CoreClient; import mineplex.core.account.CoreClient;
import mineplex.core.account.CoreClientManager; import mineplex.core.account.CoreClientManager;
import mineplex.core.common.Rank; import mineplex.core.common.Rank;
import mineplex.core.common.jsonchat.JsonMessage;
import mineplex.core.common.util.C; import mineplex.core.common.util.C;
import mineplex.core.common.util.F; import mineplex.core.common.util.F;
import mineplex.core.common.util.NautHashMap; import mineplex.core.common.util.NautHashMap;
@ -99,21 +100,49 @@ public class CustomerSupport extends MiniPlugin
caller.sendMessage(C.cDGreen + C.Strike + "============================================="); caller.sendMessage(C.cDGreen + C.Strike + "=============================================");
caller.sendMessage(C.cBlue + "Name : " + C.cYellow + playerName); 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 + "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()) for (CoinTransactionToken transaction : donor.getCoinTransactions())
{ {
if (transaction.Source.equalsIgnoreCase("Poll") || transaction.Source.equalsIgnoreCase("Coin Party Bomb Pickup") || transaction.Source.contains("Reward")) if (transaction.Source.equalsIgnoreCase("Poll") || transaction.Source.equalsIgnoreCase("Coin Party Bomb Pickup") || transaction.Source.contains("Reward") || transaction.Source.contains("purchase"))
continue; {
coinTransactionTotal += transaction.Amount;
caller.sendMessage(C.cYellow + _date.format(transaction.Date) + C.cGray + " - " + C.cYellow + transaction.Amount + " Coins - Applied via " + transaction.Source); if (transaction.Source.contains("purchase"))
enjinCoinsReceived += transaction.Amount;
}
} }
for (TransactionToken transaction : donor.getTransactions()) for (TransactionToken transaction : donor.getTransactions())
{ {
if (transaction.Coins == 0 && transaction.Gems == 0 && transaction.SalesPackageName.contains("Gem Booster")) coinSpentTotal += transaction.Coins;
caller.sendMessage(C.cYellow + _date.format(transaction.Date) + C.cGray + " - " + C.cYellow + transaction.SalesPackageName);
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 + "============================================="); caller.sendMessage(C.cDGreen + C.Strike + "=============================================");
_salesPackageManager.displaySalesPackages(caller, playerName); _salesPackageManager.displaySalesPackages(caller, playerName);
caller.sendMessage(C.cDGreen + C.Strike + "============================================="); caller.sendMessage(C.cDGreen + C.Strike + "=============================================");

View File

@ -95,6 +95,7 @@ import nautilus.game.arcade.managers.GameLobbyManager;
import nautilus.game.arcade.managers.GameLootManager; import nautilus.game.arcade.managers.GameLootManager;
import nautilus.game.arcade.managers.GameManager; import nautilus.game.arcade.managers.GameManager;
import nautilus.game.arcade.managers.GamePlayerManager; import nautilus.game.arcade.managers.GamePlayerManager;
import nautilus.game.arcade.managers.GameStatManager;
import nautilus.game.arcade.managers.GameWorldManager; import nautilus.game.arcade.managers.GameWorldManager;
import nautilus.game.arcade.managers.IdleManager; import nautilus.game.arcade.managers.IdleManager;
import nautilus.game.arcade.managers.MiscManager; import nautilus.game.arcade.managers.MiscManager;
@ -246,6 +247,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
new GameFlagManager(this); new GameFlagManager(this);
_gamePlayerManager = new GamePlayerManager(this); _gamePlayerManager = new GamePlayerManager(this);
new GameAchievementManager(this); new GameAchievementManager(this);
new GameStatManager(this);
new GameLootManager(this, petManager); new GameLootManager(this, petManager);
_gameWorldManager = new GameWorldManager(this); _gameWorldManager = new GameWorldManager(this);
new MiscManager(this); new MiscManager(this);
@ -1000,6 +1002,9 @@ public class ArcadeManager extends MiniPlugin implements IRelation
public void saveBasicStats(final Game game) public void saveBasicStats(final Game game)
{ {
if (!IsTournamentServer())
return;
final Map<UUID, Boolean> data = new HashMap<>(); final Map<UUID, Boolean> data = new HashMap<>();
for (Player loser : game.getLosers()) for (Player loser : game.getLosers())

View File

@ -95,6 +95,5 @@ public class TeamArmorAddon extends MiniPlugin
event.setCancelled(true); event.setCancelled(true);
event.getWhoClicked().closeInventory(); event.getWhoClicked().closeInventory();
System.out.println(this.getClass().getName() + " 103");
} }
} }

View File

@ -926,7 +926,8 @@ public abstract class Game implements Listener
if (!IsLive()) if (!IsLive())
return; return;
String winnerText = ChatColor.WHITE + "§lNobody won the game..."; String winnerText = ChatColor.WHITE + "Nobody";
ChatColor subColor = ChatColor.WHITE;
for (Player player : UtilServer.getPlayers()) for (Player player : UtilServer.getPlayers())
{ {
@ -944,12 +945,14 @@ public abstract class Game implements Listener
WinnerTeam = team; WinnerTeam = team;
Winner = team.GetName() + " Team"; Winner = team.GetName() + " Team";
winnerText = team.GetColor() + C.Bold + team.GetName() + " won the game!"; winnerText = team.GetColor() + team.GetName();
UtilPlayer.message(player, winnerText); subColor = team.GetColor();
UtilPlayer.message(player, team.GetColor() + C.Bold + team.GetName() + " won the game!");
} }
else 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); UtilPlayer.message(player, ArcadeFormat.Line);
} }
UtilTitle.display(winnerText, _customWinLine, 20, 120, 20); UtilTitle.display(winnerText, subColor + "won the game", 20, 120, 20);
if (AnnounceSilence) if (AnnounceSilence)
Manager.GetChat().Silence(5000, false); Manager.GetChat().Silence(5000, false);
@ -969,6 +972,7 @@ public abstract class Game implements Listener
public void AnnounceEnd(List<Player> places) public void AnnounceEnd(List<Player> places)
{ {
String winnerText = ChatColor.WHITE + "§lNobody won the game..."; String winnerText = ChatColor.WHITE + "§lNobody won the game...";
ChatColor subColor = ChatColor.WHITE;
for (Player player : UtilServer.getPlayers()) for (Player player : UtilServer.getPlayers())
{ {
@ -992,7 +996,8 @@ public abstract class Game implements Listener
{ {
Winner = places.get(0).getName(); 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()); 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); UtilPlayer.message(player, ArcadeFormat.Line);
} }
UtilTitle.display(winnerText, null, 20, 120, 20); UtilTitle.display(winnerText, subColor + "won the game", 20, 120, 20);
if (AnnounceSilence) if (AnnounceSilence)
Manager.GetChat().Silence(5000, false); 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<StatTracker<? extends Game>> getStatTrackers() public Collection<StatTracker<? extends Game>> getStatTrackers()
{ {

View File

@ -74,7 +74,6 @@ public class ChampionsDominate extends Domination
{ {
SetKit(player, GetKits()[2], true); SetKit(player, GetKits()[2], true);
player.closeInventory(); player.closeInventory();
System.out.println(this.getClass().getName() + " 64");
} }
} }

View File

@ -74,7 +74,6 @@ public class ChampionsTDM extends TeamDeathmatch
{ {
SetKit(player, GetKits()[2], true); SetKit(player, GetKits()[2], true);
player.closeInventory(); player.closeInventory();
System.out.println(this.getClass().getName() + " 61");
} }
} }

View File

@ -164,7 +164,6 @@ public class TeamDeathmatch extends TeamGame
{ {
SetKit(player, GetKits()[2], true); SetKit(player, GetKits()[2], true);
player.closeInventory(); player.closeInventory();
System.out.println(this.getClass().getName() + " 167");
} }
} }

View File

@ -1175,8 +1175,6 @@ public class MineStrike extends TeamGame
public int getArrowHitArea(Player damagee, Location origin, Vector trajectory) public int getArrowHitArea(Player damagee, Location origin, Vector trajectory)
{ {
System.out.println("Getting Area");
//Move to near-player //Move to near-player
Location start = origin.clone().add(trajectory.clone().multiply(UtilMath.offset(origin, damagee.getEyeLocation()) - 2)); 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)) if (hitHead(damagee, loc))
{ {
System.out.println("Head");
return 1; return 1;
} }
if (hitBody(damagee, loc)) if (hitBody(damagee, loc))
{ {
System.out.println("Body");
return 0; return 0;
} }
System.out.println("Miss");
return -1; return -1;
} }
@ -1217,12 +1211,12 @@ public class MineStrike extends TeamGame
loc.add(snowball.getVelocity().clone().multiply(0.1)); loc.add(snowball.getVelocity().clone().multiply(0.1));
} }
if (hitHead(damagee, loc))
return 1;
if (hitBody(damagee, loc)) if (hitBody(damagee, loc))
return 0; return 0;
if (hitHead(damagee, loc))
return 1;
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 return UtilMath.offset2d(loc, player.getLocation()) < 0.6 && //0.6 is ideal
loc.getY() > player.getLocation().getY() && 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) public boolean hitHead(Player player, Location loc)
{ {
return UtilMath.offset2d(loc, player.getLocation()) < 0.3 && //0.3 is ideal 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; loc.getY() < player.getEyeLocation().getY() + 0.2;
} }
@ -1399,7 +1393,7 @@ public class MineStrike extends TeamGame
if (_bombPlanter == null) if (_bombPlanter == null)
return; return;
if (!_bombPlanter.isBlocking()) if (!_bombPlanter.isBlocking() || !_bombPlanter.isOnline())
{ {
_bombPlanter.setExp(0f); _bombPlanter.setExp(0f);
UtilTitle.clear(_bombPlanter); UtilTitle.clear(_bombPlanter);
@ -1508,7 +1502,7 @@ public class MineStrike extends TeamGame
Block block = _bombDefuser.getTargetBlock(null, 5); 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.setExp(0f);
_bombDefuser = null; _bombDefuser = null;

View File

@ -473,14 +473,12 @@ public class Paintball extends TeamGame
for (ItemStack stack : player.getEquipment().getArmorContents()) for (ItemStack stack : player.getEquipment().getArmorContents())
{ {
System.out.println("Type:" + stack.getType() + " Meta:" + stack.getItemMeta());
if (!(stack.getItemMeta() instanceof LeatherArmorMeta)) if (!(stack.getItemMeta() instanceof LeatherArmorMeta))
continue; continue;
LeatherArmorMeta meta = (LeatherArmorMeta)stack.getItemMeta(); LeatherArmorMeta meta = (LeatherArmorMeta)stack.getItemMeta();
meta.setColor(color); meta.setColor(color);
stack.setItemMeta(meta); stack.setItemMeta(meta);
System.out.println("Changed leather meta for " + player.getName());
} }
} }
} }

View File

@ -65,7 +65,5 @@ public class KitRifle extends Kit
metaBoots.setColor(Color.WHITE); metaBoots.setColor(Color.WHITE);
boots.setItemMeta(metaBoots); boots.setItemMeta(metaBoots);
player.getInventory().setBoots(boots); player.getInventory().setBoots(boots);
System.out.println("Game kit items to " + player.getName());
} }
} }

View File

@ -292,7 +292,6 @@ public class GameFlagManager implements Listener
{ {
event.setCancelled(true); event.setCancelled(true);
event.getWhoClicked().closeInventory(); event.getWhoClicked().closeInventory();
System.out.println(this.getClass().getName() + " 267");
} }
} }

View File

@ -1194,7 +1194,6 @@ public class GameLobbyManager implements Listener, IPacketHandler
{ {
event.setCancelled(true); event.setCancelled(true);
event.getWhoClicked().closeInventory(); event.getWhoClicked().closeInventory();
System.out.println(this.getClass().getName() + " 1150");
} }
} }

View File

@ -7,6 +7,7 @@ import org.bukkit.Bukkit;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.FireworkEffect; import org.bukkit.FireworkEffect;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; 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.C;
import mineplex.core.common.util.F; import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilFirework; import mineplex.core.common.util.UtilFirework;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilTitle; import mineplex.core.common.util.UtilTitle;
import mineplex.core.pet.PetManager; import mineplex.core.pet.PetManager;
@ -55,11 +57,11 @@ public class GameLootManager implements Listener
//Chest //Chest
_rewardManager.addReward(new InventoryReward(_rewardManager, Manager.getInventoryManager(), "Treasure Chest", "Treasure Chest", 1, 1, _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 //Key
_rewardManager.addReward(new InventoryReward(_rewardManager, Manager.getInventoryManager(), "Treasure Key", "Treasure Key", 1, 1, _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 @EventHandler
@ -120,18 +122,24 @@ public class GameLootManager implements Listener
String outputName = reward.getRarity().getColor() + rewardData.getFriendlyName(); String outputName = reward.getRarity().getColor() + rewardData.getFriendlyName();
String rarityName = "";
if (reward.getRarity() != RewardRarity.COMMON)
rarityName = " " + reward.getRarity().getColor() + reward.getRarity().getName();
//Log //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 //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(); Random _random = new Random();
//Announce //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 //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(); FireworkEffect effect = FireworkEffect.builder().with(FireworkEffect.Type.BALL).withColor(Color.YELLOW).withFade(Color.WHITE).build();
UtilFirework.playFirework(player.getEyeLocation(), effect); 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) else if (reward.getRarity() == RewardRarity.LEGENDARY)
{ {
FireworkEffect effect = FireworkEffect.builder().with(FireworkEffect.Type.BALL_LARGE).withColor(Color.RED).withFade(Color.BLACK).build(); FireworkEffect effect = FireworkEffect.builder().with(FireworkEffect.Type.BALL_LARGE).withColor(Color.RED).withFade(Color.BLACK).build();
UtilFirework.playFirework(player.getEyeLocation(), effect); 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()); giveReward(event.getPlayer());
event.setCancelled(true); 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);
}
} }
} }

View File

@ -26,6 +26,7 @@ import nautilus.game.arcade.game.Game;
import nautilus.game.arcade.game.GameTeam; import nautilus.game.arcade.game.GameTeam;
import nautilus.game.arcade.game.Game.GameState; import nautilus.game.arcade.game.Game.GameState;
import nautilus.game.arcade.game.GameTeam.PlayerState; import nautilus.game.arcade.game.GameTeam.PlayerState;
import nautilus.game.arcade.stats.StatTracker;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Color; import org.bukkit.Color;
@ -36,6 +37,7 @@ import org.bukkit.FireworkEffect.Type;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
public class GameManager implements Listener public class GameManager implements Listener
@ -281,40 +283,7 @@ public class GameManager implements Listener
event.GetGame().deRegisterStats(); 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 @EventHandler
public void ScoreboardTitle(UpdateEvent event) public void ScoreboardTitle(UpdateEvent event)

View File

@ -26,10 +26,12 @@ import mineplex.core.common.util.C;
import mineplex.core.common.util.F; import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilPlayer;
import mineplex.core.donation.Donor; import mineplex.core.donation.Donor;
import mineplex.core.recharge.Recharge;
import mineplex.core.shop.page.ConfirmationPage; import mineplex.core.shop.page.ConfirmationPage;
import mineplex.minecraft.game.core.combat.event.CombatDeathEvent; import mineplex.minecraft.game.core.combat.event.CombatDeathEvent;
import mineplex.minecraft.game.core.damage.CustomDamageEvent; import mineplex.minecraft.game.core.damage.CustomDamageEvent;
import nautilus.game.arcade.ArcadeManager; import nautilus.game.arcade.ArcadeManager;
import nautilus.game.arcade.events.PlayerStateChangeEvent;
import nautilus.game.arcade.game.Game; import nautilus.game.arcade.game.Game;
import nautilus.game.arcade.game.Game.GameState; import nautilus.game.arcade.game.Game.GameState;
import nautilus.game.arcade.game.GameTeam; 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 @EventHandler
public void InventoryClick(InventoryClickEvent event) public void InventoryClick(InventoryClickEvent event)
{ {

View File

@ -5,6 +5,7 @@ import java.util.List;
import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilServer;
import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType; import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent; import mineplex.core.updater.event.UpdateEvent;
import nautilus.game.arcade.ArcadeManager; import nautilus.game.arcade.ArcadeManager;
@ -148,6 +149,9 @@ public class MiscManager implements Listener
if (player.getItemInHand().getType() != Material.WATCH) if (player.getItemInHand().getType() != Material.WATCH)
return; return;
if (!Recharge.Instance.usable(event.getPlayer(), "Return to Hub"))
return;
Manager.GetPortal().SendPlayerToServer(player, "Lobby"); Manager.GetPortal().SendPlayerToServer(player, "Lobby");
} }

View File

@ -52,7 +52,14 @@
const string PREFIX = "CommitChanges() failed because: "; const string PREFIX = "CommitChanges() failed because: ";
try try
{ {
Context.SaveChanges(); if (Context.SaveChanges() == 0)
Log("WARNING", "No entities to save: " + Environment.StackTrace);
/*
* List<Object> 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) catch (DbEntityValidationException ex)
{ {

View File

@ -559,17 +559,12 @@
if (rank == null) if (rank == null)
return account.Rank.ToString(); return account.Rank.ToString();
repository.Attach(account);
repository.Edit(account);
var expire = DateTime.Now.AddMonths(1).AddMilliseconds(-DateTime.Now.Millisecond); var expire = DateTime.Now.AddMonths(1).AddMilliseconds(-DateTime.Now.Millisecond);
account.Rank = rank; account.Rank = rank;
account.RankExpire = expire; account.RankExpire = expire;
account.RankPerm = token.Perm; account.RankPerm = token.Perm;
repository.CommitChanges();
repository.Edit(account); repository.Edit(account);
if ((rank.Name == "HERO" || rank.Name == "ULTRA") && token.Perm) if ((rank.Name == "HERO" || rank.Name == "ULTRA") && token.Perm)

View File

@ -21,11 +21,14 @@
{ {
using (var repository = _repositoryFactory.CreateRepository()) using (var repository = _repositoryFactory.CreateRepository())
{ {
bool added = false;
foreach (var item in petTokens.Where(item => !repository.Any<Pet>(x => x.PetType == item.PetType))) foreach (var item in petTokens.Where(item => !repository.Any<Pet>(x => x.PetType == item.PetType)))
{ {
repository.Add(item); repository.Add(item);
added = true;
} }
if (added)
repository.CommitChanges(); repository.CommitChanges();
return repository.GetAll<Pet>().Include(x => x.SalesPackage).ToList(); return repository.GetAll<Pet>().Include(x => x.SalesPackage).ToList();
@ -36,11 +39,14 @@
{ {
using (var repository = _repositoryFactory.CreateRepository()) using (var repository = _repositoryFactory.CreateRepository())
{ {
bool added = false;
foreach (var item in petExtraTokens.Where(item => !repository.Any<PetExtra>(x => x.Name == item.Name && x.Material == item.Material))) foreach (var item in petExtraTokens.Where(item => !repository.Any<PetExtra>(x => x.Name == item.Name && x.Material == item.Material)))
{ {
repository.Add(item); repository.Add(item);
added = true;
} }
if (added)
repository.CommitChanges(); repository.CommitChanges();
return repository.GetAll<PetExtra>().Include(x => x.SalesPackage).ToList(); return repository.GetAll<PetExtra>().Include(x => x.SalesPackage).ToList();
@ -76,6 +82,8 @@
if (pet == null) if (pet == null)
return; return;
account.Pets.RemoveAll(x => x.PetType.Equals(token.PetType) && x.OwnedPetId != pet.OwnedPetId);
pet.PetName = token.PetName; pet.PetName = token.PetName;
repository.Edit(pet); repository.Edit(pet);

View File

@ -35,11 +35,14 @@
{ {
using (var repository = RepositoryFactory.CreateRepository()) using (var repository = RepositoryFactory.CreateRepository())
{ {
bool added = false;
foreach (var skill in skills.Where(skill => !repository.Any<Skill>(x => x.Name == skill.Name && x.Level == skill.Level))) foreach (var skill in skills.Where(skill => !repository.Any<Skill>(x => x.Name == skill.Name && x.Level == skill.Level)))
{ {
repository.Add(skill); repository.Add(skill);
added = true;
} }
if (added)
repository.CommitChanges(); repository.CommitChanges();
return repository.GetAll<Skill>().Include(x => x.SalesPackage).ToList(); return repository.GetAll<Skill>().Include(x => x.SalesPackage).ToList();

File diff suppressed because it is too large Load Diff

Binary file not shown.