From adfe5fb74e3ec0a8bcdb72601d12bea000b5b1bc Mon Sep 17 00:00:00 2001 From: Ty Sayers Date: Sat, 7 Mar 2015 19:36:54 -0500 Subject: [PATCH 01/19] Implement usage of SQL connection pooling in RepositoryBase to prevent unnecessary idle connections. --- .../account/repository/AccountRepository.java | 3 +- .../benefit/BenefitManagerRepository.java | 3 +- .../core/database/RepositoryBase.java | 250 ++++-------------- .../repository/DonationRepository.java | 3 +- .../inventory/data/InventoryRepository.java | 3 +- .../leaderboard/StatEventsRepository.java | 3 +- .../core/report/ReportRepository.java | 3 +- .../mineplex/core/spawn/SpawnRepository.java | 4 +- .../mineplex/core/stats/StatsRepository.java | 9 +- .../enjinTranslator/TempRepository.java | 3 +- .../fields/repository/FieldRepository.java | 3 +- .../src/mineplex/hub/mail/MailRepository.java | 6 +- .../password/PasswordRepository.java | 4 +- 13 files changed, 84 insertions(+), 213 deletions(-) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java index ae3ce09c2..24b3b6635 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java @@ -19,6 +19,7 @@ import mineplex.core.common.Rank; import mineplex.core.common.util.Callback; import mineplex.core.common.util.NautHashMap; import mineplex.core.common.util.UUIDFetcher; +import mineplex.core.database.DBPool; import mineplex.core.database.DatabaseRunnable; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; @@ -43,7 +44,7 @@ public class AccountRepository extends RepositoryBase public AccountRepository(JavaPlugin plugin, String webAddress) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10&allowMultiQueries=true", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); _webAddress = webAddress; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java index 2fa7140aa..5affc2a0b 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java @@ -3,6 +3,7 @@ package mineplex.core.benefit; import java.sql.ResultSet; import java.sql.SQLException; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnVarChar; @@ -16,7 +17,7 @@ public class BenefitManagerRepository extends RepositoryBase public BenefitManagerRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java b/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java index 88d3686bf..338945433 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java @@ -22,58 +22,29 @@ import org.bukkit.plugin.java.JavaPlugin; public abstract class RepositoryBase implements Listener { - protected static Object _connectionLock = new Object(); - - private Connection _connection = null; - + // Queue for failed processes private static Object _queueLock = new Object(); - private NautHashMap _failedQueue = new NautHashMap(); - private String _connectionString; - private String _userName; - private String _password; - - protected JavaPlugin Plugin; - protected DataSource DataSource; - - public RepositoryBase(JavaPlugin plugin, String connectionString, String username, String password) - { - Plugin = plugin; - - _connectionString = connectionString; - _userName = username; - _password = password; - - Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() - { - public void run() - { - synchronized (_connectionLock) - { - initialize(); - update(); - } - } - }); - - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } + private DataSource _dataSource; // Connection pool + protected JavaPlugin Plugin; // Plugin responsible for this repository + /** + * Constructor + * @param plugin - the {@link JavaPlugin} module responsible for this repository. + * @param dataSource - the {@link DataSource} responsible for providing the connection pool to this repository. + */ public RepositoryBase(JavaPlugin plugin, DataSource dataSource) { Plugin = plugin; - DataSource = dataSource; + _dataSource = dataSource; Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { public void run() { - synchronized (_connectionLock) - { - initialize(); - update(); - } + initialize(); + update(); } }); @@ -84,34 +55,39 @@ public abstract class RepositoryBase implements Listener protected abstract void update(); + /** + * @return the {@link DataSource} used by the repository for connection pooling. + */ + protected DataSource getConnectionPool() + { + return _dataSource; + } + + /** + * Requirements: {@link Connection}s must be closed after usage so they may be returned to the pool! + * @see Connection#close() + * @return a newly fetched {@link Connection} from the connection pool, if a connection can be made, null otherwise. + */ protected Connection getConnection() { - return getConnection(false); - } - - protected Connection getConnection(boolean validate) - { - synchronized (_connectionLock) + try { - try - { - if (_connection == null || (validate && !_connection.isValid(2))) - { - if (DataSource != null) - _connection = DataSource.getConnection(); - else - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - } - catch (SQLException e) - { - e.printStackTrace(); - } + return _dataSource.getConnection(); + } + catch (SQLException e) + { + e.printStackTrace(); + // TODO: Log connection failures? + return null; } - - return _connection; } + /** + * Execute a query against the repository. + * @param query - the concatenated query to execute in string form. + * @param columns - the column data values used for insertion into the query. + * @return the number of rows affected by this query in the repository. + */ protected int executeUpdate(String query, Column...columns) { return executeInsert(query, null, columns); @@ -119,16 +95,14 @@ public abstract class RepositoryBase implements Listener protected int executeInsert(String query, ResultSetCallable callable, Column...columns) { - PreparedStatement preparedStatement = null; - int affectedRows = 0; - try + // Automatic resource management for handling/closing objects. + try ( + Connection connection = getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS) + ) { - getConnection(false); - - preparedStatement = _connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); - for (int i=0; i < columns.length; i++) { columns[i].setValue(preparedStatement, i+1); @@ -137,49 +111,24 @@ public abstract class RepositoryBase implements Listener affectedRows = preparedStatement.executeUpdate(); if (callable != null) + { callable.processResultSet(preparedStatement.getGeneratedKeys()); + } } catch (SQLException exception) { - getConnection(true); executeInsert(query, callable, columns); } catch (Exception exception) { exception.printStackTrace(); } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - try - { - if (DataSource != null) - _connection.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } return affectedRows; } protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column...columns) { - ResultSet resultSet = null; - try { for (int i=0; i < columns.length; i++) @@ -187,118 +136,41 @@ public abstract class RepositoryBase implements Listener columns[i].setValue(statement, i+1); } - resultSet = statement.executeQuery(); - - callable.processResultSet(resultSet); + try (ResultSet resultSet = statement.executeQuery()) + { + callable.processResultSet(resultSet); + } } catch (SQLException exception) { - getConnection(true); executeQuery(statement, callable, columns); } catch (Exception exception) { exception.printStackTrace(); } - finally - { - if (resultSet != null) - { - try - { - resultSet.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - try - { - if (DataSource != null) - _connection.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } } protected void executeQuery(String query, ResultSetCallable callable, Column...columns) { - PreparedStatement preparedStatement = null; - - try + // Automatic resource management for handling/closing objects. + try ( + Connection connection = getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(query) + ) { - getConnection(false); - - preparedStatement = _connection.prepareStatement(query); - executeQuery(preparedStatement, callable, columns); } catch (SQLException exception) { - getConnection(true); executeQuery(query, callable, columns); } catch (Exception exception) { exception.printStackTrace(); } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - try - { - if (DataSource != null) - _connection.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } } - - protected int executeUpdate(PreparedStatement preparedStatement, Column...columns) - { - int affectedRows = 0; - try - { - for (int i=0; i < columns.length; i++) - { - columns[i].setValue(preparedStatement, i+1); - } - - affectedRows = preparedStatement.executeUpdate(); - } - catch (SQLException exception) - { - getConnection(true); - executeUpdate(preparedStatement, columns); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - - return affectedRows; - } - protected void handleDatabaseCall(final DatabaseRunnable databaseRunnable, final String errorMessage) { Thread asyncThread = new Thread(new Runnable() @@ -344,19 +216,7 @@ public abstract class RepositoryBase implements Listener @EventHandler public void validateConnection(UpdateEvent event) { - if (event.getType() != UpdateType.MIN_02 || DataSource != null) - return; - - Bukkit.getScheduler().runTaskAsynchronously(Plugin, new Runnable() - { - public void run() - { - synchronized (_connectionLock) - { - getConnection(true); - } - } - }); + // Utilizes DataSource connection pools, so there is no connection to validate. } private void processFailedQueue() diff --git a/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java index 818c95df9..b7246e8be 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java @@ -8,6 +8,7 @@ import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.common.util.Callback; +import mineplex.core.database.DBPool; import mineplex.core.database.DatabaseRunnable; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; @@ -33,7 +34,7 @@ public class DonationRepository extends RepositoryBase public DonationRepository(JavaPlugin plugin, String webAddress) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); _webAddress = webAddress; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java index 2a1cb7f27..444e98bbf 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java @@ -7,6 +7,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnInt; @@ -31,7 +32,7 @@ public class InventoryRepository extends RepositoryBase public InventoryRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java index 2e0888f1e..1679bc36d 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java @@ -1,5 +1,6 @@ package mineplex.core.leaderboard; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; import mineplex.core.database.column.ColumnVarChar; @@ -35,7 +36,7 @@ public class StatEventsRepository extends RepositoryBase */ public StatEventsRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java index 968010e9c..4a9f91215 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java @@ -7,6 +7,7 @@ import java.util.UUID; import java.util.Map.Entry; import mineplex.core.common.util.NautHashMap; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnInt; @@ -40,7 +41,7 @@ This will be used to determine if staff are handling public ReportRepository(JavaPlugin plugin, String connectionString) { - super(plugin, connectionString, "root", "tAbechAk3wR7tuTh"); // TODO: Config file for host/pass? + super(plugin, DBPool.ACCOUNT); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java index 69a5e3b64..eb85bae9d 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java @@ -7,6 +7,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -22,8 +23,7 @@ public class SpawnRepository extends RepositoryBase public SpawnRepository(JavaPlugin plugin, String serverName) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); - + super(plugin, DBPool.ACCOUNT); _serverName = serverName; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java index 827b3605c..58c81c9f8 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java @@ -9,6 +9,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.common.util.NautHashMap; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -18,6 +19,7 @@ import org.jooq.DSLContext; import org.jooq.Insert; import org.jooq.Record2; import org.jooq.Result; +import org.jooq.SQLDialect; import org.jooq.Update; import org.jooq.impl.DSL; @@ -31,7 +33,7 @@ public class StatsRepository extends RepositoryBase public StatsRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } @Override @@ -79,8 +81,7 @@ public class StatsRepository extends RepositoryBase { try { - - DSLContext context = DSL.using(getConnection(true)); + DSLContext context = DSL.using(getConnectionPool(), SQLDialect.MYSQL); List updates = new ArrayList<>(); List inserts = new ArrayList<>(); @@ -133,7 +134,7 @@ public class StatsRepository extends RepositoryBase synchronized (this) { - context = DSL.using(getConnection()); + context = DSL.using(getConnectionPool(), SQLDialect.MYSQL); } Result> result = context.select(Tables.stats.name, Tables.accountStats.value).from(Tables.accountStats) diff --git a/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java b/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java index e052ee72e..ba4cd2729 100644 --- a/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java +++ b/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java @@ -2,6 +2,7 @@ package mineplex.enjinTranslator; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; import mineplex.core.database.column.ColumnVarChar; @@ -12,7 +13,7 @@ public class TempRepository extends RepositoryBase public TempRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } public void addGemBooster(String name, int amount) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java index cad9425ef..f5be7a077 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java @@ -7,6 +7,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnByte; @@ -31,7 +32,7 @@ public class FieldRepository extends RepositoryBase public FieldRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } public List getFieldBlocks(String server) diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java b/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java index 59e7e796c..af43ab9f5 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java @@ -6,9 +6,11 @@ import java.util.UUID; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.database.Tables; import mineplex.database.tables.records.MailRecord; + import org.jooq.DSLContext; import org.jooq.Result; import org.jooq.impl.DSL; @@ -19,8 +21,8 @@ public class MailRepository extends RepositoryBase public MailRepository(JavaPlugin plugin, MailManager manager) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); - + super(plugin, DBPool.ACCOUNT); + _manager = manager; } diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java index 796bde45d..20cb041e0 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java @@ -7,6 +7,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -23,8 +24,7 @@ public class PasswordRepository extends RepositoryBase public PasswordRepository(JavaPlugin plugin, String serverName) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); - + super(plugin, DBPool.ACCOUNT); _serverName = serverName; } From 215ec7b00dff89b0fbb2646de67531d6fe4406d2 Mon Sep 17 00:00:00 2001 From: Ty Sayers Date: Sat, 7 Mar 2015 19:38:06 -0500 Subject: [PATCH 02/19] Revert "Implement usage of SQL connection pooling in RepositoryBase to prevent unnecessary idle connections." This reverts commit adfe5fb74e3ec0a8bcdb72601d12bea000b5b1bc. --- .../account/repository/AccountRepository.java | 3 +- .../benefit/BenefitManagerRepository.java | 3 +- .../core/database/RepositoryBase.java | 326 +++++++++++++----- .../repository/DonationRepository.java | 3 +- .../inventory/data/InventoryRepository.java | 3 +- .../leaderboard/StatEventsRepository.java | 3 +- .../core/report/ReportRepository.java | 3 +- .../mineplex/core/spawn/SpawnRepository.java | 4 +- .../mineplex/core/stats/StatsRepository.java | 9 +- .../enjinTranslator/TempRepository.java | 3 +- .../fields/repository/FieldRepository.java | 3 +- .../src/mineplex/hub/mail/MailRepository.java | 6 +- .../password/PasswordRepository.java | 4 +- 13 files changed, 251 insertions(+), 122 deletions(-) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java index 24b3b6635..ae3ce09c2 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java @@ -19,7 +19,6 @@ import mineplex.core.common.Rank; import mineplex.core.common.util.Callback; import mineplex.core.common.util.NautHashMap; import mineplex.core.common.util.UUIDFetcher; -import mineplex.core.database.DBPool; import mineplex.core.database.DatabaseRunnable; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; @@ -44,7 +43,7 @@ public class AccountRepository extends RepositoryBase public AccountRepository(JavaPlugin plugin, String webAddress) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10&allowMultiQueries=true", "root", "tAbechAk3wR7tuTh"); _webAddress = webAddress; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java index 5affc2a0b..2fa7140aa 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java @@ -3,7 +3,6 @@ package mineplex.core.benefit; import java.sql.ResultSet; import java.sql.SQLException; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnVarChar; @@ -17,7 +16,7 @@ public class BenefitManagerRepository extends RepositoryBase public BenefitManagerRepository(JavaPlugin plugin) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java b/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java index 338945433..88d3686bf 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java @@ -22,29 +22,58 @@ import org.bukkit.plugin.java.JavaPlugin; public abstract class RepositoryBase implements Listener { - // Queue for failed processes + protected static Object _connectionLock = new Object(); + + private Connection _connection = null; + private static Object _queueLock = new Object(); + private NautHashMap _failedQueue = new NautHashMap(); - private DataSource _dataSource; // Connection pool - protected JavaPlugin Plugin; // Plugin responsible for this repository + private String _connectionString; + private String _userName; + private String _password; - /** - * Constructor - * @param plugin - the {@link JavaPlugin} module responsible for this repository. - * @param dataSource - the {@link DataSource} responsible for providing the connection pool to this repository. - */ - public RepositoryBase(JavaPlugin plugin, DataSource dataSource) + protected JavaPlugin Plugin; + protected DataSource DataSource; + + public RepositoryBase(JavaPlugin plugin, String connectionString, String username, String password) { Plugin = plugin; - _dataSource = dataSource; + + _connectionString = connectionString; + _userName = username; + _password = password; Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { public void run() { - initialize(); - update(); + synchronized (_connectionLock) + { + initialize(); + update(); + } + } + }); + + plugin.getServer().getPluginManager().registerEvents(this, plugin); + } + + public RepositoryBase(JavaPlugin plugin, DataSource dataSource) + { + Plugin = plugin; + DataSource = dataSource; + + Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() + { + public void run() + { + synchronized (_connectionLock) + { + initialize(); + update(); + } } }); @@ -55,39 +84,34 @@ public abstract class RepositoryBase implements Listener protected abstract void update(); - /** - * @return the {@link DataSource} used by the repository for connection pooling. - */ - protected DataSource getConnectionPool() - { - return _dataSource; - } - - /** - * Requirements: {@link Connection}s must be closed after usage so they may be returned to the pool! - * @see Connection#close() - * @return a newly fetched {@link Connection} from the connection pool, if a connection can be made, null otherwise. - */ protected Connection getConnection() { - try - { - return _dataSource.getConnection(); - } - catch (SQLException e) - { - e.printStackTrace(); - // TODO: Log connection failures? - return null; - } + return getConnection(false); + } + + protected Connection getConnection(boolean validate) + { + synchronized (_connectionLock) + { + try + { + if (_connection == null || (validate && !_connection.isValid(2))) + { + if (DataSource != null) + _connection = DataSource.getConnection(); + else + _connection = DriverManager.getConnection(_connectionString, _userName, _password); + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + return _connection; } - /** - * Execute a query against the repository. - * @param query - the concatenated query to execute in string form. - * @param columns - the column data values used for insertion into the query. - * @return the number of rows affected by this query in the repository. - */ protected int executeUpdate(String query, Column...columns) { return executeInsert(query, null, columns); @@ -95,14 +119,16 @@ public abstract class RepositoryBase implements Listener protected int executeInsert(String query, ResultSetCallable callable, Column...columns) { + PreparedStatement preparedStatement = null; + int affectedRows = 0; - // Automatic resource management for handling/closing objects. - try ( - Connection connection = getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS) - ) + try { + getConnection(false); + + preparedStatement = _connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); + for (int i=0; i < columns.length; i++) { columns[i].setValue(preparedStatement, i+1); @@ -111,66 +137,168 @@ public abstract class RepositoryBase implements Listener affectedRows = preparedStatement.executeUpdate(); if (callable != null) - { callable.processResultSet(preparedStatement.getGeneratedKeys()); - } } catch (SQLException exception) { + getConnection(true); executeInsert(query, callable, columns); } catch (Exception exception) { exception.printStackTrace(); } + finally + { + if (preparedStatement != null) + { + try + { + preparedStatement.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + try + { + if (DataSource != null) + _connection.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + return affectedRows; + } + + protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column...columns) + { + ResultSet resultSet = null; + + try + { + for (int i=0; i < columns.length; i++) + { + columns[i].setValue(statement, i+1); + } + + resultSet = statement.executeQuery(); + + callable.processResultSet(resultSet); + } + catch (SQLException exception) + { + getConnection(true); + executeQuery(statement, callable, columns); + } + catch (Exception exception) + { + exception.printStackTrace(); + } + finally + { + if (resultSet != null) + { + try + { + resultSet.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + try + { + if (DataSource != null) + _connection.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + } + + protected void executeQuery(String query, ResultSetCallable callable, Column...columns) + { + PreparedStatement preparedStatement = null; + + try + { + getConnection(false); + + preparedStatement = _connection.prepareStatement(query); + + executeQuery(preparedStatement, callable, columns); + } + catch (SQLException exception) + { + getConnection(true); + executeQuery(query, callable, columns); + } + catch (Exception exception) + { + exception.printStackTrace(); + } + finally + { + if (preparedStatement != null) + { + try + { + preparedStatement.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + try + { + if (DataSource != null) + _connection.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + } + + protected int executeUpdate(PreparedStatement preparedStatement, Column...columns) + { + int affectedRows = 0; + + try + { + for (int i=0; i < columns.length; i++) + { + columns[i].setValue(preparedStatement, i+1); + } + + affectedRows = preparedStatement.executeUpdate(); + } + catch (SQLException exception) + { + getConnection(true); + executeUpdate(preparedStatement, columns); + } + catch (Exception exception) + { + exception.printStackTrace(); + } return affectedRows; } - protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column...columns) - { - try - { - for (int i=0; i < columns.length; i++) - { - columns[i].setValue(statement, i+1); - } - - try (ResultSet resultSet = statement.executeQuery()) - { - callable.processResultSet(resultSet); - } - } - catch (SQLException exception) - { - executeQuery(statement, callable, columns); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - } - - protected void executeQuery(String query, ResultSetCallable callable, Column...columns) - { - // Automatic resource management for handling/closing objects. - try ( - Connection connection = getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement(query) - ) - { - executeQuery(preparedStatement, callable, columns); - } - catch (SQLException exception) - { - executeQuery(query, callable, columns); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - } - protected void handleDatabaseCall(final DatabaseRunnable databaseRunnable, final String errorMessage) { Thread asyncThread = new Thread(new Runnable() @@ -216,7 +344,19 @@ public abstract class RepositoryBase implements Listener @EventHandler public void validateConnection(UpdateEvent event) { - // Utilizes DataSource connection pools, so there is no connection to validate. + if (event.getType() != UpdateType.MIN_02 || DataSource != null) + return; + + Bukkit.getScheduler().runTaskAsynchronously(Plugin, new Runnable() + { + public void run() + { + synchronized (_connectionLock) + { + getConnection(true); + } + } + }); } private void processFailedQueue() diff --git a/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java index b7246e8be..818c95df9 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java @@ -8,7 +8,6 @@ import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.common.util.Callback; -import mineplex.core.database.DBPool; import mineplex.core.database.DatabaseRunnable; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; @@ -34,7 +33,7 @@ public class DonationRepository extends RepositoryBase public DonationRepository(JavaPlugin plugin, String webAddress) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); _webAddress = webAddress; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java index 444e98bbf..2a1cb7f27 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java @@ -7,7 +7,6 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnInt; @@ -32,7 +31,7 @@ public class InventoryRepository extends RepositoryBase public InventoryRepository(JavaPlugin plugin) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java index 1679bc36d..2e0888f1e 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java @@ -1,6 +1,5 @@ package mineplex.core.leaderboard; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; import mineplex.core.database.column.ColumnVarChar; @@ -36,7 +35,7 @@ public class StatEventsRepository extends RepositoryBase */ public StatEventsRepository(JavaPlugin plugin) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java index 4a9f91215..968010e9c 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java @@ -7,7 +7,6 @@ import java.util.UUID; import java.util.Map.Entry; import mineplex.core.common.util.NautHashMap; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnInt; @@ -41,7 +40,7 @@ This will be used to determine if staff are handling public ReportRepository(JavaPlugin plugin, String connectionString) { - super(plugin, DBPool.ACCOUNT); + super(plugin, connectionString, "root", "tAbechAk3wR7tuTh"); // TODO: Config file for host/pass? } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java index eb85bae9d..69a5e3b64 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java @@ -7,7 +7,6 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -23,7 +22,8 @@ public class SpawnRepository extends RepositoryBase public SpawnRepository(JavaPlugin plugin, String serverName) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + _serverName = serverName; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java index 58c81c9f8..827b3605c 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java @@ -9,7 +9,6 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.common.util.NautHashMap; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -19,7 +18,6 @@ import org.jooq.DSLContext; import org.jooq.Insert; import org.jooq.Record2; import org.jooq.Result; -import org.jooq.SQLDialect; import org.jooq.Update; import org.jooq.impl.DSL; @@ -33,7 +31,7 @@ public class StatsRepository extends RepositoryBase public StatsRepository(JavaPlugin plugin) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); } @Override @@ -81,7 +79,8 @@ public class StatsRepository extends RepositoryBase { try { - DSLContext context = DSL.using(getConnectionPool(), SQLDialect.MYSQL); + + DSLContext context = DSL.using(getConnection(true)); List updates = new ArrayList<>(); List inserts = new ArrayList<>(); @@ -134,7 +133,7 @@ public class StatsRepository extends RepositoryBase synchronized (this) { - context = DSL.using(getConnectionPool(), SQLDialect.MYSQL); + context = DSL.using(getConnection()); } Result> result = context.select(Tables.stats.name, Tables.accountStats.value).from(Tables.accountStats) diff --git a/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java b/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java index ba4cd2729..e052ee72e 100644 --- a/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java +++ b/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java @@ -2,7 +2,6 @@ package mineplex.enjinTranslator; import org.bukkit.plugin.java.JavaPlugin; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; import mineplex.core.database.column.ColumnVarChar; @@ -13,7 +12,7 @@ public class TempRepository extends RepositoryBase public TempRepository(JavaPlugin plugin) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); } public void addGemBooster(String name, int amount) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java index f5be7a077..cad9425ef 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java @@ -7,7 +7,6 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnByte; @@ -32,7 +31,7 @@ public class FieldRepository extends RepositoryBase public FieldRepository(JavaPlugin plugin) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); } public List getFieldBlocks(String server) diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java b/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java index af43ab9f5..59e7e796c 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java @@ -6,11 +6,9 @@ import java.util.UUID; import org.bukkit.plugin.java.JavaPlugin; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.database.Tables; import mineplex.database.tables.records.MailRecord; - import org.jooq.DSLContext; import org.jooq.Result; import org.jooq.impl.DSL; @@ -21,8 +19,8 @@ public class MailRepository extends RepositoryBase public MailRepository(JavaPlugin plugin, MailManager manager) { - super(plugin, DBPool.ACCOUNT); - + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + _manager = manager; } diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java index 20cb041e0..796bde45d 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java @@ -7,7 +7,6 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; -import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -24,7 +23,8 @@ public class PasswordRepository extends RepositoryBase public PasswordRepository(JavaPlugin plugin, String serverName) { - super(plugin, DBPool.ACCOUNT); + super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + _serverName = serverName; } From ac4b4953017c168c7195c5c37a799ad9c6dbbbfa Mon Sep 17 00:00:00 2001 From: Tim Ziankoski Date: Sat, 7 Mar 2015 20:50:47 -0500 Subject: [PATCH 03/19] Created internationalization helper class and began i18n process --- .../artifacts/Nautilus_Game_Arcade_jar.xml | 2 +- .../artifacts/Nautilus_Game_Arcade_test.xml | 1 + Plugins/.idea/copyright/profiles_settings.xml | 3 + .../Mineplex.Core.Common.iml | 4 +- .../core/common/lang/mineplex_de.properties | 1 + .../core/common/lang/mineplex_en.properties | 4 + .../src/mineplex/core/common/lang/Lang.java | 115 ++++++++++++++++++ .../arcade/managers/GameLobbyManager.java | 12 +- 8 files changed, 134 insertions(+), 8 deletions(-) create mode 100644 Plugins/.idea/copyright/profiles_settings.xml create mode 100644 Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_de.properties create mode 100644 Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_en.properties create mode 100644 Plugins/Mineplex.Core.Common/src/mineplex/core/common/lang/Lang.java diff --git a/Plugins/.idea/artifacts/Nautilus_Game_Arcade_jar.xml b/Plugins/.idea/artifacts/Nautilus_Game_Arcade_jar.xml index cd4447b88..3f5cae6e4 100644 --- a/Plugins/.idea/artifacts/Nautilus_Game_Arcade_jar.xml +++ b/Plugins/.idea/artifacts/Nautilus_Game_Arcade_jar.xml @@ -17,7 +17,7 @@ - + \ No newline at end of file diff --git a/Plugins/.idea/artifacts/Nautilus_Game_Arcade_test.xml b/Plugins/.idea/artifacts/Nautilus_Game_Arcade_test.xml index 8b3142e4c..73139df16 100644 --- a/Plugins/.idea/artifacts/Nautilus_Game_Arcade_test.xml +++ b/Plugins/.idea/artifacts/Nautilus_Game_Arcade_test.xml @@ -3,6 +3,7 @@ $PROJECT_DIR$/../Testing/Arcade/plugins + \ No newline at end of file diff --git a/Plugins/.idea/copyright/profiles_settings.xml b/Plugins/.idea/copyright/profiles_settings.xml new file mode 100644 index 000000000..e7bedf337 --- /dev/null +++ b/Plugins/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/Plugins/Mineplex.Core.Common/Mineplex.Core.Common.iml b/Plugins/Mineplex.Core.Common/Mineplex.Core.Common.iml index b59695f8a..c145ccad3 100644 --- a/Plugins/Mineplex.Core.Common/Mineplex.Core.Common.iml +++ b/Plugins/Mineplex.Core.Common/Mineplex.Core.Common.iml @@ -4,10 +4,10 @@ + - - + \ No newline at end of file diff --git a/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_de.properties b/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_de.properties new file mode 100644 index 000000000..cb380f81e --- /dev/null +++ b/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_de.properties @@ -0,0 +1 @@ +waiting.for.players=Warten auf Spieler diff --git a/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_en.properties b/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_en.properties new file mode 100644 index 000000000..d99ecb4b3 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_en.properties @@ -0,0 +1,4 @@ +waiting.for.players=Waiting for Players +lobby=Lobby +starting.in.0.seconds=Starting in {0} Seconds +starting.in.0.seconds.singular=Starting in {0} Second diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/lang/Lang.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/lang/Lang.java new file mode 100644 index 000000000..cb6e3fa89 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/lang/Lang.java @@ -0,0 +1,115 @@ +package mineplex.core.common.lang; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.WeakHashMap; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +public final class Lang +{ + private static final String RESOURCE_BUNDLE_PATH = "mineplex/core/common/lang/mineplex"; + + private static final Map _playerLocales = new WeakHashMap<>(); + private static final ResourceBundle _defaultResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE_PATH); + private static final Map _localeResourceBundles = Collections.synchronizedMap(new HashMap()); + + private Lang() + { + + } + + public static void setPlayerLocale(Player player, Locale locale) + { + _playerLocales.put(player, locale); + } + + public static ResourceBundle getDefaultResourceBundle() + { + return _defaultResourceBundle; + } + + public static ResourceBundle getResourceBundle(Locale locale) + { + ResourceBundle bundle = getDefaultResourceBundle(); + + synchronized (_localeResourceBundles) + { + if (_localeResourceBundles.containsKey(locale)) + { + ResourceBundle b = _localeResourceBundles.get(locale); + if (b != null) + bundle = b; + } + else + { + try + { + bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE_PATH, locale); + _localeResourceBundles.put(locale, bundle); + } + catch (MissingResourceException e) + { + _localeResourceBundles.put(locale, null); + + Bukkit.getLogger().warning(e.getMessage()); + } + } + } + + return bundle; + } + + public static String getString(String key, int count) + { + return getString(key, (Locale) null, count); + } + + public static String getString(String key, Locale locale, int count) + { + if (key == null) + return null; + else + { + ResourceBundle bundle; + if (locale == null) + bundle = getDefaultResourceBundle(); + else + bundle = getResourceBundle(locale); + + if (count == 1) + { + String singularKey = key + ".singular"; + if (bundle.containsKey(singularKey)) + return bundle.getString(singularKey); + } + + return bundle.getString(key); + } + } + + public static String getString(String key, Player player, int count) + { + return getString(key, _playerLocales.get(player), count); + } + + public static String getString(String key) + { + return getString(key, 0); + } + + public static String getString(String key, Locale locale) + { + return getString(key, locale, 0); + } + + public static String getString(String key, Player player) + { + return getString(key, player, 0); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java index fe3a858b4..688eaa4b8 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java @@ -1,10 +1,11 @@ package nautilus.game.arcade.managers; -import java.util.ArrayList; +import java.text.MessageFormat;import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map.Entry; import org.bukkit.Bukkit; @@ -41,6 +42,7 @@ import net.minecraft.server.v1_7_R4.WatchableObject; import mineplex.core.account.CoreClient; import mineplex.core.common.Rank; +import mineplex.core.common.lang.Lang; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.MapUtil; @@ -948,18 +950,18 @@ public class GameLobbyManager implements Listener, IPacketHandler for (Entry entry : _scoreboardMap.entrySet()) { - Objective objective = entry.getValue().getObjective("§l" + "Lobby"); - + Objective objective = entry.getValue().getObjective(C.Bold + Lang.getString("lobby", entry.getKey())); + if (Manager.GetGame() != null && Manager.GetGame().GetCountdown() >= 0) { if (Manager.GetGame().GetCountdown() > 0) - objective.setDisplayName(C.Bold + "§lStarting in " + C.cGreen + "§l" + Manager.GetGame().GetCountdown() + (Manager.GetGame().GetCountdown() == 1 ? " Second" : " Seconds")); + objective.setDisplayName(MessageFormat.format(C.Bold + Lang.getString("starting.in.0.seconds", entry.getKey(), Manager.GetGame().GetCountdown()), C.cGreen + C.Bold + Manager.GetGame().GetCountdown())); else if (Manager.GetGame().GetCountdown() == 0) objective.setDisplayName(ChatColor.WHITE + "§lIn Progress..."); } else { - objective.setDisplayName(ChatColor.GREEN + "§l" + "Waiting for Players"); + objective.setDisplayName(C.cGreen + C.Bold + Lang.getString("waiting.for.players", entry.getKey())); } int line = 15; From 521891f409dbc852e86ac2de39d64613593f9f7c Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Sat, 7 Mar 2015 21:47:02 -0800 Subject: [PATCH 04/19] Updated BungeeRotator to reflect new API key and abide by new rate limits. --- .../src/mineplex/bungee/BungeeRotator.java | 24 +++++++++++++------ .../bungee/api/DnsMadeEasyApiCallBase.java | 4 ++-- .../mineplex/bungee/api/token/DnsRecord.java | 2 +- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/BungeeRotator.java b/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/BungeeRotator.java index 359087bbe..5cd4b495f 100644 --- a/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/BungeeRotator.java +++ b/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/BungeeRotator.java @@ -119,21 +119,31 @@ public class BungeeRotator for (String address : usServers) { recordsToAdd.add(new ARecord("us", address, 300)); - log("Addding server address in DNS : " + "us " + address); + log("Adding server address in DNS : " + "us " + address); } - for (String address : euServers) - { - recordsToAdd.add(new ARecord("eu", address, 300)); - log("Addding server address in DNS : " + "eu " + address); - } - if (recordsToAdd.size() > 0) { new ApiPostCall("https://api.dnsmadeeasy.com/V2.0/dns/managed/", 962728, "/records/", "createMulti").Execute(recordsToAdd); log("Created " + recordsToAdd.size() + " records."); } + + recordsToAdd.clear(); + + for (String address : euServers) + { + recordsToAdd.add(new ARecord("eu", address, 300)); + log("Adding server address in DNS : " + "eu " + address); + } + + if (recordsToAdd.size() > 0) + { + new ApiPostCall("https://api.dnsmadeeasy.com/V2.0/dns/managed/", 962728, "/records/", "createMulti").Execute(recordsToAdd); + log("Created " + recordsToAdd.size() + " records."); + } + recordsToAdd.clear(); + if (recordsToDelete.size() > 0) { StringBuilder idBuilder = new StringBuilder(); diff --git a/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/api/DnsMadeEasyApiCallBase.java b/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/api/DnsMadeEasyApiCallBase.java index 87ade774a..f4e7aac72 100644 --- a/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/api/DnsMadeEasyApiCallBase.java +++ b/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/api/DnsMadeEasyApiCallBase.java @@ -51,13 +51,13 @@ public abstract class DnsMadeEasyApiCallBase try { String timeStamp = getServerTime(); - SecretKeySpec keySpec = new SecretKeySpec("8c9af8cc-d306-4df3-8de8-944deafa8239".getBytes(), "HmacSHA1"); + SecretKeySpec keySpec = new SecretKeySpec("35bb3b97-3815-4b63-b60b-eb1882c07b40".getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] hashBytes = mac.doFinal((timeStamp + "").getBytes()); Hex.encodeHexString(hashBytes); - request.addHeader("x-dnsme-apiKey", "610e21ee-4250-4b55-b637-a1fcc3847850"); + request.addHeader("x-dnsme-apiKey", "a9750980-b7df-4a7e-a047-2ade43628f0d"); request.addHeader("x-dnsme-requestDate", timeStamp + ""); request.addHeader("x-dnsme-hmac", Hex.encodeHexString(hashBytes)); request.addHeader("Content-Type", "application/json"); diff --git a/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/api/token/DnsRecord.java b/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/api/token/DnsRecord.java index a4d50c840..469b600be 100644 --- a/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/api/token/DnsRecord.java +++ b/Plugins/Mineplex.BungeeRotator/src/mineplex/bungee/api/token/DnsRecord.java @@ -6,6 +6,6 @@ public class DnsRecord public String name; public String type; public String value; - public String gtdLocation; + public String gtdLocation = "DEFAULT"; public int ttl; } From 14da350b1692344994098210a88aab8591d055a3 Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Sat, 7 Mar 2015 21:47:48 -0800 Subject: [PATCH 05/19] Removed unnecessary Windows DB call for Pet Factory. --- .../src/mineplex/core/pet/PetFactory.java | 38 ------------------- 1 file changed, 38 deletions(-) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/pet/PetFactory.java b/Plugins/Mineplex.Core/src/mineplex/core/pet/PetFactory.java index 40f7815f0..84a1a2664 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/pet/PetFactory.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/pet/PetFactory.java @@ -42,49 +42,11 @@ public class PetFactory _pets.put(EntityType.OCELOT, new Pet("Cat", EntityType.OCELOT, 6000)); _pets.put(EntityType.MUSHROOM_COW, new Pet("Mooshroom", EntityType.MUSHROOM_COW, 5000)); _pets.put(EntityType.WITHER, new Pet("Widder", EntityType.WITHER, -1)); - - List petTokens = new ArrayList(); - - for (Pet pet : _pets.values()) - { - PetSalesToken petToken = new PetSalesToken(); - petToken.Name = pet.GetPetName(); - petToken.PetType = pet.GetPetType().toString(); - - petTokens.add(petToken); - } - - for (PetSalesToken petToken : _repository.GetPets(petTokens)) - { - if (_pets.containsKey(EntityType.valueOf(petToken.PetType))) - { - _pets.get(EntityType.valueOf(petToken.PetType)).Update(petToken); - } - } } private void CreatePetExtras() { _petExtras.put(Material.SIGN, new PetExtra("Name Tag", Material.NAME_TAG, 100)); - - List petExtraTokens = new ArrayList(); - - for (PetExtra petExtra : _petExtras.values()) - { - PetExtraToken petToken = new PetExtraToken(); - petToken.Name = petExtra.GetName(); - petToken.Material = petExtra.GetMaterial().toString(); - - petExtraTokens.add(petToken); - } - - for (PetExtraToken token : _repository.GetPetExtras(petExtraTokens)) - { - if (_petExtras.containsKey(Material.valueOf(token.Material))) - { - _petExtras.get(Material.valueOf(token.Material)).Update(token); - } - } } public Collection GetPets() From bd8c101901a1ede335ac8d588d4cd14ed96ddfe8 Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Sat, 7 Mar 2015 21:48:15 -0800 Subject: [PATCH 06/19] Slowed down interval for pulling servers on bungees. --- .../src/mineplex/bungee/lobbyBalancer/LobbyBalancer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/lobbyBalancer/LobbyBalancer.java b/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/lobbyBalancer/LobbyBalancer.java index 5cb5e1aa4..1d723e808 100644 --- a/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/lobbyBalancer/LobbyBalancer.java +++ b/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/lobbyBalancer/LobbyBalancer.java @@ -37,7 +37,7 @@ public class LobbyBalancer implements Listener, Runnable loadLobbyServers(); _plugin.getProxy().getPluginManager().registerListener(_plugin, this); - _plugin.getProxy().getScheduler().schedule(_plugin, this, 150L, 150L, TimeUnit.MILLISECONDS); + _plugin.getProxy().getScheduler().schedule(_plugin, this, 250L, 250L, TimeUnit.MILLISECONDS); } @EventHandler From 579ac8171d5054ec5df96568619997243deee0d3 Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Sat, 7 Mar 2015 21:48:51 -0800 Subject: [PATCH 07/19] Hard-coded UUIDs for Staff Server to prevent UUID lookup Rate limits --- .../src/mineplex/staffServer/StaffServer.java | 55 +++---------------- 1 file changed, 8 insertions(+), 47 deletions(-) diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java index 4007b59a3..647cf3638 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java @@ -1,5 +1,7 @@ package mineplex.staffServer; +import java.util.UUID; + import mineplex.core.account.CoreClientManager; import mineplex.core.antihack.AntiHack; import mineplex.core.chat.Chat; @@ -75,52 +77,11 @@ public class StaffServer extends JavaPlugin ((CraftServer)getServer()).setWhitelist(true); - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() - { - public void run() - { - ((CraftServer)getServer()).getHandle().addWhitelist(new ProfileLoader(UUIDFetcher.getUUIDOf("NDrew").toString(), "NDrew").loadProfile()); - } - }, 20L); - - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() - { - public void run() - { - ((CraftServer)getServer()).getHandle().addWhitelist(new ProfileLoader(UUIDFetcher.getUUIDOf("Morena").toString(), "Morena").loadProfile()); - } - }, 40L); - - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() - { - public void run() - { - ((CraftServer)getServer()).getHandle().addWhitelist(new ProfileLoader(UUIDFetcher.getUUIDOf("Revolark").toString(), "Revolark").loadProfile()); - } - }, 60L); - - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() - { - public void run() - { - ((CraftServer)getServer()).getHandle().addWhitelist(new ProfileLoader(UUIDFetcher.getUUIDOf("EvilEsther").toString(), "EvilEsther").loadProfile()); - } - }, 80L); - - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() - { - public void run() - { - ((CraftServer)getServer()).getHandle().addWhitelist(new ProfileLoader(UUIDFetcher.getUUIDOf("Timmy48081_").toString(), "Timmy48081_").loadProfile()); - } - }, 100L); - - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() - { - public void run() - { - ((CraftServer)getServer()).getHandle().addWhitelist(new ProfileLoader(UUIDFetcher.getUUIDOf("issh").toString(), "issh").loadProfile()); - } - }, 120L); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("d3965dbc-f9cc-4e5d-9306-5be2a23ad6cb"), "NDrew")); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("939cfa72-213c-4b70-a638-c637a4955239"), "Morena")); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("f4a7aad4-116f-491a-b162-af0422c0ec4f"), "Revolark")); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("04a484d0-93e0-4777-a70c-808046917e3a"), "EvilEsther")); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("a6324fac-d44e-449c-adbe-6238423e29f2"), "Timmy48081")); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("2d5fd31b-0aa5-41db-a62d-a4611a24349a"), "ishh")); } } From dbeea5bf690c0e3013aa2a3814c8b4efa9bfb001 Mon Sep 17 00:00:00 2001 From: libraryaddict Date: Mon, 9 Mar 2015 05:17:04 +1300 Subject: [PATCH 08/19] Pre-Frost changes --- .../games/survivalgames/SurvivalGames.java | 1758 ++++++++++++----- 1 file changed, 1221 insertions(+), 537 deletions(-) diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/survivalgames/SurvivalGames.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/survivalgames/SurvivalGames.java index 1d050b58e..30f07f341 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/survivalgames/SurvivalGames.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/survivalgames/SurvivalGames.java @@ -1,5 +1,6 @@ package nautilus.game.arcade.game.games.survivalgames; +import java.lang.reflect.Field; import java.util.*; import java.util.Map.Entry; @@ -7,8 +8,16 @@ import org.bukkit.*; import org.bukkit.FireworkEffect.Type; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; import org.bukkit.block.Chest; +import org.bukkit.block.DoubleChest; +import org.bukkit.block.Furnace; +import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; +import org.bukkit.craftbukkit.v1_7_R4.entity.CraftArrow; +import org.bukkit.craftbukkit.v1_7_R4.entity.CraftPlayer; import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Firework; import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Player; import org.bukkit.entity.Snowball; @@ -27,17 +36,27 @@ import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.hanging.HangingBreakEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.PrepareItemCraftEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.FurnaceInventory; +import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; +import org.bukkit.scoreboard.TeamNameTagVisibility; import org.bukkit.util.Vector; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.MapUtil; +import mineplex.core.common.util.NautHashMap; import mineplex.core.common.util.UtilAction; import mineplex.core.common.util.UtilAlg; import mineplex.core.common.util.UtilBlock; @@ -54,7 +73,11 @@ import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTime; import mineplex.core.common.util.UtilTime.TimeUnit; import mineplex.core.common.util.UtilWorld; -import mineplex.core.itemstack.ItemStackFactory; +import mineplex.core.disguise.disguises.DisguisePlayer; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.loot.*; +import mineplex.core.packethandler.IPacketHandler; +import mineplex.core.packethandler.PacketInfo; import mineplex.core.recharge.Recharge; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; @@ -72,96 +95,126 @@ import nautilus.game.arcade.stats.FirstSupplyDropOpenStatTracker; import nautilus.game.arcade.stats.KillsWithinTimeLimitStatTracker; import nautilus.game.arcade.stats.SimultaneousSkeletonStatTracker; import nautilus.game.arcade.stats.WinWithoutWearingArmorStatTracker; +import net.minecraft.server.v1_7_R4.EntityArrow; +import net.minecraft.server.v1_7_R4.PacketPlayInUseEntity; +import net.minecraft.server.v1_7_R4.PacketPlayOutScoreboardTeam; +import net.minecraft.server.v1_7_R4.ScoreboardTeam; +import net.minecraft.server.v1_7_R4.TileEntity; +import net.minecraft.server.v1_7_R4.TileEntityChest; +import net.minecraft.util.com.mojang.authlib.GameProfile; public class SurvivalGames extends SoloGame -{ - private HashSet _openedChest = new HashSet(); - private ArrayList _baseChestLoot = new ArrayList(); - private ArrayList _superChestLoot = new ArrayList(); +{ + // Lootables + private ChestLoot _baseLoot = new ChestLoot(); + private ChestLoot _spawnLoot = new ChestLoot(); + private ChestLoot _superLoot = new ChestLoot(); + private ChestLoot _cookedFurnace = new ChestLoot(); + private ChestLoot _rawFurnace = new ChestLoot(); - //Misc + private HashMap> _hiddenNames = new HashMap>(); + private HashSet _lootedBlocks = new HashSet(); + + // Misc private HashMap _tntMap = new HashMap(); private HashSet _placedBlocks = new HashSet(); private Location _spawn; - //Creep + // Creep private int _maxSpreadRate = 120; - private ArrayList _redLocations = new ArrayList(); + private ArrayList _frostLocations = new ArrayList(); private int _spreadType = 0; private String _spreadName = ""; private boolean _ignoreLiquids = true; private ArrayList> _spreadTypeBlocks; - private HashMap _redOutTime = new HashMap(); + private HashMap _frostOutTime = new HashMap(); - private HashMap>> _redMap = new HashMap>>(); - private HashMap> _redChunks = new HashMap>(); + private HashMap>> _frostMap = new HashMap>>(); + private HashMap> _frostChunks = new HashMap>(); - //Supply Drop + // Supply Drop private ArrayList _supplyLocations = new ArrayList(); private Location _supplyCurrent = null; private Location _supplyEffect = null; - private ArrayList _supplyChests = new ArrayList(); + private ArrayList _supplyCrates = new ArrayList(); + private HashSet _landedCrates = new HashSet(); - //Deathmatch + // Deathmatch private boolean _deathmatchCountdown = false; private boolean _deathmatchLive = false; private long _deathmatchTime = 0; - //Debug + private int _chestRefillTime = 60 * 7; + + // Debug private long totalTime = 0; - public SurvivalGames(ArcadeManager manager) + private Field _nameTagVisibility; + private Field _packetTeam; + private IPacketHandler _useEntityPacketHandler; + private int _deadBodyCount; + + private NautHashMap _openedChests = new NautHashMap(); + /** + * @The field is originally set to 1, if the next tick finds it at 1, then its set to 10. If the next tick finds it at 10 then + * it removes. + * @Else the ticks set it to 50 + */ + private Field _ticksField; + + public SurvivalGames(ArcadeManager manager) { super(manager, GameType.SurvivalGames, - new Kit[] - { - new KitAxeman(manager), - //new KitLooter(manager), - new KitKnight(manager), + new Kit[] + { + new KitAxeman(manager), + // new KitLooter(manager), + new KitKnight(manager), - new KitArcher(manager), - new KitBrawler(manager), + new KitArcher(manager), - new KitAssassin(manager), - new KitBeastmaster(manager), - new KitBomber(manager), - new KitNecromancer(manager), - - new KitHorseman(manager) - }, + new KitBrawler(manager), - new String[] - { - "Search for chests to find loot", - "Slaughter your opponents", - "Stay away from the Deep Freeze!", - "Last tribute alive wins!" - }); - - _help = new String[] - { - C.cGreen + "Use a Compass to find and kill enemies!", - C.cAqua + "Crouch to become invisible to Compass tracking!", - C.cGreen + "Avoid the Deep Freeze at all costs!", - C.cAqua + "Use TNT & Tripwires to make traps!", - C.cGreen + "You lose Speed 2 at start of game if you attack.", - C.cAqua + "Avoid enemies who have better gear than you!", - C.cGreen + "Compass finds Supply Drops during night time.", - C.cAqua + "Compass finds Players during day time.", - }; + new KitAssassin(manager), - //Manager.GetAntiStack().SetEnabled(false); + new KitBeastmaster(manager), + + new KitBomber(manager), + + new KitNecromancer(manager), + + new KitHorseman(manager) + }, + + new String[] + { + "Search for chests to find loot", "Slaughter your opponents", "Stay away from the Deep Freeze!", + "Last tribute alive wins!" + }); + + _help = new String[] + { + C.cGreen + "Use a Compass to find and kill enemies!", + + C.cGreen + "Avoid the Deep Freeze at all costs!", + + C.cGreen + "You lose Speed 2 at start of game if you attack.", + + C.cAqua + "Avoid enemies who have better gear than you!" + }; + + // Manager.GetAntiStack().SetEnabled(false); this.StrictAntiHack = true; - + this.GameTimeout = 9600000; - + this.QuitDropItems = true; - + this.WorldTimeSet = 0; - this.WorldBoundaryKill = false; - + this.WorldBoundaryKill = false; + this.SpawnDistanceRequirement = 48; this.DamageSelf = true; @@ -171,39 +224,51 @@ public class SurvivalGames extends SoloGame this.ItemDrop = true; this.ItemPickup = true; - + this.InventoryClick = true; this.InventoryOpenBlock = true; this.InventoryOpenChest = true; - this.CompassEnabled = false; //XXX - - //Blocks - this.BlockBreakAllow.add(46); //TNT + // Blocks + this.BlockBreakAllow.add(46); // TNT this.BlockPlaceAllow.add(46); - this.BlockBreakAllow.add(30); //Web + this.BlockBreakAllow.add(30); // Web this.BlockPlaceAllow.add(30); - this.BlockBreakAllow.add(132); //Tripwire + this.BlockBreakAllow.add(132); // Tripwire this.BlockPlaceAllow.add(132); - this.BlockBreakAllow.add(131); //Wire Hook + this.BlockBreakAllow.add(131); // Wire Hook this.BlockPlaceAllow.add(131); - this.BlockBreakAllow.add(55); //Redstone Dust + this.BlockBreakAllow.add(55); // Redstone Dust this.BlockPlaceAllow.add(55); - this.BlockBreakAllow.add(72); //Wood Pressure Plate + this.BlockBreakAllow.add(72); // Wood Pressure Plate this.BlockPlaceAllow.add(72); - this.BlockBreakAllow.add(69); //Lever + this.BlockBreakAllow.add(69); // Lever this.BlockPlaceAllow.add(69); - this.BlockBreakAllow.add(18); //Leaves + this.BlockBreakAllow.add(18); // Leaves - //SPREAD - _spreadType = 1;//UtilMath.r(3); + BlockBreakAllow.add(Material.LONG_GRASS.getId()); + BlockBreakAllow.add(Material.RED_ROSE.getId()); + BlockBreakAllow.add(Material.YELLOW_FLOWER.getId()); + BlockBreakAllow.add(Material.BROWN_MUSHROOM.getId()); + BlockBreakAllow.add(Material.RED_MUSHROOM.getId()); + BlockBreakAllow.add(Material.DEAD_BUSH.getId()); + BlockBreakAllow.add(Material.CARROT.getId()); + BlockBreakAllow.add(Material.POTATO.getId()); + BlockBreakAllow.add(Material.DOUBLE_PLANT.getId()); + BlockBreakAllow.add(Material.CROPS.getId()); + BlockBreakAllow.add(Material.SAPLING.getId()); + BlockBreakAllow.add(Material.VINE.getId()); + BlockBreakAllow.add(Material.WATER_LILY.getId()); + + // SPREAD + _spreadType = 1;// UtilMath.r(3); _spreadTypeBlocks = new ArrayList>(); @@ -235,14 +300,179 @@ public class SurvivalGames extends SoloGame System.out.println("==================="); System.out.println("CREEP TYPE: " + _spreadName); System.out.println("==================="); - //Manager.GetStatsManager().addTable(GetName(), "kills", "deaths", "chestsOpened"); + // Manager.GetStatsManager().addTable(GetName(), "kills", "deaths", "chestsOpened"); - registerStatTrackers( - new WinWithoutWearingArmorStatTracker(this), - new KillsWithinTimeLimitStatTracker(this, 3, 60, "Bloodlust"), - new FirstSupplyDropOpenStatTracker(this), - new SimultaneousSkeletonStatTracker(this, 5) - ); + setupLoot(); + + try + { + + _packetTeam = Class.forName("org.bukkit.craftbukkit.v1_7_R4.scoreboard.CraftTeam").getDeclaredField("team"); + _packetTeam.setAccessible(true); + + _nameTagVisibility = PacketPlayOutScoreboardTeam.class.getDeclaredField("_nameTagVisibility"); + _nameTagVisibility.setAccessible(true); + + _ticksField = TileEntityChest.class.getDeclaredField("ticks"); + _ticksField.setAccessible(true); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + _useEntityPacketHandler = new IPacketHandler() + { + @Override + public void handle(PacketInfo packetInfo) + { + if (packetInfo.getPacket() instanceof PacketPlayInUseEntity) + { + net.minecraft.server.v1_7_R4.Entity entity = ((PacketPlayInUseEntity) packetInfo.getPacket()) + .a(((CraftWorld) packetInfo.getPlayer().getWorld()).getHandle()); + + if (entity instanceof EntityArrow) + { + packetInfo.setCancelled(true); + } + } + } + }; + + registerStatTrackers(new WinWithoutWearingArmorStatTracker(this), new KillsWithinTimeLimitStatTracker(this, 3, 60, + "Bloodlust"), new FirstSupplyDropOpenStatTracker(this), new SimultaneousSkeletonStatTracker(this, 5)); + } + + @EventHandler + public void handleEntityPacket(GameStateChangeEvent event) + { + if (event.GetState() == GameState.Live) + { + getArcadeManager().getPacketHandler().addPacketHandler(_useEntityPacketHandler); + } + else if (event.GetState() == GameState.Dead) + { + getArcadeManager().getPacketHandler().removePacketHandler(_useEntityPacketHandler); + } + } + + @Override + public boolean isPlaySoundGameStart() + { + return false; + } + + private void setupLoot() + { + // Food + _baseLoot.registerLoot(new RandomItem(Material.RAW_FISH, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.RAW_BEEF, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.RAW_CHICKEN, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.POTATO_ITEM, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.CARROT_ITEM, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.RED_MUSHROOM, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.BROWN_MUSHROOM, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.WHEAT, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.APPLE, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.PORK, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(new ItemStack(Material.INK_SACK, 1, (short) 3), 30, 1, 2)); // Cocoa beans + _baseLoot.registerLoot(new RandomItem(Material.ROTTEN_FLESH, 30, 1, 2)); + + // Weapons + _baseLoot.registerLoot(new RandomItem(Material.WOOD_AXE, 30)); + _baseLoot.registerLoot(new RandomItem(Material.WOOD_SWORD, 30)); + _baseLoot.registerLoot(new RandomItem(Material.STONE_AXE, 30)); + + // Leather armor + _baseLoot.registerLoot(new RandomItem(Material.LEATHER_BOOTS, 30)); + _baseLoot.registerLoot(new RandomItem(Material.LEATHER_CHESTPLATE, 30)); + _baseLoot.registerLoot(new RandomItem(Material.LEATHER_HELMET, 30)); + _baseLoot.registerLoot(new RandomItem(Material.LEATHER_LEGGINGS, 30)); + + // Chain armor + _baseLoot.registerLoot(new RandomItem(Material.CHAINMAIL_BOOTS, 30)); + _baseLoot.registerLoot(new RandomItem(Material.CHAINMAIL_CHESTPLATE, 30)); + _baseLoot.registerLoot(new RandomItem(Material.CHAINMAIL_HELMET, 30)); + _baseLoot.registerLoot(new RandomItem(Material.CHAINMAIL_LEGGINGS, 30)); + + // Throwable + _baseLoot.registerLoot(new RandomItem(Material.FISHING_ROD, 30)); + _baseLoot.registerLoot(new RandomItem(Material.BOW, 30)); + _baseLoot.registerLoot(new RandomItem(Material.ARROW, 30, 1, 5)); + _baseLoot.registerLoot(new RandomItem(Material.SNOW_BALL, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.EGG, 30, 1, 2)); + + // Misc + _baseLoot.registerLoot(new RandomItem(Material.EXP_BOTTLE, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.FLINT_AND_STEEL, 1)); + _baseLoot.registerLoot(new RandomItem(Material.COMPASS, 50)); + _baseLoot.registerLoot(new RandomItem(Material.STICK, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.BOAT, 30)); + _baseLoot.registerLoot(new RandomItem(Material.FLINT, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.FEATHER, 30, 1, 2)); + _baseLoot.registerLoot(new RandomItem(Material.GOLD_INGOT, 30, 1, 2)); + + _spawnLoot.cloneLoot(_baseLoot); + + // Food + _spawnLoot.registerLoot(new RandomItem(Material.BAKED_POTATO, 30, 1, 2)); + _spawnLoot.registerLoot(new RandomItem(Material.CAKE, 30)); + _spawnLoot.registerLoot(new RandomItem(Material.COOKED_BEEF, 30, 1, 2)); + _spawnLoot.registerLoot(new RandomItem(Material.COOKED_CHICKEN, 30, 1, 2)); + _spawnLoot.registerLoot(new RandomItem(Material.COOKED_FISH, 30, 1, 2)); + _spawnLoot.registerLoot(new RandomItem(Material.GRILLED_PORK, 30, 1, 2)); + _spawnLoot.registerLoot(new RandomItem(Material.COOKIE, 30, 1, 2)); + _spawnLoot.registerLoot(new RandomItem(Material.PUMPKIN_PIE, 30, 1, 2)); + _spawnLoot.registerLoot(new RandomItem(Material.APPLE, 30, 1, 2)); + + // Loot for chests in spawn + // Random bowl + _spawnLoot.registerLoot(new RandomItem(Material.BOWL, 30, 1, 2)); + + // Weaponry and ores + _spawnLoot.registerLoot(new RandomItem(Material.STONE_SWORD, 30)); + _spawnLoot.registerLoot(new RandomItem(Material.IRON_INGOT, 30, 1, 2)); + _spawnLoot.registerLoot(new RandomItem(Material.DIAMOND, 30)); + + // Iron gear + _spawnLoot.registerLoot(new RandomItem(Material.IRON_BOOTS, 30)); + _spawnLoot.registerLoot(new RandomItem(Material.IRON_CHESTPLATE, 30)); + _spawnLoot.registerLoot(new RandomItem(Material.IRON_HELMET, 30)); + _spawnLoot.registerLoot(new RandomItem(Material.IRON_LEGGINGS, 30)); + + // Supply crate loot + // Diamond gear + _superLoot.registerLoot(new RandomItem(Material.DIAMOND_HELMET, 3)); + _superLoot.registerLoot(new RandomItem(Material.DIAMOND_CHESTPLATE, 1)); + _superLoot.registerLoot(new RandomItem(Material.DIAMOND_LEGGINGS, 2)); + _superLoot.registerLoot(new RandomItem(Material.DIAMOND_BOOTS, 3)); + + // Iron gear + _superLoot.registerLoot(new RandomItem(Material.IRON_HELMET, 30)); + _superLoot.registerLoot(new RandomItem(Material.IRON_CHESTPLATE, 24)); + _superLoot.registerLoot(new RandomItem(Material.IRON_LEGGINGS, 27)); + _superLoot.registerLoot(new RandomItem(Material.IRON_BOOTS, 30)); + + // Weapons + _superLoot.registerLoot(new RandomItem(Material.IRON_SWORD, 24)); + _superLoot.registerLoot(new RandomItem(Material.DIAMOND_SWORD, 8)); + _superLoot.registerLoot(new RandomItem(Material.DIAMOND_AXE, 16)); + + // Cooked furnace + _cookedFurnace.registerLoot(new RandomItem(Material.COOKED_BEEF, 3, 1, 2)); + _cookedFurnace.registerLoot(new RandomItem(Material.COOKED_CHICKEN, 3, 1, 2)); + _cookedFurnace.registerLoot(new RandomItem(Material.COOKED_FISH, 3, 1, 2)); + _cookedFurnace.registerLoot(new RandomItem(Material.GRILLED_PORK, 3, 1, 2)); + _cookedFurnace.registerLoot(new RandomItem(Material.IRON_INGOT, 1, 1, 1)); + _cookedFurnace.registerLoot(new RandomItem(Material.BAKED_POTATO, 3, 1, 1)); + _cookedFurnace.registerLoot(new RandomItem(Material.PUMPKIN_PIE, 3, 1, 1)); + + // Raw furnace + _rawFurnace.registerLoot(new RandomItem(Material.RAW_BEEF, 1, 1, 2)); + _rawFurnace.registerLoot(new RandomItem(Material.RAW_CHICKEN, 1, 1, 2)); + _rawFurnace.registerLoot(new RandomItem(Material.RAW_FISH, 1, 1, 2)); + _rawFurnace.registerLoot(new RandomItem(Material.PORK, 1, 1, 2)); + _rawFurnace.registerLoot(new RandomItem(Material.POTATO_ITEM, 1, 1, 2)); } @Override @@ -252,14 +482,14 @@ public class SurvivalGames extends SoloGame } @Override - public void ParseData() + public void ParseData() { _spawn = UtilWorld.averageLocation(this.GetTeamList().get(0).GetSpawns()); for (Location loc : this.GetTeamList().get(0).GetSpawns()) loc.setYaw(UtilAlg.GetYaw(UtilAlg.getTrajectory(loc, _spawn))); - CreateChestCraftEnchant(); + setupChestsEnchantingCrafting(); _supplyLocations = WorldData.GetDataLocs("WHITE"); for (Location loc : _supplyLocations) @@ -272,35 +502,35 @@ public class SurvivalGames extends SoloGame } } - private void CreateChestCraftEnchant() + private void setupChestsEnchantingCrafting() { ArrayList chests = WorldData.GetCustomLocs("54"); System.out.println("Map Chest Locations: " + chests.size()); - //Enchants + // Enchants System.out.println("Enchanting Tables: " + Math.min(5, chests.size())); - for (int i=0 ; i<5 && !chests.isEmpty() ; i++) + for (int i = 0; i < 5 && !chests.isEmpty(); i++) { - Location loc = chests.remove(UtilMath.r(chests.size())); + Location loc = chests.remove(UtilMath.r(chests.size())); loc.getBlock().setType(Material.ENCHANTMENT_TABLE); } - //Crafting + // Crafting System.out.println("Crafting Benches: " + Math.min(10, chests.size())); - for (int i=0 ; i<10 && !chests.isEmpty() ; i++) + for (int i = 0; i < 10 && !chests.isEmpty(); i++) { - Location loc = chests.remove(UtilMath.r(chests.size())); + Location loc = chests.remove(UtilMath.r(chests.size())); loc.getBlock().setType(Material.WORKBENCH); } int spawn = 0; - //Chests + // Chests System.out.println("Chests: " + Math.min(250, chests.size())); - for (int i=0 ; i<250 && !chests.isEmpty() ; i++) + for (int i = 0; i < 250 && !chests.isEmpty(); i++) { - Location loc = chests.remove(UtilMath.r(chests.size())); + Location loc = chests.remove(UtilMath.r(chests.size())); if (UtilMath.offset2d(loc, _spawn) < 8) spawn++; @@ -336,194 +566,174 @@ public class SurvivalGames extends SoloGame while (done < 40) { - Block block = UtilBlock.getHighest(WorldData.World, WorldData.MinX + UtilMath.r(xDiff), WorldData.MinZ + UtilMath.r(zDiff), ignore); + Block block = UtilBlock.getHighest(WorldData.World, WorldData.MinX + UtilMath.r(xDiff), + WorldData.MinZ + UtilMath.r(zDiff), ignore); if (!UtilBlock.airFoliage(block) || !UtilBlock.solid(block.getRelative(BlockFace.DOWN))) continue; - block.setTypeIdAndData(54, (byte)UtilMath.r(4), true); + block.setTypeIdAndData(Material.CHEST.getId(), (byte) UtilMath.r(4), true); done++; } } + private void fillChest(Player looter, Block block) + { + _lootedBlocks.add(block.getLocation()); + + Chest chest = (Chest) block.getState(); + + chest.getBlockInventory().clear(); + + int items = 2; + if (Math.random() > 0.50) + items++; + if (Math.random() > 0.65) + items++; + if (Math.random() > 0.80) + items++; + if (Math.random() > 0.95) + items++; + + boolean spawnChest = UtilMath.offset(chest.getLocation(), _spawn) < 8; + if (spawnChest) + items += 3; + + if (GetKit(looter) instanceof KitLooter) + { + items += UtilMath.r(3); + } + + if (_supplyCrates.contains(block)) + { + items = 2; + if (Math.random() > 0.75) + items++; + if (Math.random() > 0.95) + items++; + } + + for (int i = 0; i < items; i++) + { + ItemStack item; + + if (spawnChest) + { + item = _spawnLoot.getLoot(); + } + else + { + item = GetChestItem(_supplyCrates.contains(block)); + } + + if (item.getType() == Material.COMPASS) + { + item = buildCompass(5); + } + + chest.getBlockInventory().setItem(UtilMath.r(27), item); + } + + if (_supplyCrates.contains(block)) + { + Bukkit.getPluginManager().callEvent(new SupplyChestOpenEvent(looter, block)); + } + + _supplyCrates.remove(block); + _landedCrates.add(block.getLocation()); + } + @EventHandler - private void OpenChest(PlayerInteractEvent event) + public void OpenChest(PlayerInteractEvent event) { if (event.isCancelled()) return; - if (event.getClickedBlock() == null) + Block block = event.getClickedBlock(); + + if (block == null) return; - if (!(event.getClickedBlock().getState() instanceof Chest)) + if (!IsLive()) return; - if (GetState() != GameState.Live) + if (_lootedBlocks.contains(block.getLocation())) return; - if (_openedChest.contains(event.getClickedBlock().getLocation())) - return; + BlockState state = block.getState(); - _openedChest.add(event.getClickedBlock().getLocation()); - - Chest chest = (Chest)event.getClickedBlock().getState(); - - chest.getBlockInventory().clear(); - - int count = 2; - if (Math.random() > 0.50) count++; - if (Math.random() > 0.65) count++; - if (Math.random() > 0.80) count++; - if (Math.random() > 0.95) count++; - - if (UtilMath.offset(chest.getLocation(), _spawn) < 8) - count += 3; - - if (GetKit(event.getPlayer()) instanceof KitLooter) + if (state instanceof DoubleChest) { - count += UtilMath.r(3); - } + DoubleChest doubleChest = (DoubleChest) state; - if (_supplyChests.contains(event.getClickedBlock())) + fillChest(event.getPlayer(), ((Chest) doubleChest.getLeftSide()).getBlock()); + fillChest(event.getPlayer(), ((Chest) doubleChest.getRightSide()).getBlock()); + } + else if (state instanceof Chest) { - count = 2; - if (Math.random() > 0.75) count++; - if (Math.random() > 0.95) count++; + fillChest(event.getPlayer(), block); } - - for (int i = 0; i < count; i++) - chest.getBlockInventory().setItem(UtilMath.r(27), GetChestItem(_supplyChests.contains(event.getClickedBlock()))); - - if (_supplyChests.contains(event.getClickedBlock())) + else if (state instanceof Furnace) { - Bukkit.getPluginManager().callEvent(new SupplyChestOpenEvent(event.getPlayer(), event.getClickedBlock())); + Furnace furnace = (Furnace) state; + + if (furnace.getCookTime() == 0) + { + FurnaceInventory inv = furnace.getInventory(); + + if (UtilMath.r(3) == 0) + { + int random = UtilMath.r(9); + + if (random == 0) + { + inv.setFuel(new ItemStack(Material.STICK, new Random().nextInt(2) + 1)); + } + else if (random <= 3) + { + inv.setSmelting(_rawFurnace.getLoot()); + } + else + { + inv.setResult(_cookedFurnace.getLoot()); + } + } + + _lootedBlocks.add(block.getLocation()); + } } - - _supplyChests.remove(event.getClickedBlock()); } private ItemStack GetChestItem(boolean superChest) { - if (_baseChestLoot.isEmpty()) + if (superChest) + return _superLoot.getLoot(); + + return _baseLoot.getLoot(); + } + + private String buildTime() + { + String s = ""; + + for (char c : ("" + System.nanoTime()).toCharArray()) { - //Armor - for (int i = 0; i < 10; i++) _baseChestLoot.add(new ItemStack(Material.IRON_HELMET)); - for (int i = 0; i < 3; i++) _baseChestLoot.add(new ItemStack(Material.IRON_CHESTPLATE)); - for (int i = 0; i < 5; i++) _baseChestLoot.add(new ItemStack(Material.IRON_LEGGINGS)); - for (int i = 0; i < 10; i++) _baseChestLoot.add(new ItemStack(Material.IRON_BOOTS)); - - for (int i = 0; i < 30; i++) _baseChestLoot.add(new ItemStack(Material.CHAINMAIL_HELMET)); - for (int i = 0; i < 20; i++) _baseChestLoot.add(new ItemStack(Material.CHAINMAIL_CHESTPLATE)); - for (int i = 0; i < 25; i++) _baseChestLoot.add(new ItemStack(Material.CHAINMAIL_LEGGINGS)); - for (int i = 0; i < 30; i++) _baseChestLoot.add(new ItemStack(Material.CHAINMAIL_BOOTS)); - - for (int i = 0; i < 40; i++) _baseChestLoot.add(new ItemStack(Material.GOLD_HELMET)); - for (int i = 0; i < 30; i++) _baseChestLoot.add(new ItemStack(Material.GOLD_CHESTPLATE)); - for (int i = 0; i < 35; i++) _baseChestLoot.add(new ItemStack(Material.GOLD_LEGGINGS)); - for (int i = 0; i < 40; i++) _baseChestLoot.add(new ItemStack(Material.GOLD_BOOTS)); - - for (int i = 0; i < 100; i++) _baseChestLoot.add(new ItemStack(Material.LEATHER_HELMET)); - for (int i = 0; i < 90; i++) _baseChestLoot.add(new ItemStack(Material.LEATHER_CHESTPLATE)); - for (int i = 0; i < 85; i++) _baseChestLoot.add(new ItemStack(Material.LEATHER_LEGGINGS)); - for (int i = 0; i < 100; i++) _baseChestLoot.add(new ItemStack(Material.LEATHER_BOOTS)); - - //Weapons - for (int i = 0; i < 70; i++) _baseChestLoot.add(new ItemStack(Material.WOOD_AXE)); - for (int i = 0; i < 45; i++) _baseChestLoot.add(new ItemStack(Material.GOLD_AXE)); - for (int i = 0; i < 35; i++) _baseChestLoot.add(new ItemStack(Material.STONE_AXE)); - for (int i = 0; i < 15; i++) _baseChestLoot.add(new ItemStack(Material.IRON_AXE)); - - for (int i = 0; i < 60; i++) _baseChestLoot.add(new ItemStack(Material.WOOD_SWORD)); - for (int i = 0; i < 35; i++) _baseChestLoot.add(new ItemStack(Material.GOLD_SWORD)); - for (int i = 0; i < 25; i++) _baseChestLoot.add(new ItemStack(Material.STONE_SWORD)); - for (int i = 0; i < 8; i++) _baseChestLoot.add(new ItemStack(Material.IRON_SWORD)); - - for (int i = 0; i < 45; i++) _baseChestLoot.add(new ItemStack(Material.BOW)); - for (int i = 0; i < 55; i++) _baseChestLoot.add(new ItemStack(Material.ARROW, 4)); - - for (int i = 0; i < 15; i++) _baseChestLoot.add(new ItemStack(Material.TNT, 1)); - for (int i = 0; i < 30; i++) _baseChestLoot.add(new ItemStack(Material.WEB, 2)); - - //Food - for (int i = 0; i < 40; i++) _baseChestLoot.add(new ItemStack(Material.MUSHROOM_SOUP)); - for (int i = 0; i < 50; i++) _baseChestLoot.add(new ItemStack(Material.COOKED_CHICKEN, 4)); - for (int i = 0; i < 80; i++) _baseChestLoot.add(new ItemStack(Material.RAW_BEEF, 6)); - for (int i = 0; i < 50; i++) _baseChestLoot.add(new ItemStack(Material.GRILLED_PORK, 4)); - for (int i = 0; i < 160; i++) _baseChestLoot.add(new ItemStack(Material.BREAD, 5)); - for (int i = 0; i < 40; i++) _baseChestLoot.add(new ItemStack(Material.PUMPKIN_PIE, 3)); - for (int i = 0; i < 80; i++) _baseChestLoot.add(new ItemStack(Material.COOKIE, 7)); - for (int i = 0; i < 90; i++) _baseChestLoot.add(new ItemStack(Material.ROTTEN_FLESH, 4)); - - for (int i = 0; i < 80; i++) _baseChestLoot.add(new ItemStack(Material.WHEAT, 6)); - - //Misc - for (int i = 0; i < 50; i++) _baseChestLoot.add(new ItemStack(Material.COMPASS, 1)); - for (int i = 0; i < 25; i++) _baseChestLoot.add(new ItemStack(Material.EXP_BOTTLE, 1)); - for (int i = 0; i < 50; i++) _baseChestLoot.add(new ItemStack(Material.GOLD_INGOT, 2)); - for (int i = 0; i < 30; i++) _baseChestLoot.add(new ItemStack(Material.IRON_INGOT)); - for (int i = 0; i < 5; i++) _baseChestLoot.add(new ItemStack(Material.DIAMOND)); - for (int i = 0; i < 60; i++) _baseChestLoot.add(new ItemStack(Material.STICK, 4)); - for (int i = 0; i < 80; i++) _baseChestLoot.add(new ItemStack(Material.FLINT, 6)); - for (int i = 0; i < 80; i++) _baseChestLoot.add(new ItemStack(Material.FEATHER, 6)); - for (int i = 0; i < 40; i++) _baseChestLoot.add(new ItemStack(Material.BOAT)); - for (int i = 0; i < 70; i++) _baseChestLoot.add(new ItemStack(Material.FISHING_ROD)); - - //Building Supplies - for (int i = 0; i < 45; i++) _baseChestLoot.add(new ItemStack(Material.PISTON_BASE, 4)); - - /* - String material = _baseChestLoot.get(0).getType().toString(); - double count = 0; - - for (int i = 0; i < _baseChestLoot.size(); i++) - { - if (!_baseChestLoot.get(i).getType().toString().equalsIgnoreCase(material)) - { - System.out.println(material + " - " + count + " - " + (count / _baseChestLoot.size() * 100) + "%"); - material = _baseChestLoot.get(i).getType().toString(); - count = 1; - } - else - { - count++; - } - } - - System.out.println(material + " " + (count / _baseChestLoot.size() * 100) + "%"); - */ + s += "§" + c; } - if (_superChestLoot.isEmpty()) - { - for (int i = 0; i < 3; i++) _superChestLoot.add(new ItemStack(Material.DIAMOND_HELMET)); - for (int i = 0; i < 1; i++) _superChestLoot.add(new ItemStack(Material.DIAMOND_CHESTPLATE)); - for (int i = 0; i < 2; i++) _superChestLoot.add(new ItemStack(Material.DIAMOND_LEGGINGS)); - for (int i = 0; i < 3; i++) _superChestLoot.add(new ItemStack(Material.DIAMOND_BOOTS)); + return s; + } - for (int i = 0; i < 30; i++) _superChestLoot.add(new ItemStack(Material.IRON_HELMET)); - for (int i = 0; i < 24; i++) _superChestLoot.add(new ItemStack(Material.IRON_CHESTPLATE)); - for (int i = 0; i < 27; i++) _superChestLoot.add(new ItemStack(Material.IRON_LEGGINGS)); - for (int i = 0; i < 30; i++) _superChestLoot.add(new ItemStack(Material.IRON_BOOTS)); + private ItemStack buildCompass(int uses) + { + ItemBuilder item = new ItemBuilder(Material.COMPASS); + item.setTitle(C.cWhite + "Player Tracker" + buildTime()); - for (int i = 0; i < 24; i++) _superChestLoot.add(new ItemStack(Material.IRON_SWORD)); - for (int i = 0; i < 8; i++) _superChestLoot.add(new ItemStack(Material.DIAMOND_SWORD)); - for (int i = 0; i < 16; i++) _superChestLoot.add(new ItemStack(Material.DIAMOND_AXE)); - } + item.addLore(C.cBlue + "Uses remaining: " + C.cWhite + uses); + item.addLore(C.cGray + "Use this to find the location and"); + item.addLore(C.cGray + "distance of the nearest player!"); - - ItemStack stack = _baseChestLoot.get(UtilMath.r(_baseChestLoot.size())); - if (superChest) - stack = _superChestLoot.get(UtilMath.r(_superChestLoot.size())); - - int amount = 1; - - if (stack.getType().getMaxStackSize() > 1) - amount = Math.max(1, UtilMath.r(stack.getAmount())); - - if (stack.getTypeId() == 33) - return ItemStackFactory.Instance.CreateStack(stack.getTypeId(), (byte)0, amount, "Barricade"); - - return ItemStackFactory.Instance.CreateStack(stack.getTypeId(), amount); + return item.build(); } @EventHandler @@ -532,15 +742,191 @@ public class SurvivalGames extends SoloGame if (event.GetState() != GameState.Live) return; + Scoreboard board = GetScoreboard().GetScoreboard(); + for (Player player : GetPlayers(true)) { + player.playSound(player.getLocation(), Sound.DONKEY_DEATH, 0.8F, 0); + Manager.GetCondition().Factory().Speed("Start Speed", player, player, 30, 1, false, false, false); Manager.GetCondition().Factory().HealthBoost("Start Health", player, player, 30, 1, false, false, false); player.setHealth(player.getMaxHealth()); + + Team team = board.registerNewTeam(player.getName()); + + team.setPrefix(board.getPlayerTeam(player).getPrefix()); + + team.addPlayer(player); } } + @EventHandler + public void joinMessage(PlayerJoinEvent event) + { + if (!UtilPlayer.is1_8(event.getPlayer())) + returnToHub(event.getPlayer()); + } + + @EventHandler + public void outdatedVersion(GameStateChangeEvent event) + { + for (Player player : UtilServer.getPlayers()) + { + if (!UtilPlayer.is1_8(player)) + returnToHub(player); + } + } + + public void returnToHub(Player player) + { + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cGold + C.Bold + "SurvivalGames requires you to be using Minecraft 1.8!"); + UtilPlayer.message(player, " "); + + player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 10f, 1f); + Manager.GetPortal().sendPlayerToServer(player, "Lobby"); + } + + @EventHandler + public void UpdateNametagVisibility(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + return; + + if (!IsLive()) + return; + + ArrayList alivePlayers = GetPlayers(true); + HashMap> checkedPlayers = new HashMap>(); + + for (Player target : alivePlayers) + { + + PacketPlayOutScoreboardTeam packet = null; + + try + { + ScoreboardTeam nmsTeam = (ScoreboardTeam) _packetTeam.get(target.getScoreboard().getTeam(target.getName())); + + packet = new PacketPlayOutScoreboardTeam(nmsTeam, 2); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + for (Player player : alivePlayers) + { + if (target != player) + { + boolean hideName = false; + + if (!checkedPlayers.containsKey(target) || !checkedPlayers.get(target).containsKey(player)) + { + if (target.getLocation().distance(player.getLocation()) > 16) + { + hideName = true; + } + else if (!target.hasLineOfSight(player)) + { + // no los + hideName = true; + } + + Player[] players = new Player[] + { + target, player + }; + + for (int i = 0; i <= 1; i++) + { + Player p1 = players[i]; + Player p2 = players[1 - i]; + + if (!checkedPlayers.containsKey(p1)) + { + checkedPlayers.put(p1, new HashMap()); + } + + checkedPlayers.get(p1).put(p2, hideName); + } + } + else + { + hideName = checkedPlayers.get(target).get(player); + } + + // If hiddenNames conta + if (hideName != (_hiddenNames.containsKey(player) && _hiddenNames.get(player).contains(target.getName()))) + { + if (!hideName) + { + _hiddenNames.get(player).remove(target.getName()); + } + else + { + if (!_hiddenNames.containsKey(player)) + { + _hiddenNames.put(player, new HashSet()); + } + + _hiddenNames.get(player).add(target.getName()); + } + + try + { + _nameTagVisibility.set(packet, hideName ? "never" : "always"); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + UtilPlayer.sendPacket(player, packet); + } + } + } + } + } + + @EventHandler + public void RemoveNametagInfo(PlayerQuitEvent event) + { + _hiddenNames.remove(event.getPlayer()); + deathOrQuit(event.getPlayer()); + } + + @EventHandler + public void onGameEnd(GameStateChangeEvent event) + { + if (event.GetState() != GameState.End) + return; + + new BukkitRunnable() + { + public void run() + { + if (GetState() != GameState.End) + { + cancel(); + return; + } + + for (Location loc : GetTeamList().get(0).GetSpawns()) + { + Firework firework = (Firework) loc.getWorld().spawnEntity(loc, EntityType.FIREWORK); + + FireworkMeta meta = firework.getFireworkMeta(); + + meta.addEffect(FireworkEffect.builder().withColor(Color.AQUA).with(Type.BALL).withTrail().build()); + + firework.setFireworkMeta(meta); + } + } + }.runTaskTimer(getArcadeManager().getPlugin(), 0, 60); + } + @EventHandler public void SpeedRemove(CustomDamageEvent event) { @@ -549,10 +935,29 @@ public class SurvivalGames extends SoloGame Manager.GetCondition().EndCondition(damager, null, "Start Speed"); } - //If an item spawns and no one is there to see it, does it really spawn? No. + // If an item spawns and no one is there to see it, does it really spawn? No. @EventHandler public void ItemSpawn(ItemSpawnEvent event) { + Material mat = event.getEntity().getItemStack().getType(); + + switch (mat) + { + case SEEDS: + case SAPLING: + case VINE: + case LEAVES: + case LONG_GRASS: + case RED_ROSE: + case YELLOW_FLOWER: + case DEAD_BUSH: + case WATER_LILY: + event.setCancelled(true); + return; + default: + break; + } + for (Player player : GetPlayers(true)) if (UtilMath.offset(player, event.getEntity()) < 6) return; @@ -561,52 +966,54 @@ public class SurvivalGames extends SoloGame } @EventHandler - public void RedBorderStart(GameStateChangeEvent event) + // TODO + public void frostBorderStart(GameStateChangeEvent event) { if (event.GetState() != GameState.Prepare) return; - //Start Red + // Start Red Block block; - for (int x=WorldData.MinX ; x<=WorldData.MaxX ; x++) + for (int x = WorldData.MinX; x <= WorldData.MaxX; x++) { block = WorldData.World.getHighestBlockAt(x, WorldData.MinZ); while (!UtilBlock.solid(block) && !block.isLiquid() && block.getY() > 0) block = block.getRelative(BlockFace.DOWN); if (block.getY() > 0) - _redLocations.add(block.getLocation()); + _frostLocations.add(block.getLocation()); block = WorldData.World.getHighestBlockAt(x, WorldData.MaxZ); while (!UtilBlock.solid(block) && !block.isLiquid() && block.getY() > 0) block = block.getRelative(BlockFace.DOWN); if (block.getY() > 0) - _redLocations.add(block.getLocation()); + _frostLocations.add(block.getLocation()); } - for (int z=WorldData.MinZ ; z<=WorldData.MaxZ ; z++) + for (int z = WorldData.MinZ; z <= WorldData.MaxZ; z++) { block = WorldData.World.getHighestBlockAt(WorldData.MinX, z); while (!UtilBlock.solid(block) && !block.isLiquid() && block.getY() > 0) block = block.getRelative(BlockFace.DOWN); if (block.getY() > 0) - _redLocations.add(block.getLocation()); + _frostLocations.add(block.getLocation()); block = WorldData.World.getHighestBlockAt(WorldData.MaxX, z); while (!UtilBlock.solid(block) && !block.isLiquid() && block.getY() > 0) block = block.getRelative(BlockFace.DOWN); if (block.getY() > 0) - _redLocations.add(block.getLocation()); + _frostLocations.add(block.getLocation()); } } - public int RedMax() + public int frostMax() { return _maxSpreadRate;// + (24 - GetPlayers(true).size())*2; } @EventHandler - public void RedUpdate(UpdateEvent event) + // TODO + public void frostUpdate(UpdateEvent event) { if (event.getType() != UpdateType.TICK) return; @@ -616,56 +1023,56 @@ public class SurvivalGames extends SoloGame long time = System.currentTimeMillis(); - if (_redLocations.isEmpty()) + if (_frostLocations.isEmpty()) return; - int max = Math.max(5, Math.min(RedMax(), _redLocations.size()/100)); + int max = Math.max(5, Math.min(frostMax(), _frostLocations.size() / 100)); - for (int i=0 ; i WorldData.MaxX || block.getZ() < WorldData.MinZ || block.getZ() > WorldData.MaxZ) + // Outside Boundaries + if (block.getX() < WorldData.MinX || block.getX() > WorldData.MaxX || block.getZ() < WorldData.MinZ + || block.getZ() > WorldData.MaxZ) return false; - //Not Visible + // Not Visible if (!UtilBlock.isVisible(block)) return false; - //Apply - _redLocations.add(block.getLocation()); + // Apply + _frostLocations.add(block.getLocation()); return true; } - public void RedChangeBlock(Location loc, int id, byte data) + public void frostChangeBlock(Location loc, int id, byte data) { if (!IsLive()) return; MapUtil.ChunkBlockChange(loc, id, data, false); - //Old Style + // Old Style /* if (true) { @@ -803,20 +1212,22 @@ public class SurvivalGames extends SoloGame } */ - //Non-Queue + // Non-Queue for (Player player : UtilServer.getPlayers()) { - if (Math.abs(player.getLocation().getChunk().getX() - loc.getChunk().getX()) > UtilServer.getServer().getViewDistance()) + if (Math.abs(player.getLocation().getChunk().getX() - loc.getChunk().getX()) > UtilServer.getServer() + .getViewDistance()) continue; - if (Math.abs(player.getLocation().getChunk().getZ() - loc.getChunk().getZ()) > UtilServer.getServer().getViewDistance()) + if (Math.abs(player.getLocation().getChunk().getZ() - loc.getChunk().getZ()) > UtilServer.getServer() + .getViewDistance()) continue; - if (!_redChunks.containsKey(player)) - _redChunks.put(player, new ArrayList()); + if (!_frostChunks.containsKey(player)) + _frostChunks.put(player, new ArrayList()); boolean added = false; - for (ChunkChange change : _redChunks.get(player)) + for (ChunkChange change : _frostChunks.get(player)) { if (change.Chunk.equals(loc.getChunk()))// && change.DirtyCount < 63) { @@ -826,12 +1237,13 @@ public class SurvivalGames extends SoloGame } } if (!added) - _redChunks.get(player).add(new ChunkChange(loc, id, data)); + _frostChunks.get(player).add(new ChunkChange(loc, id, data)); } } @EventHandler - public void RedChunkUpdate(UpdateEvent event) + // TODO + public void frostChunkUpdate(UpdateEvent event) { if (event.getType() != UpdateType.FAST) return; @@ -839,47 +1251,49 @@ public class SurvivalGames extends SoloGame if (!IsLive()) return; - for (Player player : _redChunks.keySet()) + for (Player player : _frostChunks.keySet()) { - //Remove Far Away - Iterator chunkIterator = _redChunks.get(player).iterator(); + // Remove Far Away + Iterator chunkIterator = _frostChunks.get(player).iterator(); while (chunkIterator.hasNext()) { ChunkChange change = chunkIterator.next(); - if (Math.abs(player.getLocation().getChunk().getX() - change.Chunk.getX()) > UtilServer.getServer().getViewDistance() || - Math.abs(player.getLocation().getChunk().getZ() - change.Chunk.getZ()) > UtilServer.getServer().getViewDistance()) + if (Math.abs(player.getLocation().getChunk().getX() - change.Chunk.getX()) > UtilServer.getServer() + .getViewDistance() + || Math.abs(player.getLocation().getChunk().getZ() - change.Chunk.getZ()) > UtilServer.getServer() + .getViewDistance()) { chunkIterator.remove(); } } - if (_redChunks.get(player).isEmpty()) + if (_frostChunks.get(player).isEmpty()) continue; - //Get Fittest Chunk to Update + // Get Fittest Chunk to Update int bestId = -1; double bestScore = 0; - for (int i=0 ; i<_redChunks.get(player).size() ; i++) + for (int i = 0; i < _frostChunks.get(player).size(); i++) { - ChunkChange change = _redChunks.get(player).get(i); + ChunkChange change = _frostChunks.get(player).get(i); - //Base Score, 1 per block + // Base Score, 1 per block double score = change.Changes.size(); - //Time Score, multiply block score by 1 + 0.5 per second - score = score * (1 + (System.currentTimeMillis() - change.Time)/200d); + // Time Score, multiply block score by 1 + 0.5 per second + score = score * (1 + (System.currentTimeMillis() - change.Time) / 200d); - //Distance Divisor + // Distance Divisor double dist = 0.5; if (!player.getLocation().getChunk().equals(change.Chunk)) { int x = Math.abs(player.getLocation().getChunk().getX() - change.Chunk.getX()); int z = Math.abs(player.getLocation().getChunk().getZ() - change.Chunk.getZ()); - dist = Math.sqrt(x*x + z*z); + dist = Math.sqrt(x * x + z * z); } - score = score/(dist*dist); + score = score / (dist * dist); if (bestId == -1 || score > bestScore) { @@ -891,70 +1305,79 @@ public class SurvivalGames extends SoloGame if (bestId == -1) continue; - //Send MultiBlock or Chunk Update for Fittest Chunk - ChunkChange change = _redChunks.get(player).remove(bestId); + // Send MultiBlock or Chunk Update for Fittest Chunk + ChunkChange change = _frostChunks.get(player).remove(bestId); if (change.DirtyCount > 63) MapUtil.SendChunkForPlayer(change.Chunk.getX(), change.Chunk.getZ(), player); else - MapUtil.SendMultiBlockForPlayer(change.Chunk.getX(), change.Chunk.getZ(), change.DirtyBlocks, change.DirtyCount, change.Chunk.getWorld(), player); + MapUtil.SendMultiBlockForPlayer(change.Chunk.getX(), change.Chunk.getZ(), change.DirtyBlocks, change.DirtyCount, + change.Chunk.getWorld(), player); } } - public boolean IsRed(Block block) + public boolean isFrost(Block block) { - if (!_redMap.containsKey(block.getX())) + if (!_frostMap.containsKey(block.getX())) return false; - if (!_redMap.get(block.getX()).containsKey(block.getY())) + if (!_frostMap.get(block.getX()).containsKey(block.getY())) return false; - return _redMap.get(block.getX()).get(block.getY()).contains(block.getZ()); + return _frostMap.get(block.getX()).get(block.getY()).contains(block.getZ()); } - public void SetRed(Location loc) + public void setFrost(Location loc) { - //Save Red - if (!_redMap.containsKey(loc.getBlockX())) - _redMap.put(loc.getBlockX(), new HashMap>()); + // Save Red + if (!_frostMap.containsKey(loc.getBlockX())) + _frostMap.put(loc.getBlockX(), new HashMap>()); - if (!_redMap.get(loc.getBlockX()).containsKey(loc.getBlockY())) - _redMap.get(loc.getBlockX()).put(loc.getBlockY(), new HashSet()); + if (!_frostMap.get(loc.getBlockX()).containsKey(loc.getBlockY())) + _frostMap.get(loc.getBlockX()).put(loc.getBlockY(), new HashSet()); - _redMap.get(loc.getBlockX()).get(loc.getBlockY()).add(loc.getBlockZ()); + _frostMap.get(loc.getBlockX()).get(loc.getBlockY()).add(loc.getBlockZ()); - //Red + // Red if (_spreadType == 0) { - RedChangeBlock(loc, 159, (byte)14); + frostChangeBlock(loc, 159, (byte) 14); } - //Snow + // Snow else if (_spreadType == 1) { - if (loc.getBlock().getType() == Material.LEAVES) //RedChangeBlock(loc, 79, (byte)0); + if (loc.getBlock().getType() == Material.LEAVES) // RedChangeBlock(loc, 79, (byte)0); { } - else if (loc.getBlock().getTypeId() == 8 || loc.getBlock().getTypeId() == 9) RedChangeBlock(loc, 79, (byte)0); - else if (loc.getBlock().getTypeId() == 10 || loc.getBlock().getTypeId() == 11) RedChangeBlock(loc, 49, (byte)0); - else RedChangeBlock(loc, 80, (byte)0); + else if (loc.getBlock().getTypeId() == 8 || loc.getBlock().getTypeId() == 9) + frostChangeBlock(loc, 79, (byte) 0); + else if (loc.getBlock().getTypeId() == 10 || loc.getBlock().getTypeId() == 11) + frostChangeBlock(loc, 49, (byte) 0); + else + frostChangeBlock(loc, 80, (byte) 0); } - //Nether - else + // Nether + else { - if (loc.getBlock().getType() == Material.LEAVES) RedChangeBlock(loc, 88, (byte)0); - else if (loc.getBlock().getTypeId() == 8 || loc.getBlock().getTypeId() == 9) RedChangeBlock(loc, 49, (byte)0); + if (loc.getBlock().getType() == Material.LEAVES) + frostChangeBlock(loc, 88, (byte) 0); + else if (loc.getBlock().getTypeId() == 8 || loc.getBlock().getTypeId() == 9) + frostChangeBlock(loc, 49, (byte) 0); else { double r = Math.random(); - if (r > 0.1) RedChangeBlock(loc, 87, (byte)0); - else RedChangeBlock(loc, 153, (byte)0); - } + if (r > 0.1) + frostChangeBlock(loc, 87, (byte) 0); + else + frostChangeBlock(loc, 153, (byte) 0); + } } } @EventHandler - public void RedAttack(UpdateEvent event) + // TODO + public void frostAttack(UpdateEvent event) { if (event.getType() != UpdateType.FASTER) return; @@ -965,12 +1388,12 @@ public class SurvivalGames extends SoloGame for (Block block : UtilBlock.getInRadius(player.getLocation(), 5d).keySet()) { - if (!IsRed(block)) + if (!isFrost(block)) continue; near = true; - //Red + // Red if (_spreadType == 0) { if (block.getRelative(BlockFace.UP).getType() == Material.AIR) @@ -980,23 +1403,26 @@ public class SurvivalGames extends SoloGame } } - //Snow + // Snow else if (_spreadType == 1) { if (Math.random() > 0.95) player.playEffect(block.getLocation().add(0, 1, 0), Effect.STEP_SOUND, Material.SNOW_BLOCK); if (Math.random() > 0.8) - { + { Vector traj = UtilAlg.getTrajectory(block.getLocation().add(0.5, 1.5, 0.5), player.getLocation()); - Snowball ball = player.getWorld().spawn(block.getLocation().add(0.5, 1.5, 0.5).subtract(traj.clone().multiply(8 + UtilMath.r(8))), Snowball.class); + Snowball ball = player.getWorld().spawn( + block.getLocation().add(0.5, 1.5, 0.5).subtract(traj.clone().multiply(8 + UtilMath.r(8))), + Snowball.class); - ball.setVelocity(UtilAlg.getTrajectory(ball.getLocation(), player.getEyeLocation().add(0, 3, 0)).add(new Vector(Math.random()-0.5, Math.random()-0.5, Math.random()-0.5).multiply(0.1))); - } + ball.setVelocity(UtilAlg.getTrajectory(ball.getLocation(), player.getEyeLocation().add(0, 3, 0)).add( + new Vector(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).multiply(0.1))); + } } - //Nether + // Nether if (_spreadType == 2) { if (block.getRelative(BlockFace.UP).getType() == Material.AIR) @@ -1016,7 +1442,7 @@ public class SurvivalGames extends SoloGame while (!UtilBlock.solid(block) && block.getY() > 0) block = block.getRelative(BlockFace.DOWN); - if (IsRed(block) || block.getY() == 0) + if (isFrost(block) || block.getY() == 0) near = true; } } @@ -1031,29 +1457,111 @@ public class SurvivalGames extends SoloGame { player.getWorld().playSound(player.getLocation(), Sound.AMBIENCE_RAIN, 0.5f, 0f); - if (!_redOutTime.containsKey(player)) + if (!_frostOutTime.containsKey(player)) { - _redOutTime.put(player, System.currentTimeMillis()); - } + _frostOutTime.put(player, System.currentTimeMillis()); + } else { - if (UtilTime.elapsed(_redOutTime.get(player), 5000)) - { - Manager.GetDamage().NewDamageEvent(player, null, null, - DamageCause.VOID, 1, false, true, false, - "Hunger Games", _spreadName); + if (UtilTime.elapsed(_frostOutTime.get(player), 5000)) + { + Manager.GetDamage().NewDamageEvent(player, null, null, DamageCause.VOID, 1, false, true, false, + "Hunger Games", _spreadName); } } } else { - _redOutTime.remove(player); + _frostOutTime.remove(player); + } + } + } + + public void refillChests() + { + ArrayList list = new ArrayList(_lootedBlocks); + + _lootedBlocks.clear(); + + for (Location loc : list) + { + if (loc.getChunk().isLoaded()) + { + Block block = loc.getBlock(); + + if (_landedCrates.contains(loc)) + continue; + + if (block.getState() instanceof InventoryHolder) + { + InventoryHolder holder = (InventoryHolder) block.getState(); + + if (!holder.getInventory().getViewers().isEmpty()) + { + fillChest((Player) holder.getInventory().getViewers().get(0), block); + } + } } } } @EventHandler - public void RedDamage(CustomDamageEvent event) + public void chestRefill(UpdateEvent event) + { + if (!IsLive() || event.getType() != UpdateType.SEC) + return; + + if (_deathmatchCountdown || _deathmatchLive) + return; + + if (_chestRefillTime > 0) + { + _chestRefillTime--; + switch (_chestRefillTime) + { + case 0: + + Bukkit.broadcastMessage(ChatColor.GOLD + "➽" + ChatColor.GREEN + " The chests has been refilled!"); + + for (Player player : Bukkit.getOnlinePlayers()) + { + player.playSound(player.getEyeLocation(), Sound.IRONGOLEM_DEATH, 1000, 0); + } + + refillChests(); + break; + case 1: + case 2: + case 3: + case 4: + case 5: + case 10: + case 15: + case 30: + case 60: + case 120: + case 180: + case 300: + + String time; + + if (_chestRefillTime >= 60) + time = (_chestRefillTime / 60) + " minute" + (_chestRefillTime > 60 ? "s" : ""); + else + time = _chestRefillTime + " second" + (_chestRefillTime != 1 ? "s" : ""); + + Bukkit.broadcastMessage(ChatColor.GOLD + "➽" + ChatColor.GREEN + " The chests will be refilled in " + time); + + break; + default: + break; + } + } + } + + @EventHandler + // TODO + public void frostDamage(CustomDamageEvent event) { if (event.GetProjectile() == null) return; @@ -1066,29 +1574,6 @@ public class SurvivalGames extends SoloGame event.AddKnockback("Snowball", 4); } - @EventHandler - public void DayNightCycle(UpdateEvent event) - { - if (!IsLive()) - return; - - if (event.getType() != UpdateType.TICK) - return; - - long time = WorldData.World.getTime(); - - if (time > 22000 || time < 14000) - { - WorldTimeSet = (WorldTimeSet + 4)%24000; - } - else - { - WorldTimeSet = (WorldTimeSet + 16)%24000; - } - - WorldData.World.setTime(WorldTimeSet); - } - @EventHandler public void SupplyDrop(UpdateEvent event) { @@ -1109,18 +1594,19 @@ public class SurvivalGames extends SoloGame _supplyCurrent = _supplyLocations.remove(UtilMath.r(_supplyLocations.size())); - //Remove Prior - _supplyChests.remove(_supplyCurrent.getBlock().getRelative(BlockFace.UP)); + // Remove Prior + _supplyCrates.remove(_supplyCurrent.getBlock().getRelative(BlockFace.UP)); _supplyCurrent.getBlock().getRelative(BlockFace.UP).setType(Material.AIR); - //Create New + // Create New _supplyCurrent.getBlock().setType(Material.BEACON); - for (int x=-1 ; x<=1 ; x++) - for (int z=-1 ; z<=1 ; z++) + for (int x = -1; x <= 1; x++) + for (int z = -1; z <= 1; z++) _supplyCurrent.getBlock().getRelative(x, -1, z).setType(Material.IRON_BLOCK); - //Announce - this.Announce(C.cYellow + C.Bold + "Supply Drop Incoming (" + ChatColor.RESET + UtilWorld.locToStrClean(_supplyCurrent) + C.cYellow + C.Bold + ")"); + // Announce + this.Announce(C.cYellow + C.Bold + "Supply Drop Incoming (" + ChatColor.RESET + + UtilWorld.locToStrClean(_supplyCurrent) + C.cYellow + C.Bold + ")"); } } else @@ -1133,23 +1619,25 @@ public class SurvivalGames extends SoloGame _supplyEffect.setY(250); } - FireworkEffect effect = FireworkEffect.builder().flicker(false).withColor(Color.YELLOW).with(Type.BURST).trail(false).build(); + FireworkEffect effect = FireworkEffect.builder().flicker(false).withColor(Color.YELLOW).with(Type.BURST) + .trail(false).build(); UtilFirework.playFirework(_supplyEffect, effect); - _supplyEffect.setY(_supplyEffect.getY()-2); + _supplyEffect.setY(_supplyEffect.getY() - 2); if (UtilMath.offset(_supplyEffect, _supplyCurrent) < 2) { - effect = FireworkEffect.builder().flicker(false).withColor(Color.YELLOW).with(Type.BALL_LARGE).trail(true).build(); + effect = FireworkEffect.builder().flicker(false).withColor(Color.YELLOW).with(Type.BALL_LARGE).trail(true) + .build(); UtilFirework.playFirework(_supplyEffect, effect); - //Create Chest + // Create Chest _supplyCurrent.getBlock().setType(Material.GLASS); _supplyCurrent.getBlock().getRelative(BlockFace.UP).setType(Material.CHEST); - _supplyChests.add(_supplyCurrent.getBlock().getRelative(BlockFace.UP)); - _openedChest.remove(_supplyCurrent); + _supplyCrates.add(_supplyCurrent.getBlock().getRelative(BlockFace.UP)); + _lootedBlocks.remove(_supplyCurrent); - //Reset + // Reset _supplyEffect = null; _supplyCurrent = null; } @@ -1157,6 +1645,29 @@ public class SurvivalGames extends SoloGame } } + @EventHandler + public void DayNightCycle(UpdateEvent event) + { + if (!IsLive()) + return; + + if (event.getType() != UpdateType.TICK) + return; + + long time = WorldData.World.getTime(); + + if (time > 22000 || time < 14000) + { + WorldTimeSet = (WorldTimeSet + 4) % 24000; + } + else + { + WorldTimeSet = (WorldTimeSet + 16) % 24000; + } + + WorldData.World.setTime(WorldTimeSet); + } + @EventHandler public void SupplyGlow(UpdateEvent event) { @@ -1166,10 +1677,10 @@ public class SurvivalGames extends SoloGame if (event.getType() != UpdateType.TICK) return; - if (_supplyChests.isEmpty()) + if (_supplyCrates.isEmpty()) return; - Iterator chestIterator = _supplyChests.iterator(); + Iterator chestIterator = _supplyCrates.iterator(); while (chestIterator.hasNext()) { @@ -1185,6 +1696,22 @@ public class SurvivalGames extends SoloGame } } + @EventHandler + public void preventBucketCraft(PrepareItemCraftEvent event) + { + ItemStack result = event.getInventory().getResult(); + + if (result != null) + { + Material type = result.getType(); + + if (type == Material.BUCKET) + { + event.getInventory().setResult(new ItemStack(Material.AIR)); + } + } + } + @EventHandler public void DeathmatchUpdate(UpdateEvent event) { @@ -1218,18 +1745,18 @@ public class SurvivalGames extends SoloGame long timeLeft = 60000 - (System.currentTimeMillis() - _deathmatchTime); if (timeLeft <= 0) - { + { _deathmatchLive = true; - GetTeamList().get(0).SpawnTeleport(); + GetTeamList().get(0).SpawnTeleport(false); - _redLocations.clear(); + _frostLocations.clear(); for (Block block : UtilBlock.getInRadius(_spawn, 52d).keySet()) - RedSpread(block); + frostSpread(block); _deathmatchTime = 10; - } + } } else { @@ -1286,9 +1813,9 @@ public class SurvivalGames extends SoloGame { if (!event.getMessage().equalsIgnoreCase("/dm")) return; - + event.setCancelled(true); - + if (!IsAlive(event.getPlayer())) { UtilPlayer.message(event.getPlayer(), F.main("Game", "You are not in the game.")); @@ -1330,91 +1857,175 @@ public class SurvivalGames extends SoloGame } @EventHandler - public void CompassUpdate(UpdateEvent event) + public void chestTickEvent(UpdateEvent event) { - if (event.getType() != UpdateType.SEC) + if (event.getType() != UpdateType.SLOW) return; - if (!IsLive()) - return; + Iterator> itel = _openedChests.entrySet().iterator(); - //Night Time > Drop Target - if (WorldData.World.getTime() > 14000 && WorldData.World.getTime() < 23000 && _supplyCurrent != null) + while (itel.hasNext()) { - for (Player player : GetPlayers(true)) + Entry entry = itel.next(); + // TODO Test this is removed properly when unloaded chunks + // TODO Load chests status when chunk loads packets + try { - player.setCompassTarget(_supplyCurrent); + int key = (entry.getKey().x + entry.getKey().y + entry.getKey().z) % 200; - for (int i : player.getInventory().all(Material.COMPASS).keySet()) + int ticks = (_ticksField.getInt(entry.getKey()) + key) % 200; + + System.out.print(ticks + " - " + entry.getKey().o); + + if (ticks == entry.getValue()) { - ItemStack stack = player.getInventory().getItem(i); + if (ticks == 1) + { + System.out.print("Removed"); + itel.remove(); + } + else + { + _ticksField.setInt(entry.getKey(), (200 - key) + ticks - 1); + _openedChests.put(entry.getKey(), ticks - 1); + } + } + else + { + _ticksField.setInt(entry.getKey(), (200 - key) + 10); + System.out.print((_ticksField.getInt(entry.getKey()) + key)); + _openedChests.put(entry.getKey(), 10); + } + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + } - ItemMeta itemMeta = stack.getItemMeta(); - itemMeta.setDisplayName( - C.cWhite + C.Bold + "Supply Drop Location: " + C.cYellow + UtilMath.trim(1, UtilMath.offset(player.getLocation(), _supplyCurrent))); - stack.setItemMeta(itemMeta); + @EventHandler + public void chestCloseEvent(InventoryCloseEvent event) + { + InventoryHolder holder = event.getInventory().getHolder(); - player.getInventory().setItem(i, stack); + if (holder instanceof DoubleChest) + { + holder = (Chest) ((DoubleChest) holder).getLeftSide(); + } + + if (holder instanceof Chest) + { + Block block = ((Chest) holder).getBlock(); + + TileEntity tileEntity = ((CraftWorld) block.getWorld()).getTileEntityAt(block.getX(), block.getY(), block.getZ()); + + if (tileEntity instanceof TileEntityChest) + { + TileEntityChest chest = (TileEntityChest) tileEntity; + + try + { + chest.o = 10; + + int key = (chest.x + chest.y + chest.z) % 200; + + _ticksField.setInt(chest, (200 - key) + 10); + + _openedChests.put(chest, 10); + } + catch (Exception ex) + { + ex.printStackTrace(); } } } - //Player Target - else + } + + @EventHandler + public void onUse(PlayerInteractEvent event) + { + if (!IsLive()) + return; + + Player player = event.getPlayer(); + + if (!IsAlive(player)) + return; + + if (!event.getAction().name().contains("RIGHT")) + return; + + ItemStack item = event.getItem(); + + if (item == null || item.getType() != Material.COMPASS) + return; + + int uses = Integer.parseInt(ChatColor.stripColor(item.getItemMeta().getLore().get(0)).replaceAll("\\D+", "")); + + if (uses > 0) { - for (Player player : GetPlayers(true)) - { - Player target = null; - double bestDist = 0; + uses--; - for (Player other : Manager.GetGame().GetPlayers(true)) + Player closest = null; + double cDist = 0; + + for (Player p : GetPlayers(true)) + { + if (p != player) { - if (other.equals(player)) - continue; + double dist = p.getLocation().distance(player.getLocation()); - if (other.isSneaking()) - continue; - - double dist = UtilMath.offset(player, other); - - if (target == null || dist < bestDist) + if (dist > 10 && (closest == null || dist < cDist)) { - target = other; - bestDist = dist; - } - } - - if (target != null) - { - player.setCompassTarget(target.getLocation()); - - for (int i : player.getInventory().all(Material.COMPASS).keySet()) - { - ItemStack stack = player.getInventory().getItem(i); - - - ItemMeta itemMeta = stack.getItemMeta(); - itemMeta.setDisplayName( - " " + C.cWhite + C.Bold + "Nearest Player: " + C.cYellow + target.getName() + - " " + C.cWhite + C.Bold + "Distance: " + C.cYellow + UtilMath.trim(1, bestDist)); - stack.setItemMeta(itemMeta); - - player.getInventory().setItem(i, stack); + cDist = dist; + closest = p; } } } - } - } + + if (closest != null) + { + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1, 0); + closest.playSound(closest.getLocation(), Sound.ORB_PICKUP, 1, 0); + + player.setCompassTarget(closest.getLocation()); + player.setItemInHand(buildCompass(uses)); + + closest.sendMessage(F.main("Compass", player.getName() + " used a compass on you!")); + + player.sendMessage(F.main("Compass", "Located " + closest.getName() + " " + (int) cDist + " blocks away")); + + if (uses >= 1) + { + player.sendMessage(F.main("Compass", uses + " use" + (uses > 1 ? "s" : "") + " of the compass remaining.")); + } + else + { + player.sendMessage(F.main("Compass", "No remaining uses! Next use will break it!")); + } + } + } + else + { + player.sendMessage(F.main("Compass", "The compass breaks! No remaining uses!")); + + player.getWorld().playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 5); + + player.setItemInHand(new ItemStack(Material.AIR)); + } + } @EventHandler - public void DisallowBrewFurnace(PlayerInteractEvent event) + public void DisallowBrewingStand(PlayerInteractEvent event) { if (event.getClickedBlock() == null) return; - if (event.getClickedBlock().getType() == Material.BREWING_STAND || - event.getClickedBlock().getType() == Material.FURNACE || - event.getClickedBlock().getType() == Material.BURNING_FURNACE) + if (event.getClickedBlock().getType() == Material.BREWING_STAND) + { event.setCancelled(true); + } } @EventHandler @@ -1447,7 +2058,7 @@ public class SurvivalGames extends SoloGame Player player = event.getPlayer(); - if (!UtilInv.IsItem(player.getItemInHand(), Material.TNT, (byte)0)) + if (!UtilInv.IsItem(player.getItemInHand(), Material.TNT, (byte) 0)) return; event.setCancelled(true); @@ -1460,15 +2071,16 @@ public class SurvivalGames extends SoloGame if (!Manager.GetGame().CanThrowTNT(player.getLocation())) { - //Inform + // Inform UtilPlayer.message(event.getPlayer(), F.main(GetName(), "You cannot use " + F.item("Throw TNT") + " here.")); return; } - UtilInv.remove(player, Material.TNT, (byte)0, 1); + UtilInv.remove(player, Material.TNT, (byte) 0, 1); UtilInv.Update(player); - TNTPrimed tnt = player.getWorld().spawn(player.getEyeLocation().add(player.getLocation().getDirection()), TNTPrimed.class); + TNTPrimed tnt = player.getWorld() + .spawn(player.getEyeLocation().add(player.getLocation().getDirection()), TNTPrimed.class); UtilAction.velocity(tnt, player.getLocation().getDirection(), 0.5, false, 0, 0.1, 10, false); @@ -1483,64 +2095,53 @@ public class SurvivalGames extends SoloGame Player player = _tntMap.remove(event.getEntity()); + /*CustomExplosion explosion = new CustomExplosion(this.getArcadeManager().GetDamage(), event.getEntity().getLocation(), + ((TNTPrimed) event.getEntity()).getYield(), "Throwing TNT"); + + explosion.setPlayer(player, true);*/ + for (Player other : UtilPlayer.getNearby(event.getEntity().getLocation(), 14)) Manager.GetCondition().Factory().Explosion("Throwing TNT", other, player, 50, 0.1, false, false); } @EventHandler - public void BlockPlace(BlockPlaceEvent event) - { - if (IsRed(event.getBlockAgainst())) + // TODO + public void BlockPlaceOnFrost(BlockPlaceEvent event) + { + if (isFrost(event.getBlockAgainst())) { event.setCancelled(true); return; } - - if (event.getItemInHand().getType() == Material.PISTON_BASE) - { - _placedBlocks.add(event.getBlock().getLocation()); - event.setCancelled(false); - - final Block block = event.getBlock(); - - UtilServer.getServer().getScheduler().scheduleSyncDelayedTask(Manager.getPlugin(), new Runnable() - { - public void run() - { - block.setType(Material.PISTON_BASE); - block.setData((byte) 6); - } - }, 0); - } } @EventHandler - public void TourneyKills(CombatDeathEvent event) - { - if (!(event.GetEvent().getEntity() instanceof Player)) - return; - - Player killed = (Player)event.GetEvent().getEntity(); - - if (event.GetLog().GetKiller() != null) - { - Player killer = UtilPlayer.searchExact(event.GetLog().GetKiller().GetName()); + public void TourneyKills(CombatDeathEvent event) + { + if (!(event.GetEvent().getEntity() instanceof Player)) + return; + + Player killed = (Player) event.GetEvent().getEntity(); + + if (event.GetLog().GetKiller() != null) + { + Player killer = UtilPlayer.searchExact(event.GetLog().GetKiller().GetName()); + + if (killer != null && !killer.equals(killed)) + { + // Manager.GetStatsManager().addStat(killer, GetName(), "kills", 1); + } + } + + if (event.GetLog().GetPlayer() != null) + { + if (killed != null) + { + // Manager.GetStatsManager().addStat(killed, GetName(), "deaths", 1); + } + } + } - if (killer != null && !killer.equals(killed)) - { - //Manager.GetStatsManager().addStat(killer, GetName(), "kills", 1); - } - } - - if (event.GetLog().GetPlayer() != null) - { - if (killed != null) - { - //Manager.GetStatsManager().addStat(killed, GetName(), "deaths", 1); - } - } - } - @EventHandler public void BlockBreak(BlockBreakEvent event) { @@ -1575,18 +2176,102 @@ public class SurvivalGames extends SoloGame event.setCancelled(true); } + private void deathOrQuit(Player player) + { + if (!IsLive()) + return; + + String name = ""; + + for (char c : ("" + _deadBodyCount++).toCharArray()) + { + name += "§" + c; + } + + try + { + + Team team = player.getScoreboard().registerNewTeam(name); + + if (_hiddenNames.containsKey(player) && !_hiddenNames.get(player).isEmpty()) + { + ScoreboardTeam nmsTeam = (ScoreboardTeam) _packetTeam.get(team); + + PacketPlayOutScoreboardTeam packet = new PacketPlayOutScoreboardTeam(nmsTeam, 2); + + Field teamName = PacketPlayOutScoreboardTeam.class.getDeclaredField("a"); + teamName.setAccessible(true); + + for (Player alive : GetPlayers(true)) + { + if (_hiddenNames.get(player).contains(alive.getName())) + { + teamName.set(packet, alive.getName()); + UtilPlayer.sendPacket(player, packet); + } + } + } + + team.setNameTagVisibility(TeamNameTagVisibility.NEVER); + team.addEntry(name); + + PacketPlayOutScoreboardTeam packet = new PacketPlayOutScoreboardTeam((ScoreboardTeam) _packetTeam.get(team), 2); + + for (Player alive : GetPlayers(false)) + { + UtilPlayer.sendPacket(alive, packet); + } + + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + GameProfile newProfile = new GameProfile(UUID.randomUUID(), name); + + newProfile.getProperties().putAll(((CraftPlayer) player).getHandle().getProfile().getProperties()); + + DisguisePlayer disguise = new DisguisePlayer(null, newProfile); + disguise.setSleeping(BlockFace.values()[Math.round(player.getLocation().getYaw() / 90F) & 0x3].getOppositeFace()); + + getArcadeManager().GetDisguise().addFutureDisguise(disguise); + + Entity entity = player.getWorld().spawnEntity(player.getLocation(), EntityType.ARROW); + try + { + EntityArrow entityArrow = ((CraftArrow) entity).getHandle(); + + Field at = EntityArrow.class.getDeclaredField("at"); + at.setAccessible(true); + at.set(entityArrow, Integer.MIN_VALUE); // Despawn time + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + _hiddenNames.remove(player); + } + @EventHandler public void PlayerKillAward(CombatDeathEvent event) { Game game = Manager.GetGame(); - if (game == null) return; + if (game == null) + return; if (!(event.GetEvent().getEntity() instanceof Player)) return; - FireworkEffect effect = FireworkEffect.builder().flicker(false).withColor(Color.RED).with(Type.BALL_LARGE).trail(false).build(); - for (int i=0 ; i<3 ; i++) - UtilFirework.launchFirework(event.GetEvent().getEntity().getLocation(), effect, null, 3); + Player player = (Player) event.GetEvent().getEntity(); + + deathOrQuit(player); + + FireworkEffect effect = FireworkEffect.builder().flicker(false).withColor(Color.RED).with(Type.BALL_LARGE).trail(false) + .build(); + for (int i = 0; i < 3; i++) + UtilFirework.launchFirework(player.getLocation(), effect, null, 3); if (event.GetLog().GetKiller() == null) return; @@ -1595,7 +2280,7 @@ public class SurvivalGames extends SoloGame if (killer == null) return; - if (killer.equals(event.GetEvent().getEntity())) + if (killer.equals(player)) return; killer.giveExpLevels(1); @@ -1614,11 +2299,12 @@ public class SurvivalGames extends SoloGame } @EventHandler + // TODO public void FixClean(PlayerQuitEvent event) { - _redChunks.remove(event.getPlayer()); + _frostChunks.remove(event.getPlayer()); } - + @Override @EventHandler public void ScoreboardUpdate(UpdateEvent event) @@ -1632,7 +2318,7 @@ public class SurvivalGames extends SoloGame Scoreboard.Reset(); Scoreboard.WriteBlank(); - + GameTeam team = GetTeamList().get(0); if (team.GetPlayers(false).size() < 9) @@ -1665,19 +2351,18 @@ public class SurvivalGames extends SoloGame Scoreboard.Write(C.cRed + "Players Dead"); Scoreboard.Write("" + (team.GetPlayers(false).size() - team.GetPlayers(true).size())); } - - + if (_deathmatchCountdown) { if (event.getType() != UpdateType.TICK) return; long timeLeft = 60000 - (System.currentTimeMillis() - _deathmatchTime); - + Scoreboard.WriteBlank(); Scoreboard.Write(C.cYellow + C.Bold + "Deathmatch"); Scoreboard.Write(UtilTime.MakeStr(Math.max(0, timeLeft), 0)); - + } Scoreboard.Draw(); @@ -1693,13 +2378,12 @@ public class SurvivalGames extends SoloGame return true; } - + @EventHandler public void deathmatchBowShoot(EntityShootBowEvent event) { if (isDeathMatchAboutToStart()) event.getProjectile().remove(); } - - + } From 27c17eccfb97fdcfdd11af67ea0c1b0b788e4161 Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Sun, 8 Mar 2015 13:47:49 -0700 Subject: [PATCH 09/19] Disabled redis pub commands. Added getServerStatusesByPrefix to redis. Increased timeout for servers. Turned on DoubleGemWeekend --- .../mineplex/core/message/MessageManager.java | 2 ++ .../src/mineplex/core/party/PartyManager.java | 2 ++ .../src/mineplex/core/punish/Punish.java | 4 ++-- .../core/status/ServerStatusManager.java | 2 +- .../src/mineplex/core/teleport/Teleport.java | 4 +++- .../serverdata/RedisServerRepository.java | 18 +++++++++++++++--- .../mineplex/serverdata/ServerRepository.java | 2 ++ .../game/arcade/managers/GameGemManager.java | 2 +- 8 files changed, 28 insertions(+), 8 deletions(-) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/message/MessageManager.java b/Plugins/Mineplex.Core/src/mineplex/core/message/MessageManager.java index 47b1948b5..6096e46e9 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/message/MessageManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/message/MessageManager.java @@ -490,6 +490,7 @@ public class MessageManager extends MiniClientPlugin // If this is a admin message, or the sender isn't muted/ignoring the target if (adminMessage || canSenderMessageThem(sender, playerTarget)) { + /* // Construct the command to send to redis RedisMessage globalMessage = new RedisMessage(_serverName, @@ -529,6 +530,7 @@ public class MessageManager extends MiniClientPlugin // Time to send the message! globalMessage.publish(); + */ } } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/party/PartyManager.java b/Plugins/Mineplex.Core/src/mineplex/core/party/PartyManager.java index 5c334f60d..20601c066 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/party/PartyManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/party/PartyManager.java @@ -92,6 +92,7 @@ public class PartyManager extends MiniPlugin @EventHandler public void serverTransfer(ServerTransferEvent event) { + /* for (Party party : _parties) { if (party.GetLeader().equals(event.getPlayer().getName())) @@ -123,6 +124,7 @@ public class PartyManager extends MiniPlugin break; } } + */ } @EventHandler(priority = EventPriority.MONITOR) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/punish/Punish.java b/Plugins/Mineplex.Core/src/mineplex/core/punish/Punish.java index ad0cf6594..e84a1c1bd 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/punish/Punish.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/punish/Punish.java @@ -167,7 +167,7 @@ public class Punish extends MiniPlugin if (target != null) target.kickPlayer(kickReason); else - new mineplex.serverdata.transfers.PunishCommand(playerName, true, false, kickReason).publish(); + ;//new mineplex.serverdata.transfers.PunishCommand(playerName, true, false, kickReason).publish(); } }); @@ -193,7 +193,7 @@ public class Punish extends MiniPlugin target.playSound(target.getLocation(), Sound.CAT_MEOW, 1f, 1f); } else - new mineplex.serverdata.transfers.PunishCommand(playerName, false, finalDuration != 0, F.main("Punish", F.elem(C.cGray + C.Bold + (finalDuration != 0 ? "Mute" : "Warning") + " Reason: ") + reason)).publish(); + ;//new mineplex.serverdata.transfers.PunishCommand(playerName, false, finalDuration != 0, F.main("Punish", F.elem(C.cGray + C.Bold + (finalDuration != 0 ? "Mute" : "Warning") + " Reason: ") + reason)).publish(); _repository.LoadPunishClient(playerName, new Callback() { diff --git a/Plugins/Mineplex.Core/src/mineplex/core/status/ServerStatusManager.java b/Plugins/Mineplex.Core/src/mineplex/core/status/ServerStatusManager.java index f466d2c37..e8dba0b5f 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/status/ServerStatusManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/status/ServerStatusManager.java @@ -26,7 +26,7 @@ import mineplex.serverdata.transfers.SuicideCommand; public class ServerStatusManager extends MiniPlugin { // The default timeout (in seconds) before the ServerStatus expires. - public final int DEFAULT_SERVER_TIMEOUT = 15; + public final int DEFAULT_SERVER_TIMEOUT = 30; private ServerRepository _repository; private CoreClientManager _clientManager; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/teleport/Teleport.java b/Plugins/Mineplex.Core/src/mineplex/core/teleport/Teleport.java index 67dd351f0..6e13426a4 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/teleport/Teleport.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/teleport/Teleport.java @@ -46,17 +46,19 @@ public class Teleport extends MiniPlugin _serverName = getPlugin().getConfig().getString("serverstatus.name"); + /* RedisLocateHandler locateHandler = new RedisLocateHandler(this); ServerCommandManager.getInstance().registerCommandType("RedisLocate", RedisLocate.class, locateHandler); ServerCommandManager.getInstance().registerCommandType("RedisLocateCallback", RedisLocateCallback.class, locateHandler); + */ } @Override public void addCommands() { addCommand(new TeleportCommand(this)); - addCommand(new LocateCommand(this)); + //addCommand(new LocateCommand(this)); } public void handleLocateCallback(RedisLocateCallback callback) diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java index a0b5bab4f..03e4a1be7 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java @@ -51,6 +51,12 @@ public class RedisServerRepository implements ServerRepository @Override public Collection getServerStatuses() + { + return getServerStatusesByPrefix(""); + } + + @Override + public Collection getServerStatusesByPrefix(String prefix) { Collection servers = new HashSet(); Jedis jedis = _readPool.getResource(); @@ -63,8 +69,11 @@ public class RedisServerRepository implements ServerRepository List> responses = new ArrayList>(); for (String serverName : getActiveNames(setKey)) { - String dataKey = concatenate(setKey, serverName); - responses.add(pipeline.get(dataKey)); + if (prefix.isEmpty() || serverName.startsWith(prefix)) + { + String dataKey = concatenate(setKey, serverName); + responses.add(pipeline.get(dataKey)); + } } pipeline.sync(); @@ -96,7 +105,7 @@ public class RedisServerRepository implements ServerRepository return servers; } - + @Override public Collection getServersByGroup(String serverGroup) { @@ -146,6 +155,7 @@ public class RedisServerRepository implements ServerRepository @Override public void updataServerStatus(MinecraftServer serverData, int timeout) { + long time = System.currentTimeMillis(); Jedis jedis = _writePool.getResource(); try @@ -174,6 +184,8 @@ public class RedisServerRepository implements ServerRepository _writePool.returnResource(jedis); } } + + System.out.println("Finished update - " + (System.currentTimeMillis() - time) + "ms"); } @Override diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerRepository.java index cd5e4a881..1c2bd5146 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerRepository.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/ServerRepository.java @@ -18,6 +18,8 @@ public interface ServerRepository */ public Collection getServerStatuses(); + public Collection getServerStatusesByPrefix(String prefix); + public Collection getServersByGroup(String serverGroup); /** diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameGemManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameGemManager.java index 27ded40e6..7f781e56f 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameGemManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameGemManager.java @@ -30,7 +30,7 @@ public class GameGemManager implements Listener { ArcadeManager Manager; - boolean DoubleGem = false; + boolean DoubleGem = true; public GameGemManager(ArcadeManager manager) { From fbe6b294cb8c395a45d6b853093edd3bf53ed1a2 Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Sun, 8 Mar 2015 13:51:31 -0700 Subject: [PATCH 10/19] Removed redis logging. --- .../src/mineplex/serverdata/RedisServerRepository.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java index 03e4a1be7..87bd41db6 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/RedisServerRepository.java @@ -155,7 +155,6 @@ public class RedisServerRepository implements ServerRepository @Override public void updataServerStatus(MinecraftServer serverData, int timeout) { - long time = System.currentTimeMillis(); Jedis jedis = _writePool.getResource(); try @@ -184,8 +183,6 @@ public class RedisServerRepository implements ServerRepository _writePool.returnResource(jedis); } } - - System.out.println("Finished update - " + (System.currentTimeMillis() - time) + "ms"); } @Override From 3a0e597276993486d1fe2ab2c6b877a931b3f453 Mon Sep 17 00:00:00 2001 From: Cheese Date: Mon, 9 Mar 2015 22:15:24 +1100 Subject: [PATCH 11/19] more event server stuff --- .../core/gadget/types/MorphGadget.java | 8 + .../src/nautilus/game/arcade/game/Game.java | 2 + .../arcade/game/games/event/EventGame.java | 778 ++++++++++++++++-- .../game/games/event/kits/KitPlayer.java | 3 +- .../game/arcade/managers/GameChatManager.java | 11 +- .../game/arcade/managers/GameFlagManager.java | 8 + 6 files changed, 721 insertions(+), 89 deletions(-) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/gadget/types/MorphGadget.java b/Plugins/Mineplex.Core/src/mineplex/core/gadget/types/MorphGadget.java index d6b9074d5..47e121979 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/gadget/types/MorphGadget.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/gadget/types/MorphGadget.java @@ -2,6 +2,8 @@ package mineplex.core.gadget.types; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.PlayerDeathEvent; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; @@ -29,4 +31,10 @@ public abstract class MorphGadget extends Gadget if (_active.remove(player)) UtilPlayer.message(player, F.main("Gadget", "You unmorphed from " + F.elem(GetName()) + ".")); } + + @EventHandler + public void playerDeath(PlayerDeathEvent event) + { + Disable(event.getEntity()); + } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java index 317843efe..95feec423 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java @@ -155,10 +155,12 @@ public abstract class Game implements Listener public boolean DamageTeamOther = true; public boolean BlockBreak = false; + public boolean BlockBreakCreative = false; public HashSet BlockBreakAllow = new HashSet(); public HashSet BlockBreakDeny = new HashSet(); public boolean BlockPlace = false; + public boolean BlockPlaceCreative = false; public HashSet BlockPlaceAllow = new HashSet(); public HashSet BlockPlaceDeny = new HashSet(); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventGame.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventGame.java index ae0f743be..6c90a9e11 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventGame.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventGame.java @@ -1,20 +1,39 @@ package nautilus.game.arcade.game.games.event; import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; import org.bukkit.Sound; +import org.bukkit.World; import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.v1_7_R4.entity.CraftLivingEntity; import org.bukkit.craftbukkit.v1_7_R4.entity.CraftPlayer; +import org.bukkit.entity.Ageable; import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; +import org.bukkit.entity.Skeleton; +import org.bukkit.entity.Slime; +import org.bukkit.entity.Villager; +import org.bukkit.entity.Wolf; +import org.bukkit.entity.Zombie; +import org.bukkit.entity.Skeleton.SkeletonType; +import org.bukkit.entity.Villager.Profession; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerToggleFlightEvent; +import org.bukkit.inventory.ItemStack; +import mineplex.core.command.CommandCenter; import mineplex.core.common.Rank; import mineplex.core.common.util.C; import mineplex.core.common.util.F; @@ -23,6 +42,7 @@ import mineplex.core.common.util.UtilAction; import mineplex.core.common.util.UtilAlg; import mineplex.core.common.util.UtilBlock; import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilInv; import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; @@ -32,10 +52,12 @@ import mineplex.core.disguise.disguises.DisguiseChicken; import mineplex.core.disguise.disguises.DisguiseEnderman; import mineplex.core.disguise.disguises.DisguiseWither; import mineplex.core.gadget.event.GadgetActivateEvent; +import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.mount.event.MountActivateEvent; import mineplex.core.recharge.Recharge; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; +import nautilus.game.arcade.events.GameStateChangeEvent; import nautilus.game.arcade.game.GameTeam.PlayerState; import nautilus.game.arcade.game.games.event.kits.*; import nautilus.game.arcade.ArcadeManager; @@ -56,6 +78,8 @@ public class EventGame extends SoloGame private boolean _gadgetsEnabled = true; private NautHashMap _radius = new NautHashMap(); + private NautHashMap _kitItems = new NautHashMap(); + public EventGame(ArcadeManager manager) { super(manager, GameType.Event, @@ -83,7 +107,10 @@ public class EventGame extends SoloGame this.TeleportsDisqualify = false; this.PrepareFreeze = false; - + + this.BlockPlaceCreative = true; + this.BlockBreakCreative = true; + //Dont timeout this.GameTimeout = -1; @@ -97,29 +124,29 @@ public class EventGame extends SoloGame if (InProgress()) joinTeam(event.getPlayer()); } - -// @EventHandler -// public void specToTeam(UpdateEvent event) -// { -// if (!InProgress()) -// return; -// -// if (event.getType() != UpdateType.FAST) -// return; -// -// for (Player player : UtilServer.getPlayers()) -// { -// if (!GetTeamList().get(0).HasPlayer(player)) -// { -// joinTeam(player); -// } -// } -// } - + + // @EventHandler + // public void specToTeam(UpdateEvent event) + // { + // if (!InProgress()) + // return; + // + // if (event.getType() != UpdateType.FAST) + // return; + // + // for (Player player : UtilServer.getPlayers()) + // { + // if (!GetTeamList().get(0).HasPlayer(player)) + // { + // joinTeam(player); + // } + // } + // } + public void joinTeam(Player player) { Announce(C.cRed + C.Bold + player.getName() + " joined " + GetTeamList().get(0).GetName()); - + //Set Team SetPlayerTeam(player, GetTeamList().get(0), true); @@ -133,10 +160,10 @@ public class EventGame extends SoloGame other.hidePlayer(player); other.showPlayer(player); } - + //Spawn GetTeamList().get(0).SpawnTeleport(player); - + //GameMode player.setGameMode(GameMode.SURVIVAL); } @@ -158,13 +185,32 @@ public class EventGame extends SoloGame UtilPlayer.message(player, F.value("/e scoreboard [Text]", "Sets Scoreboard Text")); } + private void commandHelpSettings(Player player) + { + UtilPlayer.message(player, F.main("Event", "Displaying Settings Commands;")); + UtilPlayer.message(player, F.value("/e damage all", "Toggles All Damage")); + UtilPlayer.message(player, F.value("/e damage pvp", "Toggles PvP Damage")); + UtilPlayer.message(player, F.value("/e damage pve", "Toggles PvE Damage")); + UtilPlayer.message(player, F.value("/e damage pve", "Toggles EvP Damage")); + UtilPlayer.message(player, F.value("/e health <-1 to 20>", "Locks Players Health")); + UtilPlayer.message(player, F.value("/e hunger <-1 to 20>", "Locks Players Hunger")); + UtilPlayer.message(player, F.value("/e item drop", "Toggles Item Drop")); + UtilPlayer.message(player, F.value("/e item pickup", "Toggles Item Pickup")); + UtilPlayer.message(player, F.value("/e blockplace", "Toggles Block Placing (On/Off)")); + UtilPlayer.message(player, F.value("/e blockplace whitelist ", "Whitelists Block Place")); + UtilPlayer.message(player, F.value("/e blockplace blacklist ", "Whitelists Block Place")); + UtilPlayer.message(player, F.value("/e blockbreak", "Toggles Block Breaking (On/Off)")); + UtilPlayer.message(player, F.value("/e blockbreak whitelist ", "Whitelists Block Break")); + UtilPlayer.message(player, F.value("/e blockbreak blacklist ", "Blacklists Block Break")); + } + //Command Handler @EventHandler(priority = EventPriority.LOWEST) public void commandHandler(PlayerCommandPreprocessEvent event) { if (!InProgress()) return; - + if (!event.getMessage().toLowerCase().startsWith("/e ")) return; @@ -176,10 +222,16 @@ public class EventGame extends SoloGame //Trim off /e and split to args String[] args = event.getMessage().substring(3, event.getMessage().length()).split(" "); - if (args.length == 0) + if (args.length == 0 || args[0].equalsIgnoreCase("help")) { commandHelp(event.getPlayer()); } + else if (args[0].equalsIgnoreCase("settings")) + { + commandHelpSettings(event.getPlayer()); + } + + //XXX Commands else if (args[0].equalsIgnoreCase("tp")) { commandTeleport(event.getPlayer(), args); @@ -208,6 +260,221 @@ public class EventGame extends SoloGame { commandScoreboard(event.getPlayer(), args); } + else if (args[0].equalsIgnoreCase("whitelist")) + { + commandWhitelist(event.getPlayer(), args); + } + + + //XXX Settings + else if (event.getMessage().toLowerCase().equals("/e damage all")) + { + Damage = !Damage; + Announce(F.main("Event Settings", F.value("Damage All", F.tf(Damage)))); + } + else if (event.getMessage().toLowerCase().equals("/e damage pvp")) + { + DamagePvP = !DamagePvP; + Announce(F.main("Event Settings", F.value("Damage PvP", F.tf(DamagePvP)))); + } + else if (event.getMessage().toLowerCase().equals("/e damage pve")) + { + DamagePvE = !DamagePvE; + Announce(F.main("Event Settings", F.value("Damage PvE", F.tf(DamagePvE)))); + } + else if (event.getMessage().toLowerCase().equals("/e damage evp")) + { + DamageEvP = !DamageEvP; + Announce(F.main("Event Settings", F.value("Damage EvP", F.tf(DamageEvP)))); + } + else if (args[0].equalsIgnoreCase("health")) + { + commandHealth(event.getPlayer(), args); + } + else if (args[0].equalsIgnoreCase("hunger")) + { + commandHunger(event.getPlayer(), args); + } + else if (event.getMessage().toLowerCase().equals("/e item drop")) + { + ItemDrop = !ItemDrop; + Announce(F.main("Event Settings", F.value("Item Drop", F.tf(ItemDrop)))); + } + else if (event.getMessage().toLowerCase().equals("/e item pickup")) + { + ItemPickup = !ItemPickup; + Announce(F.main("Event Settings", F.value("Item Pickup", F.tf(ItemPickup)))); + } + else if (event.getMessage().toLowerCase().equals("/e blockplace")) + { + BlockPlace = !BlockPlace; + Announce(F.main("Event Settings", F.value("Block Place", F.tf(BlockPlace)))); + } + else if (args.length >= 4 && args[0].equalsIgnoreCase("blockplace") + && (args[1].equalsIgnoreCase("whitelist") || args[1].equalsIgnoreCase("blacklist")) + && (args[2].equalsIgnoreCase("add") || args[2].equalsIgnoreCase("remove"))) + { + commandBlockPlace(event.getPlayer(), args, args[1].equalsIgnoreCase("whitelist"), args[2].equalsIgnoreCase("add")); + } + else if (event.getMessage().toLowerCase().equals("/e blockbreak")) + { + BlockBreak = !BlockBreak; + Announce(F.main("Event Settings", F.value("Block Break", F.tf(BlockBreak)))); + } + else if (args.length >= 4 && args[0].equalsIgnoreCase("blockbreak") + && (args[1].equalsIgnoreCase("whitelist") || args[1].equalsIgnoreCase("blacklist")) + && (args[2].equalsIgnoreCase("add") || args[2].equalsIgnoreCase("remove"))) + { + commandBlockBreak(event.getPlayer(), args, args[1].equalsIgnoreCase("whitelist"), args[2].equalsIgnoreCase("add")); + } + } + + private void commandBlockPlace(Player player, String[] args, boolean whitelist, boolean add) + { + try + { + int blockId = Integer.parseInt(args[3]); + + if (whitelist) + { + if (add) + { + BlockPlaceAllow.add(blockId); + UtilPlayer.message(player, F.main("Event Settings", F.value("Block Place Whitelist", "Added " + blockId))); + } + else + { + BlockPlaceAllow.remove(blockId); + UtilPlayer.message(player, F.main("Event Settings", F.value("Block Place Whitelist", "Removed " + blockId))); + } + } + else + { + if (add) + { + BlockPlaceDeny.add(blockId); + UtilPlayer.message(player, F.main("Event Settings", F.value("Block Place Blacklist", "Added " + blockId))); + } + else + { + BlockPlaceDeny.remove(blockId); + UtilPlayer.message(player, F.main("Event Settings", F.value("Block Place Blacklist", "Removed " + blockId))); + } + } + + return; + } + catch (Exception e) + { + + } + + commandHelpSettings(player); + } + + private void commandBlockBreak(Player player, String[] args, boolean whitelist, boolean add) + { + try + { + int blockId = Integer.parseInt(args[3]); + + if (whitelist) + { + if (add) + { + BlockBreakAllow.add(blockId); + UtilPlayer.message(player, F.main("Event Settings", F.value("Block Break Whitelist", "Added " + blockId))); + } + else + { + BlockBreakAllow.remove(blockId); + UtilPlayer.message(player, F.main("Event Settings", F.value("Block Break Whitelist", "Removed " + blockId))); + } + } + else + { + if (add) + { + BlockBreakDeny.add(blockId); + UtilPlayer.message(player, F.main("Event Settings", F.value("Block Break Blacklist", "Added " + blockId))); + } + else + { + BlockBreakDeny.remove(blockId); + UtilPlayer.message(player, F.main("Event Settings", F.value("Block Break Blacklist", "Removed " + blockId))); + } + } + + return; + } + catch (Exception e) + { + + } + + commandHelpSettings(player); + } + + private void commandHealth(Player player, String[] args) + { + try + { + if (args.length >= 2) + { + int health = Integer.parseInt(args[1]); + + if (health <= 0) + health = -1; + if (health > 20) + health = 20; + + HealthSet = health; + + if (HealthSet == -1) + Announce(F.main("Event Settings", F.value("Health Set", "Disabled"))); + else + Announce(F.main("Event Settings", F.value("Health Set", HealthSet + ""))); + + return; + } + } + catch (Exception e) + { + + } + + commandHelpSettings(player); + } + + private void commandHunger(Player player, String[] args) + { + try + { + if (args.length >= 2) + { + int hunger = Integer.parseInt(args[1]); + + if (hunger <= 0) + hunger = -1; + if (hunger > 20) + hunger = 20; + + HungerSet = hunger; + + if (HungerSet == -1) + Announce(F.main("Event Settings", F.value("Hunger Set", "Disabled"))); + else + Announce(F.main("Event Settings", F.value("Hunger Set", HungerSet + ""))); + + return; + } + } + catch (Exception e) + { + + } + + commandHelpSettings(player); } //Teleport Command (To, Here, All) @@ -258,17 +525,17 @@ public class EventGame extends SoloGame public void commandGadget(Player player, String[] args) { _gadgetsEnabled = !_gadgetsEnabled; - + if (!_gadgetsEnabled) { Manager.getCosmeticManager().getMountManager().DisableAll(); Manager.getCosmeticManager().getGadgetManager().DisableAll(); } - + for (Player other : UtilServer.getPlayers()) other.sendMessage(C.cWhite + C.Bold + "Gadgets/Mounts are now " + F.elem(_gadgetsEnabled ? C.cGreen + C.Bold + "Enabled" : C.cRed + C.Bold + "Disabled")); } - + //Silence @EventHandler public void commandSilence(Player player, String[] args) @@ -359,13 +626,6 @@ public class EventGame extends SoloGame } - //Game Settings - PvP, Blocks, etc - @EventHandler - public void commandSetting(Player player, String[] args) - { - - } - //Double Jump @EventHandler public void commandDoubleJump(Player player, String[] args) @@ -448,6 +708,335 @@ public class EventGame extends SoloGame } } + @EventHandler + public void commandWhitelist(Player player, String[] args) + { + //On and Off + if (args.length >= 2) + { + if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("of")) + { + UtilServer.getServer().setWhitelist(args[1].equalsIgnoreCase("on")); + return; + } + } + + //Add and Remove + if (args.length >= 3) + { + if (args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) + { + OfflinePlayer target = Bukkit.getOfflinePlayer(args[2]); + + if (args[1].equalsIgnoreCase("add")) + UtilServer.getServer().getWhitelistedPlayers().add(target); + else + UtilServer.getServer().getWhitelistedPlayers().remove(target); + + return; + } + } + + commandHelp(player); + } + + @EventHandler + protected void commandMob(Player caller, String[] args) + { + if (args.length == 1) + { + HashMap entMap = new HashMap(); + + int count = 0; + for (World world : UtilServer.getServer().getWorlds()) + { + for (Entity ent : world.getEntities()) + { + if (!entMap.containsKey(ent.getType())) + entMap.put(ent.getType(), 0); + + entMap.put(ent.getType(), 1 + entMap.get(ent.getType())); + count++; + } + } + + UtilPlayer.message(caller, F.main("Creature", "Listing Entities:")); + for (EntityType cur : entMap.keySet()) + { + UtilPlayer.message(caller, F.desc(UtilEnt.getName(cur), entMap.get(cur)+"")); + } + + UtilPlayer.message(caller, F.desc("Total", count+"")); + } + else + { + EntityType type = UtilEnt.searchEntity(caller, args[1], true); + + if (type == null) + return; + + UtilPlayer.message(caller, F.main("Creature", "Spawning Creature(s);")); + + //Store Args + HashSet argSet = new HashSet(); + for (int i = 2 ; i < args.length ; i++) + if (args[i].length() > 0) + argSet.add(args[i]); + + + //Search Count + int count = 1; + HashSet argHandle = new HashSet(); + for (String arg : argSet) + { + try + { + int newCount = Integer.parseInt(arg); + + if (newCount <= 0) + continue; + + //Set Count + count = newCount; + UtilPlayer.message(caller, F.desc("Amount", count+"")); + + //Flag Arg + argHandle.add(arg); + break; + } + catch (Exception e) + { + //None + } + } + for (String arg : argHandle) + argSet.remove(arg); + + //Spawn + HashSet entSet = new HashSet(); + for (int i = 0 ; i < count ; i++) + { + CreatureAllowOverride = true; + entSet.add(Manager.GetCreature().SpawnEntity(caller.getTargetBlock(null, 0).getLocation().add(0.5, 1, 0.5), type)); + CreatureAllowOverride = false; + } + + //Search Vars + for (String arg : argSet) + { + if (arg.length() == 0) + continue; + + //Baby + else if (arg.equalsIgnoreCase("baby") || arg.equalsIgnoreCase("b")) + { + for (Entity ent : entSet) + { + if (ent instanceof Ageable) + ((Ageable)ent).setBaby(); + else if (ent instanceof Zombie) + ((Zombie)ent).setBaby(true); + } + + UtilPlayer.message(caller, F.desc("Baby", "True")); + argHandle.add(arg); + } + + //Lock + else if (arg.equalsIgnoreCase("age") || arg.equalsIgnoreCase("lock")) + { + for (Entity ent : entSet) + if (ent instanceof Ageable) + { + ((Ageable)ent).setAgeLock(true); + UtilPlayer.message(caller, F.desc("Age", "False")); + } + + argHandle.add(arg); + } + + //Angry + else if (arg.equalsIgnoreCase("angry") || arg.equalsIgnoreCase("a")) + { + for (Entity ent : entSet) + if (ent instanceof Wolf) + ((Wolf)ent).setAngry(true); + + for (Entity ent : entSet) + if (ent instanceof Skeleton) + ((Skeleton)ent).setSkeletonType(SkeletonType.WITHER); + + UtilPlayer.message(caller, F.desc("Angry", "True")); + argHandle.add(arg); + } + + //Profession + else if (arg.toLowerCase().charAt(0) == 'p') + { + try + { + String prof = arg.substring(1, arg.length()); + + Profession profession = null; + for (Profession cur : Profession.values()) + if (cur.name().toLowerCase().contains(prof.toLowerCase())) + profession = cur; + + UtilPlayer.message(caller, F.desc("Profession", profession.name())); + + for (Entity ent : entSet) + if (ent instanceof Villager) + ((Villager)ent).setProfession(profession); + } + catch (Exception e) + { + UtilPlayer.message(caller, F.desc("Profession", "Invalid [" + arg + "] on " + type.name())); + } + argHandle.add(arg); + } + + //Size + else if (arg.toLowerCase().charAt(0) == 's') + { + try + { + String size = arg.substring(1, arg.length()); + + UtilPlayer.message(caller, F.desc("Size", Integer.parseInt(size)+"")); + + for (Entity ent : entSet) + if (ent instanceof Slime) + ((Slime)ent).setSize(Integer.parseInt(size)); + } + catch (Exception e) + { + UtilPlayer.message(caller, F.desc("Size", "Invalid [" + arg + "] on " + type.name())); + } + argHandle.add(arg); + } + + else if (arg.toLowerCase().charAt(0) == 'n' && arg.length() > 1) + { + try + { + String name = ""; + + for (char c : arg.substring(1, arg.length()).toCharArray()) + { + if (c != '_') + name += c; + else + name += " "; + } + + for (Entity ent : entSet) + { + if (ent instanceof CraftLivingEntity) + { + CraftLivingEntity cEnt = (CraftLivingEntity)ent; + cEnt.setCustomName(name); + cEnt.setCustomNameVisible(true); + } + } + } + catch (Exception e) + { + UtilPlayer.message(caller, F.desc("Size", "Invalid [" + arg + "] on " + type.name())); + } + argHandle.add(arg); + } + } + for (String arg : argHandle) + argSet.remove(arg); + + for (String arg : argSet) + UtilPlayer.message(caller, F.desc("Unhandled", arg)); + + //Inform + UtilPlayer.message(caller, F.main("Creature", "Spawned " + count + " " + UtilEnt.getName(type) + ".")); + } + } + + @EventHandler + public void commandGive(Player caller, String[] args) + { + ItemStackFactory.Instance.matchItem + + + //Item + LinkedList itemList = new LinkedList(); + itemList = Util().Items().matchItem(caller, name, true); + if (itemList.isEmpty()) return; + + //Player + LinkedList giveList = new LinkedList(); + + if (target.equalsIgnoreCase("all")) + { + for (Player cur : UtilServer.getPlayers()) + giveList.add(cur); + } + else + { + giveList = UtilPlayer.matchOnline(caller, target, true); + if (giveList.isEmpty()) return; + } + + + //Amount + int count = 1; + try + { + count = Integer.parseInt(amount); + + if (count < 1) + { + UtilPlayer.message(caller, F.main("Give", "Invalid Amount [" + amount + "]. Defaulting to [1].")); + count = 1; + } + } + catch (Exception e) + { + UtilPlayer.message(caller, F.main("Give", "Invalid Amount [" + amount + "]. Defaulting to [1].")); + } + + //Create + String givenList = ""; + for (Player cur : giveList) + givenList += cur.getName() + " "; + if (givenList.length() > 0) + givenList = givenList.substring(0, givenList.length()-1); + + for (Material curItem : itemList) + { + for (Player cur : giveList) + { + ItemStack stack = ItemStackFactory.Instance.CreateStack(curItem, count); + + //Give + if (UtilInv.insert(cur, stack)) + { + //Inform + if (!cur.equals(caller)) + UtilPlayer.message(cur, F.main("Give", "You received " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false)) + " from " + F.elem(caller.getName()) + ".")); + } + } + + if (target.equalsIgnoreCase("all")) + UtilPlayer.message(caller, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false)) + " to " + F.elem("ALL")) + "."); + + else if (giveList.size() > 1) + UtilPlayer.message(caller, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false)) + " to " + F.elem(givenList) + ".")); + + else + UtilPlayer.message(caller, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false)) + " to " + F.elem(giveList.getFirst().getName()) + ".")); + + + //Log + Log("Gave [" + count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false) + "] to [" + givenList + "] from [" + caller.getName() + "]."); + } + } + @EventHandler public void doubleJumpTrigger(PlayerToggleFlightEvent event) { @@ -483,7 +1072,7 @@ public class EventGame extends SoloGame { if (!_doubleJump) return; - + if (event.getType() != UpdateType.TICK) return; @@ -506,20 +1095,20 @@ public class EventGame extends SoloGame if (!_gadgetsEnabled) event.setCancelled(true); } - + @EventHandler public void mountActivate(MountActivateEvent event) { if (!_gadgetsEnabled) event.setCancelled(true); } - + @EventHandler public void forcefieldUpdate(UpdateEvent event) { if (!InProgress()) return; - + if (event.getType() != UpdateType.FASTER) return; @@ -547,7 +1136,7 @@ public class EventGame extends SoloGame Entity bottom = other; while (bottom.getVehicle() != null) bottom = bottom.getVehicle(); - + UtilAction.velocity(bottom, UtilAlg.getTrajectory2d(player, bottom), 1.6, true, 0.8, 0, 10, true); other.getWorld().playSound(other.getLocation(), Sound.CHICKEN_EGG_POP, 2f, 0.5f); } @@ -555,48 +1144,54 @@ public class EventGame extends SoloGame } } } - -// @EventHandler -// public void updateVisibility(UpdateEvent event) -// { -// if (!InProgress()) -// return; -// -// if (event.getType() != UpdateType.FAST) -// return; -// -// for (Player player : UtilServer.getPlayers()) -// { -// if (!Manager.getPreferences().Get(player).ShowPlayers) -// { -// for (Player other : UtilServer.getPlayers()) -// { -// if (player.equals(other)) -// continue; -// -// ((CraftPlayer)player).hidePlayer(other, true, false); -// } -// } -// else -// { -// for (Player other : UtilServer.getPlayers()) -// { -// if (player.equals(other)) -// continue; -// -// if ((Manager.getPreferences().Get(player).Invisibility && _mps.isAdmin(player, false)) || ) -// { -// ((CraftPlayer)other).hidePlayer(player, true, false); -// } -// else -// { -// other.showPlayer(player); -// } -// } -// } -// } -// } - + + @EventHandler(priority = EventPriority.LOW) + public void explosionBlocks(EntityExplodeEvent event) + { + event.blockList().clear(); + } + + // @EventHandler + // public void updateVisibility(UpdateEvent event) + // { + // if (!InProgress()) + // return; + // + // if (event.getType() != UpdateType.FAST) + // return; + // + // for (Player player : UtilServer.getPlayers()) + // { + // if (!Manager.getPreferences().Get(player).ShowPlayers) + // { + // for (Player other : UtilServer.getPlayers()) + // { + // if (player.equals(other)) + // continue; + // + // ((CraftPlayer)player).hidePlayer(other, true, false); + // } + // } + // else + // { + // for (Player other : UtilServer.getPlayers()) + // { + // if (player.equals(other)) + // continue; + // + // if ((Manager.getPreferences().Get(player).Invisibility && _mps.isAdmin(player, false)) || ) + // { + // ((CraftPlayer)other).hidePlayer(player, true, false); + // } + // else + // { + // other.showPlayer(player); + // } + // } + // } + // } + // } + @Override public void EndCheck() { @@ -627,12 +1222,23 @@ public class EventGame extends SoloGame Scoreboard.Draw(); } - + //This re-enables cosmetic hotbar, because MPS disables it @EventHandler(priority = EventPriority.MONITOR) - public void fixHotbarItemTemp(PlayerCommandPreprocessEvent event) + public void fixHotbarItemTemp(GameStateChangeEvent event) { - if (event.getMessage().toLowerCase().startsWith("/sethost")) - Manager.GetServerConfig().HotbarInventory = true; + Manager.GetServerConfig().HotbarInventory = true; + } + + public void giveItems(Player player) + { + UtilInv.Clear(player); + + for (Material mat : _kitItems.keySet()) + { + int amount = _kitItems.get(mat); + + player.getInventory().addItem(new ItemStack(mat, amount)); + } } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/kits/KitPlayer.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/kits/KitPlayer.java index e8e0aa5c5..bee6a44d8 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/kits/KitPlayer.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/kits/KitPlayer.java @@ -6,6 +6,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.game.games.event.EventGame; import nautilus.game.arcade.kit.Kit; import nautilus.game.arcade.kit.KitAvailability; import nautilus.game.arcade.kit.Perk; @@ -32,6 +33,6 @@ public class KitPlayer extends Kit @Override public void GiveItems(Player player) { - + ((EventGame)Manager.GetGame()).giveItems(player); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameChatManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameChatManager.java index 559a0f890..9d5cac836 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameChatManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameChatManager.java @@ -7,6 +7,7 @@ import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.party.Party; import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.GameType; import nautilus.game.arcade.game.GameTeam; import nautilus.game.arcade.game.Game.GameState; @@ -68,11 +69,17 @@ public class GameChatManager implements Listener //Rank Prefix & MPS Host Prefix if (Manager.GetGameHostManager().isHost(event.getPlayer())) { - rankStr = C.cDGreen + C.Bold + "MPS Host "; + if (Manager.GetGame() != null && Manager.GetGame().GetType() == GameType.Event) + rankStr = C.cDGreen + C.Bold + "Event Host "; + else + rankStr = C.cDGreen + C.Bold + "MPS Host "; } else if (Manager.GetGameHostManager().isAdmin(event.getPlayer(), false)) { - rankStr = C.cDGreen + C.Bold + "MPS Admin "; + if (Manager.GetGame() != null && Manager.GetGame().GetType() == GameType.Event) + rankStr = C.cDGreen + C.Bold + "Event Admin "; + else + rankStr = C.cDGreen + C.Bold + "MPS Admin "; } else { diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java index 08aabe38a..e49e92f97 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java @@ -319,6 +319,10 @@ public class GameFlagManager implements Listener if (!player.isOp() || player.getGameMode() != GameMode.CREATIVE) event.setCancelled(true); } + else if (game.BlockPlaceCreative && player.getGameMode() == GameMode.CREATIVE) // Event Server Allowance + { + return; + } else { if (game.BlockPlace) @@ -356,6 +360,10 @@ public class GameFlagManager implements Listener { event.setCancelled(true); } + else if (game.BlockBreakCreative && player.getGameMode() == GameMode.CREATIVE) // Event Server Allowance + { + return; + } else { if (game.BlockBreak) From e443b41e15fd475bba06ac63cc39751f02939bb7 Mon Sep 17 00:00:00 2001 From: Cheese Date: Mon, 9 Mar 2015 22:16:08 +1100 Subject: [PATCH 12/19] removed unfinished code --- .../arcade/game/games/event/EventGame.java | 80 ------------------- 1 file changed, 80 deletions(-) diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventGame.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventGame.java index 6c90a9e11..41e839902 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventGame.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventGame.java @@ -957,86 +957,6 @@ public class EventGame extends SoloGame } } - @EventHandler - public void commandGive(Player caller, String[] args) - { - ItemStackFactory.Instance.matchItem - - - //Item - LinkedList itemList = new LinkedList(); - itemList = Util().Items().matchItem(caller, name, true); - if (itemList.isEmpty()) return; - - //Player - LinkedList giveList = new LinkedList(); - - if (target.equalsIgnoreCase("all")) - { - for (Player cur : UtilServer.getPlayers()) - giveList.add(cur); - } - else - { - giveList = UtilPlayer.matchOnline(caller, target, true); - if (giveList.isEmpty()) return; - } - - - //Amount - int count = 1; - try - { - count = Integer.parseInt(amount); - - if (count < 1) - { - UtilPlayer.message(caller, F.main("Give", "Invalid Amount [" + amount + "]. Defaulting to [1].")); - count = 1; - } - } - catch (Exception e) - { - UtilPlayer.message(caller, F.main("Give", "Invalid Amount [" + amount + "]. Defaulting to [1].")); - } - - //Create - String givenList = ""; - for (Player cur : giveList) - givenList += cur.getName() + " "; - if (givenList.length() > 0) - givenList = givenList.substring(0, givenList.length()-1); - - for (Material curItem : itemList) - { - for (Player cur : giveList) - { - ItemStack stack = ItemStackFactory.Instance.CreateStack(curItem, count); - - //Give - if (UtilInv.insert(cur, stack)) - { - //Inform - if (!cur.equals(caller)) - UtilPlayer.message(cur, F.main("Give", "You received " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false)) + " from " + F.elem(caller.getName()) + ".")); - } - } - - if (target.equalsIgnoreCase("all")) - UtilPlayer.message(caller, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false)) + " to " + F.elem("ALL")) + "."); - - else if (giveList.size() > 1) - UtilPlayer.message(caller, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false)) + " to " + F.elem(givenList) + ".")); - - else - UtilPlayer.message(caller, F.main("Give", "You gave " + F.item(count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false)) + " to " + F.elem(giveList.getFirst().getName()) + ".")); - - - //Log - Log("Gave [" + count + " " + ItemStackFactory.Instance.GetName(curItem, (byte)0, false) + "] to [" + givenList + "] from [" + caller.getName() + "]."); - } - } - @EventHandler public void doubleJumpTrigger(PlayerToggleFlightEvent event) { From 759db08679e84ca18f5085e55cca0f2b8a06c9b7 Mon Sep 17 00:00:00 2001 From: Tim Ziankoski Date: Mon, 9 Mar 2015 17:24:01 -0400 Subject: [PATCH 13/19] Revert "Merge branch 'master' of ssh://184.154.0.242:7999/min/Mineplex" This reverts commit 2e06a272b499147ab1b612529ebf4edc5411a67f, reversing changes made to e443b41e15fd475bba06ac63cc39751f02939bb7. --- .../artifacts/Nautilus_Game_Arcade_jar.xml | 2 +- .../artifacts/Nautilus_Game_Arcade_test.xml | 1 - Plugins/.idea/copyright/profiles_settings.xml | 3 - .../Mineplex.Core.Common.iml | 4 +- .../core/common/lang/mineplex_de.properties | 1 - .../core/common/lang/mineplex_en.properties | 4 - .../src/mineplex/core/common/lang/Lang.java | 115 ------------------ .../arcade/managers/GameLobbyManager.java | 12 +- 8 files changed, 8 insertions(+), 134 deletions(-) delete mode 100644 Plugins/.idea/copyright/profiles_settings.xml delete mode 100644 Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_de.properties delete mode 100644 Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_en.properties delete mode 100644 Plugins/Mineplex.Core.Common/src/mineplex/core/common/lang/Lang.java diff --git a/Plugins/.idea/artifacts/Nautilus_Game_Arcade_jar.xml b/Plugins/.idea/artifacts/Nautilus_Game_Arcade_jar.xml index 3f5cae6e4..cd4447b88 100644 --- a/Plugins/.idea/artifacts/Nautilus_Game_Arcade_jar.xml +++ b/Plugins/.idea/artifacts/Nautilus_Game_Arcade_jar.xml @@ -17,7 +17,7 @@ - + \ No newline at end of file diff --git a/Plugins/.idea/artifacts/Nautilus_Game_Arcade_test.xml b/Plugins/.idea/artifacts/Nautilus_Game_Arcade_test.xml index 73139df16..8b3142e4c 100644 --- a/Plugins/.idea/artifacts/Nautilus_Game_Arcade_test.xml +++ b/Plugins/.idea/artifacts/Nautilus_Game_Arcade_test.xml @@ -3,7 +3,6 @@ $PROJECT_DIR$/../Testing/Arcade/plugins - \ No newline at end of file diff --git a/Plugins/.idea/copyright/profiles_settings.xml b/Plugins/.idea/copyright/profiles_settings.xml deleted file mode 100644 index e7bedf337..000000000 --- a/Plugins/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/Plugins/Mineplex.Core.Common/Mineplex.Core.Common.iml b/Plugins/Mineplex.Core.Common/Mineplex.Core.Common.iml index c145ccad3..b59695f8a 100644 --- a/Plugins/Mineplex.Core.Common/Mineplex.Core.Common.iml +++ b/Plugins/Mineplex.Core.Common/Mineplex.Core.Common.iml @@ -4,10 +4,10 @@ - - \ No newline at end of file + + diff --git a/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_de.properties b/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_de.properties deleted file mode 100644 index cb380f81e..000000000 --- a/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_de.properties +++ /dev/null @@ -1 +0,0 @@ -waiting.for.players=Warten auf Spieler diff --git a/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_en.properties b/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_en.properties deleted file mode 100644 index d99ecb4b3..000000000 --- a/Plugins/Mineplex.Core.Common/resources/mineplex/core/common/lang/mineplex_en.properties +++ /dev/null @@ -1,4 +0,0 @@ -waiting.for.players=Waiting for Players -lobby=Lobby -starting.in.0.seconds=Starting in {0} Seconds -starting.in.0.seconds.singular=Starting in {0} Second diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/lang/Lang.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/lang/Lang.java deleted file mode 100644 index cb6e3fa89..000000000 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/lang/Lang.java +++ /dev/null @@ -1,115 +0,0 @@ -package mineplex.core.common.lang; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.WeakHashMap; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -public final class Lang -{ - private static final String RESOURCE_BUNDLE_PATH = "mineplex/core/common/lang/mineplex"; - - private static final Map _playerLocales = new WeakHashMap<>(); - private static final ResourceBundle _defaultResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE_PATH); - private static final Map _localeResourceBundles = Collections.synchronizedMap(new HashMap()); - - private Lang() - { - - } - - public static void setPlayerLocale(Player player, Locale locale) - { - _playerLocales.put(player, locale); - } - - public static ResourceBundle getDefaultResourceBundle() - { - return _defaultResourceBundle; - } - - public static ResourceBundle getResourceBundle(Locale locale) - { - ResourceBundle bundle = getDefaultResourceBundle(); - - synchronized (_localeResourceBundles) - { - if (_localeResourceBundles.containsKey(locale)) - { - ResourceBundle b = _localeResourceBundles.get(locale); - if (b != null) - bundle = b; - } - else - { - try - { - bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE_PATH, locale); - _localeResourceBundles.put(locale, bundle); - } - catch (MissingResourceException e) - { - _localeResourceBundles.put(locale, null); - - Bukkit.getLogger().warning(e.getMessage()); - } - } - } - - return bundle; - } - - public static String getString(String key, int count) - { - return getString(key, (Locale) null, count); - } - - public static String getString(String key, Locale locale, int count) - { - if (key == null) - return null; - else - { - ResourceBundle bundle; - if (locale == null) - bundle = getDefaultResourceBundle(); - else - bundle = getResourceBundle(locale); - - if (count == 1) - { - String singularKey = key + ".singular"; - if (bundle.containsKey(singularKey)) - return bundle.getString(singularKey); - } - - return bundle.getString(key); - } - } - - public static String getString(String key, Player player, int count) - { - return getString(key, _playerLocales.get(player), count); - } - - public static String getString(String key) - { - return getString(key, 0); - } - - public static String getString(String key, Locale locale) - { - return getString(key, locale, 0); - } - - public static String getString(String key, Player player) - { - return getString(key, player, 0); - } -} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java index 688eaa4b8..fe3a858b4 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java @@ -1,11 +1,10 @@ package nautilus.game.arcade.managers; -import java.text.MessageFormat;import java.util.ArrayList; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; -import java.util.Locale; import java.util.Map.Entry; import org.bukkit.Bukkit; @@ -42,7 +41,6 @@ import net.minecraft.server.v1_7_R4.WatchableObject; import mineplex.core.account.CoreClient; import mineplex.core.common.Rank; -import mineplex.core.common.lang.Lang; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.MapUtil; @@ -950,18 +948,18 @@ public class GameLobbyManager implements Listener, IPacketHandler for (Entry entry : _scoreboardMap.entrySet()) { - Objective objective = entry.getValue().getObjective(C.Bold + Lang.getString("lobby", entry.getKey())); - + Objective objective = entry.getValue().getObjective("§l" + "Lobby"); + if (Manager.GetGame() != null && Manager.GetGame().GetCountdown() >= 0) { if (Manager.GetGame().GetCountdown() > 0) - objective.setDisplayName(MessageFormat.format(C.Bold + Lang.getString("starting.in.0.seconds", entry.getKey(), Manager.GetGame().GetCountdown()), C.cGreen + C.Bold + Manager.GetGame().GetCountdown())); + objective.setDisplayName(C.Bold + "§lStarting in " + C.cGreen + "§l" + Manager.GetGame().GetCountdown() + (Manager.GetGame().GetCountdown() == 1 ? " Second" : " Seconds")); else if (Manager.GetGame().GetCountdown() == 0) objective.setDisplayName(ChatColor.WHITE + "§lIn Progress..."); } else { - objective.setDisplayName(C.cGreen + C.Bold + Lang.getString("waiting.for.players", entry.getKey())); + objective.setDisplayName(ChatColor.GREEN + "§l" + "Waiting for Players"); } int line = 15; From f47447134e982921e33699db9abb2576d2222b4b Mon Sep 17 00:00:00 2001 From: libraryaddict Date: Wed, 11 Mar 2015 13:16:00 +1300 Subject: [PATCH 14/19] Cleanup hologram class, remove witherskull option for 1.8 and fix duplicate nametags and non-invisibility on armorstands --- .../src/mineplex/core/CustomTagFix.java | 5 + .../src/mineplex/core/hologram/Hologram.java | 1213 +++++++++-------- .../game/games/searchanddestroy/TeamBomb.java | 3 +- 3 files changed, 630 insertions(+), 591 deletions(-) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/CustomTagFix.java b/Plugins/Mineplex.Core/src/mineplex/core/CustomTagFix.java index 130995fde..bc4a9381f 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/CustomTagFix.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/CustomTagFix.java @@ -192,6 +192,11 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook // Ignore Armor stand packets if (spawnPacket.b == 30 || spawnPacket.l == null || spawnPacket.l.c() == null || spawnPacket.a == 777777) { + if (spawnPacket.b == 30) + { + _ignoreSkulls.add(spawnPacket.a); + } + return; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/hologram/Hologram.java b/Plugins/Mineplex.Core/src/mineplex/core/hologram/Hologram.java index 1c454ae01..7b470f779 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/hologram/Hologram.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/hologram/Hologram.java @@ -29,628 +29,663 @@ import mineplex.core.common.util.UtilPlayer; public class Hologram { - public enum HologramTarget - { - BLACKLIST, WHITELIST; - } + public enum HologramTarget + { + BLACKLIST, WHITELIST; + } - private Packet _destroy1_7; - private Packet _destroy1_8; - private boolean _destroyPackets = true; - /** - * 1.7 packets uses both EntityIDs while 1.8 uses only the first. - */ - private ArrayList> _entityIds = new ArrayList>(); - private Entity _followEntity; - private HologramManager _hologramManager; - private boolean _isWitherSkull; - /** - * Keeps track of the holograms movements. This fixes offset that occasionally happens when moving a hologram around. - */ - private Vector _lastMovement; - private Location _location; - private boolean _makePackets = true; - private Packet[] _packets1_7; - private Packet[] _packets1_8; - private HashSet _playersInList = new HashSet(); - private ArrayList _playersTracking = new ArrayList(); - private HologramTarget _target = HologramTarget.BLACKLIST; - private String[] _text = new String[0]; - private int _viewDistance = 70; - protected Vector relativeToEntity; - private boolean _removeEntityDeath; + private Packet _destroy1_7; + private Packet _destroy1_8; + /** + * 1.7 packets uses both EntityIDs while 1.8 uses only the first. + */ + private ArrayList> _entityIds = new ArrayList>(); + private Entity _followEntity; + private HologramManager _hologramManager; + private String[] _hologramText = new String[0]; + /** + * Keeps track of the holograms movements. This fixes offset that occasionally happens when moving a hologram around. + */ + private Vector _lastMovement; + private Location _location; + private boolean _makeDestroyPackets = true; + private boolean _makeSpawnPackets = true; + private Packet[] _packets1_7; + private Packet[] _packets1_8; + private HashSet _playersInList = new HashSet(); + private ArrayList _playersTracking = new ArrayList(); + private boolean _removeEntityDeath; + private HologramTarget _target = HologramTarget.BLACKLIST; + private int _viewDistance = 70; + protected Vector relativeToEntity; - public Hologram(HologramManager hologramManager, Location location, String... text) - { - _hologramManager = hologramManager; - _location = location.clone(); - setText(text); - } - - public boolean isRemoveOnEntityDeath() { - return _removeEntityDeath; - } - - public Hologram setRemoveOnEntityDeath() { - _removeEntityDeath = true; - return this; - } + public Hologram(HologramManager hologramManager, Location location, String... text) + { + _hologramManager = hologramManager; + _location = location.clone(); + setText(text); + } - /** - * Adds the player to the Hologram to be effected by Whitelist or Blacklist - */ - public Hologram addPlayer(Player player) - { - return addPlayer(player.getName()); - } + /** + * Adds the player to the Hologram to be effected by Whitelist or Blacklist + */ + public Hologram addPlayer(Player player) + { + return addPlayer(player.getName()); + } - /** - * Adds the player to the Hologram to be effected by Whitelist or Blacklist - */ - public Hologram addPlayer(String player) - { - _playersInList.add(player); - return this; - } + /** + * Adds the player to the Hologram to be effected by Whitelist or Blacklist + */ + public Hologram addPlayer(String player) + { + _playersInList.add(player); + return this; + } - /** - * Is there a player entry in the hologram for Whitelist and Blacklist - */ - public boolean containsPlayer(Player player) - { - return _playersInList.contains(player.getName()); - } + /** + * Is there a player entry in the hologram for Whitelist and Blacklist + */ + public boolean containsPlayer(Player player) + { + return _playersInList.contains(player.getName()); + } - /** - * Is there a player entry in the hologram for Whitelist and Blacklist - */ - public boolean containsPlayer(String player) - { - return _playersInList.contains(player); - } + /** + * Is there a player entry in the hologram for Whitelist and Blacklist + */ + public boolean containsPlayer(String player) + { + return _playersInList.contains(player); + } - protected Packet getDestroyPacket(Player player) - { - if (_destroyPackets) - { - makeDestroyPacket(); - _destroyPackets = false; - } - return UtilPlayer.is1_8(player) ? _destroy1_8 : _destroy1_7; - } + protected Packet getDestroyPacket(Player player) + { + if (_makeDestroyPackets) + { + makeDestroyPacket(); + _makeDestroyPackets = false; + } - public Entity getEntityFollowing() - { - return _followEntity; - } + return UtilPlayer.is1_8(player) ? _destroy1_8 : _destroy1_7; + } - /** - * Get who can see the hologram - * - * @Whitelist = Only people added can see the hologram - * @Blacklist = Anyone but people added can see the hologram - */ - public HologramTarget getHologramTarget() - { - return _target; - } + public Entity getEntityFollowing() + { + return _followEntity; + } - /** - * Get the hologram location - */ - public Location getLocation() - { - return _location.clone(); - } + /** + * Get who can see the hologram + * + * @Whitelist = Only people added can see the hologram + * @Blacklist = Anyone but people added can see the hologram + */ + public HologramTarget getHologramTarget() + { + return _target; + } - protected ArrayList getNearbyPlayers() - { - ArrayList nearbyPlayers = new ArrayList(); - for (Player player : getLocation().getWorld().getPlayers()) - { - if (isVisible(player)) - { - nearbyPlayers.add(player); - } - } - return nearbyPlayers; - } + /** + * Get the hologram location + */ + public Location getLocation() + { + return _location.clone(); + } - protected ArrayList getPlayersTracking() - { - return _playersTracking; - } + protected ArrayList getNearbyPlayers() + { + ArrayList nearbyPlayers = new ArrayList(); - protected Packet[] getSpawnPackets(Player player) - { - if (_makePackets) - { - makeSpawnPackets(); - _makePackets = false; - } - return UtilPlayer.is1_8(player) ? _packets1_8 : _packets1_7; - } + for (Player player : getLocation().getWorld().getPlayers()) + { + if (isVisible(player)) + { + nearbyPlayers.add(player); + } + } + return nearbyPlayers; + } - /** - * Get the text in the hologram - */ - public String[] getText() - { - // We reverse it again as the hologram would otherwise display the text from the bottom row to the top row - String[] reversed = new String[_text.length]; - for (int i = 0; i < reversed.length; i++) - { - reversed[i] = _text[reversed.length - (i + 1)]; - } - return reversed; - } + protected ArrayList getPlayersTracking() + { + return _playersTracking; + } - /** - * Get the view distance the hologram is viewable from. Default is 70 - */ - public int getViewDistance() - { - return _viewDistance; - } + protected Packet[] getSpawnPackets(Player player) + { + if (_makeSpawnPackets) + { + makeSpawnPackets(); + _makeSpawnPackets = false; + } - /** - * Is the hologram holograming? - */ - public boolean isInUse() - { - return _lastMovement != null; - } + return UtilPlayer.is1_8(player) ? _packets1_8 : _packets1_7; + } - /** - * Does the hologram use the wither skull for 1.8 clients? - */ - public boolean isUsingWitherSkull() - { - return _isWitherSkull; - } + /** + * Get the text in the hologram + */ + public String[] getText() + { + // We reverse it again as the hologram would otherwise display the text from the bottom row to the top row + String[] reversed = new String[_hologramText.length]; - public boolean isVisible(Player player) - { - if (getLocation().getWorld() == player.getWorld()) - { - if ((getHologramTarget() == HologramTarget.WHITELIST) == containsPlayer(player)) - { - if (getLocation().distance(player.getLocation()) < getViewDistance()) - { - return true; - } - } - } - return false; - } + for (int i = 0; i < reversed.length; i++) + { + reversed[i] = _hologramText[reversed.length - (i + 1)]; + } - private void makeDestroyPacket() - { - int[] entityIds1_7 = new int[_entityIds.size() * 2]; - int[] entityIds1_8 = new int[_entityIds.size()]; - for (int i = 0; i < _entityIds.size(); i++) - { - Entry entry = _entityIds.get(i); - entityIds1_7[i * 2] = entry.getKey(); - entityIds1_7[(i * 2) + 1] = entry.getValue(); - entityIds1_8[i] = entry.getKey(); - } - _destroy1_7 = new PacketPlayOutEntityDestroy(entityIds1_7); - _destroy1_8 = new PacketPlayOutEntityDestroy(entityIds1_8); - } + return reversed; + } - private void makeSpawnPackets() - { - _packets1_7 = new Packet[_text.length * 3]; - _packets1_8 = new Packet[_text.length * (isUsingWitherSkull() ? 2 : 1)]; - if (_entityIds.size() < _text.length) - { - _destroyPackets = true; - for (int i = _entityIds.size(); i < _text.length; i++) - { - _entityIds.add(new HashMap.SimpleEntry(UtilEnt.getNewEntityId(), UtilEnt.getNewEntityId())); - } - } - else - { - _destroyPackets = true; - while (_entityIds.size() > _text.length) - { - _entityIds.remove(_text.length); - } - } - for (int textRow = 0; textRow < _text.length; textRow++) - { - Entry entityIds = this._entityIds.get(textRow); - Packet[] packets1_7 = makeSpawnPackets1_7(textRow, entityIds.getKey(), entityIds.getValue(), _text[textRow]); - for (int i = 0; i < packets1_7.length; i++) - { - _packets1_7[(textRow * 3) + i] = packets1_7[i]; - } + /** + * Get the view distance the hologram is viewable from. Default is 70 + */ + public int getViewDistance() + { + return _viewDistance; + } - Packet[] packets1_8 = makeSpawnPackets1_8(textRow, entityIds.getKey(), _text[textRow]); - for (int i = 0; i < packets1_8.length; i++) - { - _packets1_8[(textRow * (isUsingWitherSkull() ? 2 : 1)) + i] = packets1_8[i]; - } - } - } + /** + * Is the hologram holograming? + */ + public boolean isInUse() + { + return _lastMovement != null; + } - private Packet[] makeSpawnPackets1_7(int height, int witherId, int horseId, String horseName) - { - // Spawn wither skull - PacketPlayOutSpawnEntity spawnWitherSkull = new PacketPlayOutSpawnEntity(); - spawnWitherSkull.a = witherId; - spawnWitherSkull.b = (int) (getLocation().getX() * 32); - spawnWitherSkull.c = (int) ((getLocation().getY() + 54.6 + ((double) height * 0.285D)) * 32); - spawnWitherSkull.d = (int) (getLocation().getZ() * 32); - spawnWitherSkull.j = 66; - // Spawn horse - PacketPlayOutSpawnEntityLiving spawnHorse = new PacketPlayOutSpawnEntityLiving(); - spawnHorse.a = horseId; - spawnHorse.b = 100; - spawnHorse.c = (int) (getLocation().getX() * 32); - spawnHorse.d = (int) ((getLocation().getY() + 54.83 + ((double) height * 0.285D) + 0.23D) * 32); - spawnHorse.e = (int) (getLocation().getZ() * 32); - // Setup datawatcher - DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 0); - watcher.a(1, (short) 300); - watcher.a(10, horseName); - watcher.a(11, (byte) 1); - watcher.a(12, -1700000); - spawnHorse.l = watcher; - // Make horse ride wither - PacketPlayOutAttachEntity attachEntity = new PacketPlayOutAttachEntity(); - attachEntity.b = horseId; - attachEntity.c = witherId; - return new Packet[] - { - spawnWitherSkull, spawnHorse, attachEntity - }; - } + public boolean isRemoveOnEntityDeath() + { + return _removeEntityDeath; + } - private Packet[] makeSpawnPackets1_8(int textRow, int entityId, String lineOfText) - { - if (this.isUsingWitherSkull()) - { - PacketPlayOutSpawnEntity spawnPacket = new PacketPlayOutSpawnEntity(); - spawnPacket.a = entityId; - spawnPacket.b = (int) (getLocation().getX() * 32); - spawnPacket.c = (int) ((getLocation().getY() + -0.55 + ((double) textRow * 0.285)) * 32); - spawnPacket.d = (int) (getLocation().getZ() * 32); - spawnPacket.j = 66; - // Setup datawatcher for wither skull - PacketPlayOutEntityMetadata metadataPacket = new PacketPlayOutEntityMetadata(); - metadataPacket.a = entityId; - DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 0); - watcher.a(2, lineOfText); - watcher.a(3, (byte) 1); - metadataPacket.b = watcher.c(); - return new Packet[] - { - spawnPacket, metadataPacket - }; - } - else - { - PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(); - packet.a = entityId; - packet.b = 30; - packet.c = (int) (getLocation().getX() * 32); - packet.d = (int) ((getLocation().getY() + -2.1 + ((double) textRow * 0.285)) * 32); - packet.e = (int) (getLocation().getZ() * 32); - // Setup datawatcher for armor stand - DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 32); - watcher.a(2, lineOfText); - watcher.a(3, (byte) 1); - // watcher.a(10, (byte) 10); TODO Uncomment after a new MC version is released (1.8.2?) - // It uses the marker value which mojang indicates will be usable to hide the bounding box. - // Currently it hides the bounding box and the entity itself.. - packet.l = watcher; - return new Packet[] - { - packet - }; - } - } + public boolean isVisible(Player player) + { + if (getLocation().getWorld() == player.getWorld()) + { + if ((getHologramTarget() == HologramTarget.WHITELIST) == containsPlayer(player)) + { + if (getLocation().distance(player.getLocation()) < getViewDistance()) + { + return true; + } + } + } - /** - * Removes the player from the Hologram so they are no longer effected by Whitelist or Blacklist - */ - public Hologram removePlayer(Player player) - { - return addPlayer(player.getName()); - } + return false; + } - /** - * Removes the player from the Hologram so they are no longer effected by Whitelist or Blacklist - */ - public Hologram removePlayer(String player) - { - _playersInList.remove(player); - return this; - } + private void makeDestroyPacket() + { + int[] entityIds1_7 = new int[_entityIds.size() * 2]; + int[] entityIds1_8 = new int[_entityIds.size()]; - /** - * If the entity moves, the hologram will update its position to appear relative to the movement. - * - * @Please note the hologram updates every tick. - */ - public Hologram setFollowEntity(Entity entityToFollow) - { - _followEntity = entityToFollow; - relativeToEntity = entityToFollow == null ? null : this._location.clone().subtract(entityToFollow.getLocation()) - .toVector(); - return this; - } + for (int i = 0; i < _entityIds.size(); i++) + { + Entry entry = _entityIds.get(i); - /** - * Set who can see the hologram - * - * @Whitelist = Only people added can see the hologram - * @Blacklist = Anyone but people added can see the hologram - */ - public Hologram setHologramTarget(HologramTarget newTarget) - { - this._target = newTarget; - return this; - } + entityIds1_7[i * 2] = entry.getKey(); + entityIds1_7[(i * 2) + 1] = entry.getValue(); - /** - * Sets the hologram to appear at this location - */ - public Hologram setLocation(Location newLocation) - { - _makePackets = true; - Location oldLocation = getLocation(); - _location = newLocation.clone(); - if (getEntityFollowing() != null) - { - relativeToEntity = _location.clone().subtract(getEntityFollowing().getLocation()).toVector(); - } - if (isInUse()) - { - ArrayList canSee = getNearbyPlayers(); - Iterator itel = _playersTracking.iterator(); - while (itel.hasNext()) - { - Player player = itel.next(); - if (!canSee.contains(player)) - { - itel.remove(); - if (player.getWorld() == getLocation().getWorld()) - { - ((CraftPlayer) player).getHandle().playerConnection.sendPacket(getDestroyPacket(player)); - } - } - } - itel = canSee.iterator(); - while (itel.hasNext()) - { - Player player = itel.next(); - if (!_playersTracking.contains(player)) - { - _playersTracking.add(player); - itel.remove(); - for (Packet packet : getSpawnPackets(player)) - { - ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); - } - } - } - if (!canSee.isEmpty()) - { - _lastMovement.add(new Vector(newLocation.getX() - oldLocation.getX(), newLocation.getY() - oldLocation.getY(), - newLocation.getZ() - oldLocation.getZ())); - int x = (int) Math.floor(32 * _lastMovement.getX()); - int y = (int) Math.floor(32 * _lastMovement.getY()); - int z = (int) Math.floor(32 * _lastMovement.getZ()); - Packet[] packets1_7 = new Packet[_text.length]; - Packet[] packets1_8 = new Packet[_text.length]; - int i = 0; - if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 && z <= 127) - { - _lastMovement.subtract(new Vector(x / 32D, y / 32D, z / 32D)); - for (Entry entityId : this._entityIds) - { - PacketPlayOutRelEntityMove relMove = new PacketPlayOutRelEntityMove(); - relMove.a = entityId.getKey(); - relMove.b = (byte) x; - relMove.c = (byte) y; - relMove.d = (byte) z; - packets1_7[i] = relMove; - packets1_8[i] = relMove; - i++; - } - } - else - { - x = (int) Math.floor(32 * newLocation.getX()); - z = (int) Math.floor(32 * newLocation.getZ()); - _lastMovement = new Vector(newLocation.getX() - (x / 32D), 0, newLocation.getZ() - (z / 32D)); - for (Entry entityId : this._entityIds) - { - for (int b = 0; b < 2; b++) - { - PacketPlayOutEntityTeleport teleportPacket = new PacketPlayOutEntityTeleport(); - teleportPacket.a = entityId.getKey(); - teleportPacket.b = x; - teleportPacket.c = (int) Math.floor((oldLocation.getY() - + (b == 0 ? 54.6 : isUsingWitherSkull() ? -0.55 : -2.1) + ((double) i * 0.285)) * 32); - teleportPacket.d = z; - if (b == 0) - { - packets1_7[i] = teleportPacket; - } - else - { - packets1_8[i] = teleportPacket; - } - } - i++; - } - } - for (Player player : canSee) - { - for (Packet packet : UtilPlayer.is1_8(player) ? packets1_8 : packets1_7) - { - ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); - } - } - } - } - return this; - } + entityIds1_8[i] = entry.getKey(); + } - /** - * Set the hologram text - */ - public Hologram setText(String... newText) - { - String[] reversed = new String[newText.length]; - for (int i = 0; i < reversed.length; i++) - { - reversed[i] = newText[reversed.length - (i + 1)]; - } - if (reversed.equals(_text)) - return this; - _makePackets = true; - if (isInUse()) - { - ArrayList packets1_7 = new ArrayList(); - int[] destroy1_7 = new int[0]; - int[] destroy1_8 = new int[0]; - ArrayList packets1_8 = new ArrayList(); - if (_text.length != reversed.length) - { - _destroyPackets = true; - } - for (int textRow = 0; textRow < Math.max(_text.length, reversed.length); textRow++) - { - // You can safely assume that _entityIds here is containing _text.length amount as this code is inside isInUse - if (textRow >= _text.length) - { - // Add entity id and send spawn packets - // You add a entity id because the new hologram needs - Entry entry = new HashMap.SimpleEntry(UtilEnt.getNewEntityId(), UtilEnt.getNewEntityId()); - _entityIds.add(entry); - packets1_7.addAll(Arrays.asList(makeSpawnPackets1_7(textRow, entry.getKey(), entry.getValue(), - reversed[textRow]))); - packets1_8.addAll(Arrays.asList(makeSpawnPackets1_8(textRow, entry.getKey(), reversed[textRow]))); - } - else if (textRow >= reversed.length) - { - // Remove entity id and send destroy packets - Entry entry = _entityIds.remove(reversed.length); - destroy1_7 = Arrays.copyOf(destroy1_7, destroy1_7.length + 2); - destroy1_7[destroy1_7.length - 2] = entry.getKey(); - destroy1_7[destroy1_7.length - 1] = entry.getValue(); - destroy1_8 = Arrays.copyOf(destroy1_8, destroy1_8.length + 1); - destroy1_8[destroy1_8.length - 1] = entry.getKey(); - } - else if (!reversed[textRow].equals(_text[textRow])) - { - // Send update metadata packets - Entry entry = _entityIds.get(textRow); - PacketPlayOutEntityMetadata metadata1_7 = new PacketPlayOutEntityMetadata(); - metadata1_7.a = entry.getValue(); - DataWatcher watcher1_7 = new DataWatcher(null); - watcher1_7.a(0, (byte) 0); - watcher1_7.a(1, (short) 300); - watcher1_7.a(10, reversed[textRow]); - watcher1_7.a(11, (byte) 1); - watcher1_7.a(12, -1700000); - metadata1_7.b = watcher1_7.c(); - packets1_7.add(metadata1_7); + _destroy1_7 = new PacketPlayOutEntityDestroy(entityIds1_7); + _destroy1_8 = new PacketPlayOutEntityDestroy(entityIds1_8); + } - PacketPlayOutEntityMetadata metadata1_8 = new PacketPlayOutEntityMetadata(); - metadata1_8.a = entry.getKey(); - DataWatcher watcher1_8 = new DataWatcher(null); - watcher1_8.a(0, (byte) 0); - watcher1_8.a(2, reversed[textRow]); - watcher1_8.a(3, (byte) 1); - metadata1_8.b = watcher1_8.c(); - packets1_8.add(metadata1_8); - } - } - if (destroy1_7.length > 0) - { - packets1_7.add(new PacketPlayOutEntityDestroy(destroy1_7)); - } - if (destroy1_8.length > 0) - { - packets1_8.add(new PacketPlayOutEntityDestroy(destroy1_8)); - } - for (Player player : _playersTracking) - { - for (Packet packet : UtilPlayer.is1_8(player) ? packets1_8 : packets1_7) - { - ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); - } - } - } - _text = reversed; - return this; - } + private void makeSpawnPackets() + { + _packets1_7 = new Packet[_hologramText.length * 3]; + _packets1_8 = new Packet[_hologramText.length * 1]; - /** - * Tells the hologram to use the wither skull instead of armorstand for 1.8 clients - */ - public Hologram setUsesWitherSkull() - { - _isWitherSkull = true; - return this; - } + if (_entityIds.size() < _hologramText.length) + { + _makeDestroyPackets = true; - /** - * Set the distance the hologram is viewable from. Default is 70 - */ - public Hologram setViewDistance(int newDistance) - { - this._viewDistance = newDistance; - return setLocation(getLocation()); - } + for (int i = _entityIds.size(); i < _hologramText.length; i++) + { + _entityIds.add(new HashMap.SimpleEntry(UtilEnt.getNewEntityId(), UtilEnt.getNewEntityId())); + } + } + else + { + _makeDestroyPackets = true; - /** - * Start the hologram - */ - public Hologram start() - { - if (!isInUse()) - { - _hologramManager.addHologram(this); - _playersTracking.addAll(getNearbyPlayers()); - for (Player player : _playersTracking) - { - for (Packet packet : getSpawnPackets(player)) - { - ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); - } - } - _lastMovement = new Vector(); - } - return this; - } + while (_entityIds.size() > _hologramText.length) + { + _entityIds.remove(_hologramText.length); + } + } + for (int textRow = 0; textRow < _hologramText.length; textRow++) + { + Entry entityIds = this._entityIds.get(textRow); - /** - * Stop the hologram - */ - public Hologram stop() - { - if (isInUse()) - { - _hologramManager.removeHologram(this); - for (Player player : _playersTracking) - { - ((CraftPlayer) player).getHandle().playerConnection.sendPacket(getDestroyPacket(player)); - } - _playersTracking.clear(); - _lastMovement = null; - } - return this; - } + Packet[] packets1_7 = makeSpawnPackets1_7(textRow, entityIds.getKey(), entityIds.getValue(), _hologramText[textRow]); + + for (int i = 0; i < packets1_7.length; i++) + { + _packets1_7[(textRow * 3) + i] = packets1_7[i]; + } + + Packet[] packets1_8 = makeSpawnPackets1_8(textRow, entityIds.getKey(), _hologramText[textRow]); + + for (int i = 0; i < packets1_8.length; i++) + { + _packets1_8[textRow + i] = packets1_8[i]; + } + } + } + + private Packet[] makeSpawnPackets1_7(int height, int witherId, int horseId, String horseName) + { + // Spawn wither skull + PacketPlayOutSpawnEntity spawnWitherSkull = new PacketPlayOutSpawnEntity(); + + spawnWitherSkull.a = witherId; + spawnWitherSkull.b = (int) (getLocation().getX() * 32); + spawnWitherSkull.c = (int) ((getLocation().getY() + 54.6 + ((double) height * 0.285D)) * 32); + spawnWitherSkull.d = (int) (getLocation().getZ() * 32); + spawnWitherSkull.j = 66; + + // Spawn horse + PacketPlayOutSpawnEntityLiving spawnHorse = new PacketPlayOutSpawnEntityLiving(); + DataWatcher watcher = new DataWatcher(null); + + spawnHorse.a = horseId; + spawnHorse.b = 100; + spawnHorse.c = (int) (getLocation().getX() * 32); + spawnHorse.d = (int) ((getLocation().getY() + 54.83 + ((double) height * 0.285D) + 0.23D) * 32); + spawnHorse.e = (int) (getLocation().getZ() * 32); + spawnHorse.l = watcher; + + // Setup datawatcher + watcher.a(0, (byte) 0); + watcher.a(1, (short) 300); + watcher.a(10, horseName); + watcher.a(11, (byte) 1); + watcher.a(12, -1700000); + + // Make horse ride wither + PacketPlayOutAttachEntity attachEntity = new PacketPlayOutAttachEntity(); + + attachEntity.b = horseId; + attachEntity.c = witherId; + + return new Packet[] + { + spawnWitherSkull, spawnHorse, attachEntity + }; + } + + private Packet[] makeSpawnPackets1_8(int textRow, int entityId, String lineOfText) + { + PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(); + DataWatcher watcher = new DataWatcher(null); + + packet.a = entityId; + packet.b = 30; + packet.c = (int) (getLocation().getX() * 32); + packet.d = (int) ((getLocation().getY() + -2.1 + ((double) textRow * 0.285)) * 32); + packet.e = (int) (getLocation().getZ() * 32); + packet.l = watcher; + + // Setup datawatcher for armor stand + watcher.a(0, (byte) 32); + watcher.a(2, lineOfText); + watcher.a(3, (byte) 1); + // watcher.a(10, (byte) 16); // TODO Uncomment after we can enforce 1.8.3 + // Also correct hologram positioning + + return new Packet[] + { + packet + }; + } + + /** + * Removes the player from the Hologram so they are no longer effected by Whitelist or Blacklist + */ + public Hologram removePlayer(Player player) + { + return addPlayer(player.getName()); + } + + /** + * Removes the player from the Hologram so they are no longer effected by Whitelist or Blacklist + */ + public Hologram removePlayer(String player) + { + _playersInList.remove(player); + return this; + } + + /** + * If the entity moves, the hologram will update its position to appear relative to the movement. + * + * @Please note the hologram updates every tick. + */ + public Hologram setFollowEntity(Entity entityToFollow) + { + _followEntity = entityToFollow; + relativeToEntity = entityToFollow == null ? null : this._location.clone().subtract(entityToFollow.getLocation()) + .toVector(); + + return this; + } + + /** + * Set who can see the hologram + * + * @Whitelist = Only people added can see the hologram + * @Blacklist = Anyone but people added can see the hologram + */ + public Hologram setHologramTarget(HologramTarget newTarget) + { + this._target = newTarget; + return this; + } + + /** + * Sets the hologram to appear at this location + */ + public Hologram setLocation(Location newLocation) + { + _makeSpawnPackets = true; + + Location oldLocation = getLocation(); + _location = newLocation.clone(); + + if (getEntityFollowing() != null) + { + relativeToEntity = _location.clone().subtract(getEntityFollowing().getLocation()).toVector(); + } + if (isInUse()) + { + ArrayList canSee = getNearbyPlayers(); + Iterator itel = _playersTracking.iterator(); + + while (itel.hasNext()) + { + Player player = itel.next(); + if (!canSee.contains(player)) + { + itel.remove(); + + if (player.getWorld() == getLocation().getWorld()) + { + ((CraftPlayer) player).getHandle().playerConnection.sendPacket(getDestroyPacket(player)); + } + } + } + itel = canSee.iterator(); + while (itel.hasNext()) + { + Player player = itel.next(); + + if (!_playersTracking.contains(player)) + { + _playersTracking.add(player); + itel.remove(); + + for (Packet packet : getSpawnPackets(player)) + { + ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + } + } + } + if (!canSee.isEmpty()) + { + _lastMovement.add(new Vector(newLocation.getX() - oldLocation.getX(), newLocation.getY() - oldLocation.getY(), + newLocation.getZ() - oldLocation.getZ())); + + int x = (int) Math.floor(32 * _lastMovement.getX()); + int y = (int) Math.floor(32 * _lastMovement.getY()); + int z = (int) Math.floor(32 * _lastMovement.getZ()); + + Packet[] packets1_7 = new Packet[_hologramText.length]; + Packet[] packets1_8 = new Packet[_hologramText.length]; + + int i = 0; + + if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 && z <= 127) + { + _lastMovement.subtract(new Vector(x / 32D, y / 32D, z / 32D)); + for (Entry entityId : this._entityIds) + { + PacketPlayOutRelEntityMove relMove = new PacketPlayOutRelEntityMove(); + + relMove.a = entityId.getKey(); + relMove.b = (byte) x; + relMove.c = (byte) y; + relMove.d = (byte) z; + + packets1_7[i] = relMove; + packets1_8[i] = relMove; + i++; + } + } + else + { + x = (int) Math.floor(32 * newLocation.getX()); + z = (int) Math.floor(32 * newLocation.getZ()); + + _lastMovement = new Vector(newLocation.getX() - (x / 32D), 0, newLocation.getZ() - (z / 32D)); + + for (Entry entityId : this._entityIds) + { + for (int b = 0; b < 2; b++) + { + PacketPlayOutEntityTeleport teleportPacket = new PacketPlayOutEntityTeleport(); + teleportPacket.a = entityId.getKey(); + teleportPacket.b = x; + teleportPacket.c = (int) Math + .floor((oldLocation.getY() + (b == 0 ? 54.6 : -2.1) + ((double) i * 0.285)) * 32); + teleportPacket.d = z; + + if (b == 0) + { + packets1_7[i] = teleportPacket; + } + else + { + packets1_8[i] = teleportPacket; + } + } + + i++; + } + } + + for (Player player : canSee) + { + for (Packet packet : UtilPlayer.is1_8(player) ? packets1_8 : packets1_7) + { + ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + } + } + } + } + return this; + } + + public Hologram setRemoveOnEntityDeath() + { + _removeEntityDeath = true; + return this; + } + + /** + * Set the hologram text + */ + public Hologram setText(String... newLines) + { + String[] newText = new String[newLines.length]; + + for (int i = 0; i < newText.length; i++) + { + newText[i] = newLines[newText.length - (i + 1)]; + } + + if (newText.equals(_hologramText)) + return this; + + _makeSpawnPackets = true; + + if (isInUse()) + { + int[] destroy1_7 = new int[0]; + int[] destroy1_8 = new int[0]; + + ArrayList packets1_7 = new ArrayList(); + ArrayList packets1_8 = new ArrayList(); + + if (_hologramText.length != newText.length) + { + _makeDestroyPackets = true; + } + + for (int i = 0; i < Math.max(_hologramText.length, newText.length); i++) + { + // If more lines than previously + if (i >= _hologramText.length) + { + // Add entity id and send spawn packets + // You add a entity id because the new hologram needs + Entry entry = new HashMap.SimpleEntry(UtilEnt.getNewEntityId(), UtilEnt.getNewEntityId()); + _entityIds.add(entry); + + packets1_7.addAll(Arrays.asList(makeSpawnPackets1_7(i, entry.getKey(), entry.getValue(), newText[i]))); + + packets1_8.addAll(Arrays.asList(makeSpawnPackets1_8(i, entry.getKey(), newText[i]))); + } + // If less lines than previously + else if (i >= newText.length) + { + // Remove entity id and send destroy packets + Entry entry = _entityIds.remove(newText.length); + + destroy1_7 = Arrays.copyOf(destroy1_7, destroy1_7.length + 2); + + destroy1_7[destroy1_7.length - 2] = entry.getKey(); + destroy1_7[destroy1_7.length - 1] = entry.getValue(); + + destroy1_8 = Arrays.copyOf(destroy1_8, destroy1_8.length + 1); + destroy1_8[destroy1_8.length - 1] = entry.getKey(); + } + else if (!newText[i].equals(_hologramText[i])) + { + // Send update metadata packets + Entry entry = _entityIds.get(i); + PacketPlayOutEntityMetadata metadata1_7 = new PacketPlayOutEntityMetadata(); + + metadata1_7.a = entry.getValue(); + + DataWatcher watcher1_7 = new DataWatcher(null); + + watcher1_7.a(0, (byte) 0); + watcher1_7.a(1, (short) 300); + watcher1_7.a(10, newText[i]); + watcher1_7.a(11, (byte) 1); + watcher1_7.a(12, -1700000); + + metadata1_7.b = watcher1_7.c(); + + packets1_7.add(metadata1_7); + + PacketPlayOutEntityMetadata metadata1_8 = new PacketPlayOutEntityMetadata(); + + metadata1_8.a = entry.getKey(); + + DataWatcher watcher1_8 = new DataWatcher(null); + + watcher1_8.a(0, (byte) 32); + watcher1_8.a(2, newText[i]); + watcher1_8.a(3, (byte) 1); + // watcher1_8.a(10, (byte) 16);// TODO Uncomment after we can enforce 1.8.3 + // Also correct hologram positioning + metadata1_8.b = watcher1_8.c(); + + packets1_8.add(metadata1_8); + } + } + + if (destroy1_7.length > 0) + { + packets1_7.add(new PacketPlayOutEntityDestroy(destroy1_7)); + } + + if (destroy1_8.length > 0) + { + packets1_8.add(new PacketPlayOutEntityDestroy(destroy1_8)); + } + + for (Player player : _playersTracking) + { + for (Packet packet : UtilPlayer.is1_8(player) ? packets1_8 : packets1_7) + { + ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + } + } + } + + _hologramText = newText; + + return this; + } + + /** + * Set the distance the hologram is viewable from. Default is 70 + */ + public Hologram setViewDistance(int newDistance) + { + this._viewDistance = newDistance; + return setLocation(getLocation()); + } + + /** + * Start the hologram + */ + public Hologram start() + { + if (!isInUse()) + { + _hologramManager.addHologram(this); + _playersTracking.addAll(getNearbyPlayers()); + + for (Player player : _playersTracking) + { + for (Packet packet : getSpawnPackets(player)) + { + ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + } + } + + _lastMovement = new Vector(); + } + return this; + } + + /** + * Stop the hologram + */ + public Hologram stop() + { + if (isInUse()) + { + _hologramManager.removeHologram(this); + + for (Player player : _playersTracking) + { + ((CraftPlayer) player).getHandle().playerConnection.sendPacket(getDestroyPacket(player)); + } + + _playersTracking.clear(); + _lastMovement = null; + } + return this; + } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/searchanddestroy/TeamBomb.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/searchanddestroy/TeamBomb.java index 9c045890f..50dfd8594 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/searchanddestroy/TeamBomb.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/searchanddestroy/TeamBomb.java @@ -315,8 +315,7 @@ class TeamBomb implements Comparable public void setupHologram() { - _hologram = new Hologram(this._game.getArcadeManager().getHologramManager(), getBlockLocation().clone().add(0, 1, 0)) - .setUsesWitherSkull(); + _hologram = new Hologram(this._game.getArcadeManager().getHologramManager(), getBlockLocation().clone().add(0, 1, 0)); _hologram.setText(getTeam().GetColor() + C.Bold + getTeam().GetName() + " Team's Bomb"); _hologram.start(); } From 4db745c1e5dff5dafffb5af8f14847f857c42a1a Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Wed, 11 Mar 2015 17:23:23 -0700 Subject: [PATCH 15/19] Added Version and IP logging for Bungees. --- .../bungee/playerStats/PlayerStats.java | 2 + .../playerStats/PlayerStatsRepository.java | 75 ++++++++++++++----- 2 files changed, 59 insertions(+), 18 deletions(-) diff --git a/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/playerStats/PlayerStats.java b/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/playerStats/PlayerStats.java index 1430e36e4..f91366095 100644 --- a/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/playerStats/PlayerStats.java +++ b/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/playerStats/PlayerStats.java @@ -28,6 +28,8 @@ public class PlayerStats implements Listener public void run() { _repository.addPlayer(event.getPlayer().getName()); + _repository.addPlayerVersion(event.getPlayer().getName(), event.getPlayer().getPendingConnection().getVersion()); + _repository.addPlayerIP(event.getPlayer().getName(), event.getPlayer().getPendingConnection().getAddress().getAddress().getHostAddress()); } }); } diff --git a/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/playerStats/PlayerStatsRepository.java b/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/playerStats/PlayerStatsRepository.java index 4c7c3b23c..b1a18dcd2 100644 --- a/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/playerStats/PlayerStatsRepository.java +++ b/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/playerStats/PlayerStatsRepository.java @@ -1,5 +1,6 @@ package mineplex.bungee.playerStats; +import java.net.InetAddress; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; @@ -16,8 +17,12 @@ public class PlayerStatsRepository private static String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS DailyUnique (id INT NOT NULL AUTO_INCREMENT, day VARCHAR(100), playerName VARCHAR(20), PRIMARY KEY (id), UNIQUE KEY unique_player_per_day (day, playerName));"; private static String INSERT_PLAYER = "INSERT INTO DailyUnique (day, playerName) values(curdate(), ?) ON DUPLICATE KEY UPDATE playerName=playerName;"; - private static String CREATE_VER_TABLE = "CREATE TABLE IF NOT EXISTS PlayerVersion (id INT NOT NULL AUTO_INCREMENT, playerName VARCHAR(20), version VARCHAR(40), PRIMARY KEY (id), UNIQUE KEY unique_player (playerName));"; - private static String INSERT_VER_PLAYER = "INSERT INTO PlayerVersion (playerName, version) values(?, ?) ON DUPLICATE KEY UPDATE version=version;"; + private static String CREATE_VER_TABLE = "CREATE TABLE IF NOT EXISTS PlayerVersion (id INT NOT NULL AUTO_INCREMENT, playerName VARCHAR(20), version INT, PRIMARY KEY (id), UNIQUE KEY unique_player (playerName));"; + private static String INSERT_VER_PLAYER = "INSERT INTO PlayerVersion (playerName, version) values(?, ?);"; + private static String UPDATE_VER_PLAYER = "UPDATE PlayerVersion SET version = ? WHERE playerName = ?;"; + + private static String CREATE_IP_TABLE = "CREATE TABLE IF NOT EXISTS PlayerIP (id INT NOT NULL AUTO_INCREMENT, playerName VARCHAR(20), ip VARCHAR(20), PRIMARY KEY (id), UNIQUE INDEX unique_player_ip (playerName, ip));"; + private static String INSERT_IP_PLAYER = "INSERT IGNORE INTO PlayerIP (playerName, ip) values(?, ?);"; public void initialize() { @@ -36,6 +41,11 @@ public class PlayerStatsRepository preparedStatement = _connection.prepareStatement(CREATE_VER_TABLE); preparedStatement.execute(); + + preparedStatement.close(); + + preparedStatement = _connection.prepareStatement(CREATE_IP_TABLE); + preparedStatement.execute(); } catch (Exception exception) { @@ -103,7 +113,7 @@ public class PlayerStatsRepository } } - public boolean addPlayerVersion(String playerName, String version) + public void addPlayerVersion(String playerName, int version) { PreparedStatement preparedStatement = null; @@ -112,34 +122,63 @@ public class PlayerStatsRepository if (_connection == null || _connection.isClosed()) _connection = DriverManager.getConnection(_connectionString, _userName, _password); - preparedStatement = _connection.prepareStatement(INSERT_VER_PLAYER, Statement.RETURN_GENERATED_KEYS); + preparedStatement = _connection.prepareStatement(UPDATE_VER_PLAYER); - preparedStatement.setString(1, playerName); - preparedStatement.setString(2, version); + preparedStatement.setInt(1, version); + preparedStatement.setString(2, playerName); int affectedRows = preparedStatement.executeUpdate(); if (affectedRows == 0) { - throw new SQLException("Adding player version record failed, no rows affected."); - } - - return true; + preparedStatement.close(); + preparedStatement = _connection.prepareStatement(INSERT_VER_PLAYER, Statement.RETURN_GENERATED_KEYS); + + preparedStatement.setString(1, playerName); + preparedStatement.setInt(2, version); + + preparedStatement.executeUpdate(); + } } catch (Exception exception) { exception.printStackTrace(); - - try + } + finally + { + if (preparedStatement != null) { - Thread.sleep(10); - } - catch (InterruptedException e) - { - e.printStackTrace(); + try + { + preparedStatement.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } } + } + } + + public void addPlayerIP(String playerName, String address) + { + PreparedStatement preparedStatement = null; + + try + { + if (_connection == null || _connection.isClosed()) + _connection = DriverManager.getConnection(_connectionString, _userName, _password); + + preparedStatement = _connection.prepareStatement(INSERT_IP_PLAYER, Statement.RETURN_GENERATED_KEYS); - return addPlayer(playerName); + preparedStatement.setString(1, playerName); + preparedStatement.setString(2, address); + + preparedStatement.executeUpdate(); + } + catch (Exception exception) + { + exception.printStackTrace(); } finally { From 1ab43c9f446e6223055416d6013f7d50d11bede6 Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Wed, 11 Mar 2015 17:23:48 -0700 Subject: [PATCH 16/19] Added new support agent to whitelist for customer support server. --- .../src/mineplex/staffServer/StaffServer.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java index 647cf3638..52624bf4a 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java @@ -77,11 +77,10 @@ public class StaffServer extends JavaPlugin ((CraftServer)getServer()).setWhitelist(true); - ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("d3965dbc-f9cc-4e5d-9306-5be2a23ad6cb"), "NDrew")); - ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("939cfa72-213c-4b70-a638-c637a4955239"), "Morena")); - ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("f4a7aad4-116f-491a-b162-af0422c0ec4f"), "Revolark")); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("377bdea3-badc-448d-81c1-65db43b17ea4"), "Strutt20")); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("cf1b629c-cc55-4eb4-be9e-3ca86dfc7b9d"), "mannalou")); ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("04a484d0-93e0-4777-a70c-808046917e3a"), "EvilEsther")); - ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("a6324fac-d44e-449c-adbe-6238423e29f2"), "Timmy48081")); + ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("adaa7613-6683-400f-baf8-7272c04b2cb4"), "Timmy48081_")); ((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("2d5fd31b-0aa5-41db-a62d-a4611a24349a"), "ishh")); } } From a955526adf9b679b82b3f56f3c0df2738a988cce Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Wed, 11 Mar 2015 17:24:03 -0700 Subject: [PATCH 17/19] Disabled double gems. --- .../src/nautilus/game/arcade/managers/GameGemManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameGemManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameGemManager.java index 7f781e56f..27ded40e6 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameGemManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameGemManager.java @@ -30,7 +30,7 @@ public class GameGemManager implements Listener { ArcadeManager Manager; - boolean DoubleGem = true; + boolean DoubleGem = false; public GameGemManager(ArcadeManager manager) { From 0b2ce48b3ea761b044fded3c2db7880ad8519183 Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Wed, 11 Mar 2015 17:27:21 -0700 Subject: [PATCH 18/19] Fix dead lobbies bug. --- .../src/mineplex/hub/server/ui/LobbyMenu.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/LobbyMenu.java b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/LobbyMenu.java index f47ee6a16..90cc6faa1 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/LobbyMenu.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/LobbyMenu.java @@ -57,7 +57,7 @@ public class LobbyMenu extends ShopPageBase implements slot = Integer.parseInt(serverInfo.Name.split("-")[1]) - 1; if (slot >= 54) - break; + continue; if (serverInfo.Name.equalsIgnoreCase(getPlugin().getStatusManager().getCurrentServerName())) status = Material.EMERALD_BLOCK; @@ -81,6 +81,12 @@ public class LobbyMenu extends ShopPageBase implements else addItem(slot, new ShopItem(status, ChatColor.UNDERLINE + "" + ChatColor.BOLD + "" + ChatColor.WHITE + "Server " + serverInfo.Name.substring(serverInfo.Name.indexOf('-') + 1), lore.toArray(new String[lore.size()]), Integer.parseInt(serverInfo.Name.substring(serverInfo.Name.indexOf('-') + 1)), false)); } + + while (slot < 54) + { + clear(slot); + slot++; + } } public void Update() From 626bfc35fc4dc462618239520a51d888da98b932 Mon Sep 17 00:00:00 2001 From: Jonathan Williams Date: Wed, 11 Mar 2015 18:05:13 -0700 Subject: [PATCH 19/19] Revert "Revert "Implement usage of SQL connection pooling in RepositoryBase to prevent unnecessary idle connections."" This reverts commit 215ec7b00dff89b0fbb2646de67531d6fe4406d2. Enabled multi-queries on db pool. Cleaned up some code using new pooling getConnection inappropriately --- .../account/repository/AccountRepository.java | 65 +---- .../benefit/BenefitManagerRepository.java | 3 +- .../src/mineplex/core/database/DBPool.java | 5 +- .../core/database/RepositoryBase.java | 255 ++++-------------- .../repository/DonationRepository.java | 3 +- .../inventory/data/InventoryRepository.java | 3 +- .../leaderboard/StatEventsRepository.java | 3 +- .../preferences/PreferencesRepository.java | 27 +- .../core/report/ReportRepository.java | 3 +- .../mineplex/core/spawn/SpawnRepository.java | 4 +- .../mineplex/core/stats/StatsRepository.java | 9 +- .../enjinTranslator/TempRepository.java | 3 +- .../fields/repository/FieldRepository.java | 3 +- .../src/mineplex/hub/mail/MailRepository.java | 6 +- .../password/PasswordRepository.java | 4 +- 15 files changed, 98 insertions(+), 298 deletions(-) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java index ae3ce09c2..602e2fd62 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java @@ -1,5 +1,6 @@ package mineplex.core.account.repository; +import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -19,6 +20,7 @@ import mineplex.core.common.Rank; import mineplex.core.common.util.Callback; import mineplex.core.common.util.NautHashMap; import mineplex.core.common.util.UUIDFetcher; +import mineplex.core.database.DBPool; import mineplex.core.database.DatabaseRunnable; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; @@ -43,34 +45,9 @@ public class AccountRepository extends RepositoryBase public AccountRepository(JavaPlugin plugin, String webAddress) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10&allowMultiQueries=true", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); _webAddress = webAddress; - - Statement statement = null; - - try - { - statement = getConnection().createStatement(); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - finally - { - if (statement != null) - { - try - { - statement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } } @Override @@ -81,13 +58,11 @@ public class AccountRepository extends RepositoryBase public void login(NautHashMap loginProcessors, String uuid, String name) { - Statement statement = null; - ResultSet resultSet = null; - - try + try ( + Connection connection = getConnection(); + Statement statement = connection.createStatement() + ) { - statement = getConnection().createStatement(); - /* boolean statementStatus = statement.execute( "UPDATE accounts SET name='" + name + "', lastLogin=now() WHERE accounts.uuid = '" + uuid + "';" @@ -152,32 +127,6 @@ public class AccountRepository extends RepositoryBase { exception.printStackTrace(); } - finally - { - if (statement != null) - { - try - { - statement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - if (resultSet != null) - { - try - { - resultSet.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } } public String GetClient(String name, UUID uuid, String ipAddress) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java index 2fa7140aa..5affc2a0b 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/benefit/BenefitManagerRepository.java @@ -3,6 +3,7 @@ package mineplex.core.benefit; import java.sql.ResultSet; import java.sql.SQLException; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnVarChar; @@ -16,7 +17,7 @@ public class BenefitManagerRepository extends RepositoryBase public BenefitManagerRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/database/DBPool.java b/Plugins/Mineplex.Core/src/mineplex/core/database/DBPool.java index 8dacde695..d7747d086 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/database/DBPool.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/database/DBPool.java @@ -16,6 +16,7 @@ public final class DBPool { BasicDataSource source = new BasicDataSource(); source.addConnectionProperty("autoReconnect", "true"); + source.addConnectionProperty("allowMultiQueries", "true"); source.setDefaultAutoCommit(true); source.setEnableAutoCommitOnReturn(true); source.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); @@ -23,8 +24,8 @@ public final class DBPool source.setUrl(url); source.setUsername(username); source.setPassword(password); - source.setMaxTotal(2); - source.setMaxIdle(2); + source.setMaxTotal(3); + source.setMaxIdle(3); source.setTimeBetweenEvictionRunsMillis(180 * 1000); source.setSoftMinEvictableIdleTimeMillis(180 * 1000); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java b/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java index 88d3686bf..eab9840f2 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/database/RepositoryBase.java @@ -1,7 +1,6 @@ package mineplex.core.database; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -22,58 +21,29 @@ import org.bukkit.plugin.java.JavaPlugin; public abstract class RepositoryBase implements Listener { - protected static Object _connectionLock = new Object(); - - private Connection _connection = null; - + // Queue for failed processes private static Object _queueLock = new Object(); - private NautHashMap _failedQueue = new NautHashMap(); - private String _connectionString; - private String _userName; - private String _password; - - protected JavaPlugin Plugin; - protected DataSource DataSource; - - public RepositoryBase(JavaPlugin plugin, String connectionString, String username, String password) - { - Plugin = plugin; - - _connectionString = connectionString; - _userName = username; - _password = password; - - Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() - { - public void run() - { - synchronized (_connectionLock) - { - initialize(); - update(); - } - } - }); - - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } + private DataSource _dataSource; // Connection pool + protected JavaPlugin Plugin; // Plugin responsible for this repository + /** + * Constructor + * @param plugin - the {@link JavaPlugin} module responsible for this repository. + * @param dataSource - the {@link DataSource} responsible for providing the connection pool to this repository. + */ public RepositoryBase(JavaPlugin plugin, DataSource dataSource) { Plugin = plugin; - DataSource = dataSource; + _dataSource = dataSource; Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { public void run() { - synchronized (_connectionLock) - { - initialize(); - update(); - } + initialize(); + update(); } }); @@ -84,34 +54,39 @@ public abstract class RepositoryBase implements Listener protected abstract void update(); + /** + * @return the {@link DataSource} used by the repository for connection pooling. + */ + protected DataSource getConnectionPool() + { + return _dataSource; + } + + /** + * Requirements: {@link Connection}s must be closed after usage so they may be returned to the pool! + * @see Connection#close() + * @return a newly fetched {@link Connection} from the connection pool, if a connection can be made, null otherwise. + */ protected Connection getConnection() { - return getConnection(false); - } - - protected Connection getConnection(boolean validate) - { - synchronized (_connectionLock) + try { - try - { - if (_connection == null || (validate && !_connection.isValid(2))) - { - if (DataSource != null) - _connection = DataSource.getConnection(); - else - _connection = DriverManager.getConnection(_connectionString, _userName, _password); - } - } - catch (SQLException e) - { - e.printStackTrace(); - } + return _dataSource.getConnection(); + } + catch (SQLException e) + { + e.printStackTrace(); + // TODO: Log connection failures? + return null; } - - return _connection; } + /** + * Execute a query against the repository. + * @param query - the concatenated query to execute in string form. + * @param columns - the column data values used for insertion into the query. + * @return the number of rows affected by this query in the repository. + */ protected int executeUpdate(String query, Column...columns) { return executeInsert(query, null, columns); @@ -119,16 +94,14 @@ public abstract class RepositoryBase implements Listener protected int executeInsert(String query, ResultSetCallable callable, Column...columns) { - PreparedStatement preparedStatement = null; - int affectedRows = 0; - try + // Automatic resource management for handling/closing objects. + try ( + Connection connection = getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS) + ) { - getConnection(false); - - preparedStatement = _connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); - for (int i=0; i < columns.length; i++) { columns[i].setValue(preparedStatement, i+1); @@ -137,49 +110,24 @@ public abstract class RepositoryBase implements Listener affectedRows = preparedStatement.executeUpdate(); if (callable != null) + { callable.processResultSet(preparedStatement.getGeneratedKeys()); + } } catch (SQLException exception) { - getConnection(true); executeInsert(query, callable, columns); } catch (Exception exception) { exception.printStackTrace(); } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - try - { - if (DataSource != null) - _connection.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } return affectedRows; } protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column...columns) { - ResultSet resultSet = null; - try { for (int i=0; i < columns.length; i++) @@ -187,118 +135,41 @@ public abstract class RepositoryBase implements Listener columns[i].setValue(statement, i+1); } - resultSet = statement.executeQuery(); - - callable.processResultSet(resultSet); + try (ResultSet resultSet = statement.executeQuery()) + { + callable.processResultSet(resultSet); + } } catch (SQLException exception) { - getConnection(true); executeQuery(statement, callable, columns); } catch (Exception exception) { exception.printStackTrace(); } - finally - { - if (resultSet != null) - { - try - { - resultSet.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - try - { - if (DataSource != null) - _connection.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } } protected void executeQuery(String query, ResultSetCallable callable, Column...columns) { - PreparedStatement preparedStatement = null; - - try + // Automatic resource management for handling/closing objects. + try ( + Connection connection = getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(query) + ) { - getConnection(false); - - preparedStatement = _connection.prepareStatement(query); - executeQuery(preparedStatement, callable, columns); } catch (SQLException exception) { - getConnection(true); executeQuery(query, callable, columns); } catch (Exception exception) { exception.printStackTrace(); } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - try - { - if (DataSource != null) - _connection.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } } - - protected int executeUpdate(PreparedStatement preparedStatement, Column...columns) - { - int affectedRows = 0; - try - { - for (int i=0; i < columns.length; i++) - { - columns[i].setValue(preparedStatement, i+1); - } - - affectedRows = preparedStatement.executeUpdate(); - } - catch (SQLException exception) - { - getConnection(true); - executeUpdate(preparedStatement, columns); - } - catch (Exception exception) - { - exception.printStackTrace(); - } - - return affectedRows; - } - protected void handleDatabaseCall(final DatabaseRunnable databaseRunnable, final String errorMessage) { Thread asyncThread = new Thread(new Runnable() @@ -341,24 +212,6 @@ public abstract class RepositoryBase implements Listener processFailedQueue(); } - @EventHandler - public void validateConnection(UpdateEvent event) - { - if (event.getType() != UpdateType.MIN_02 || DataSource != null) - return; - - Bukkit.getScheduler().runTaskAsynchronously(Plugin, new Runnable() - { - public void run() - { - synchronized (_connectionLock) - { - getConnection(true); - } - } - }); - } - private void processFailedQueue() { synchronized (_queueLock) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java index 818c95df9..b7246e8be 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java @@ -8,6 +8,7 @@ import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.common.util.Callback; +import mineplex.core.database.DBPool; import mineplex.core.database.DatabaseRunnable; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; @@ -33,7 +34,7 @@ public class DonationRepository extends RepositoryBase public DonationRepository(JavaPlugin plugin, String webAddress) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); _webAddress = webAddress; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java index 2a1cb7f27..444e98bbf 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/inventory/data/InventoryRepository.java @@ -7,6 +7,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnInt; @@ -31,7 +32,7 @@ public class InventoryRepository extends RepositoryBase public InventoryRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java index 2e0888f1e..1679bc36d 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/leaderboard/StatEventsRepository.java @@ -1,5 +1,6 @@ package mineplex.core.leaderboard; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; import mineplex.core.database.column.ColumnVarChar; @@ -35,7 +36,7 @@ public class StatEventsRepository extends RepositoryBase */ public StatEventsRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesRepository.java index a451cea77..44852c23e 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesRepository.java @@ -1,5 +1,6 @@ package mineplex.core.preferences; +import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -14,7 +15,7 @@ import mineplex.core.database.column.ColumnVarChar; public class PreferencesRepository extends RepositoryBase { - private static String CREATE_ACCOUNT_TABLE = "CREATE TABLE IF NOT EXISTS accountPreferences (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(256), games BOOL NOT NULL DEFAULT 1, visibility BOOL NOT NULL DEFAULT 1, showChat BOOL NOT NULL DEFAULT 1, friendChat BOOL NOT NULL DEFAULT 1, privateMessaging BOOL NOT NULL DEFAULT 1, partyRequests BOOL NOT NULL DEFAULT 0, invisibility BOOL NOT NULL DEFAULT 0, forcefield BOOL NOT NULL DEFAULT 0, showMacReports BOOL NOT NULL DEFAULT 0, ignoreVelocity BOOL NOT NULL DEFAULT 0, PRIMARY KEY (id), UNIQUE INDEX uuid_index (uuid));"; + //private static String CREATE_ACCOUNT_TABLE = "CREATE TABLE IF NOT EXISTS accountPreferences (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(256), games BOOL NOT NULL DEFAULT 1, visibility BOOL NOT NULL DEFAULT 1, showChat BOOL NOT NULL DEFAULT 1, friendChat BOOL NOT NULL DEFAULT 1, privateMessaging BOOL NOT NULL DEFAULT 1, partyRequests BOOL NOT NULL DEFAULT 0, invisibility BOOL NOT NULL DEFAULT 0, forcefield BOOL NOT NULL DEFAULT 0, showMacReports BOOL NOT NULL DEFAULT 0, ignoreVelocity BOOL NOT NULL DEFAULT 0, PRIMARY KEY (id), UNIQUE INDEX uuid_index (uuid));"; private static String INSERT_ACCOUNT = "INSERT INTO accountPreferences (uuid) VALUES (?) ON DUPLICATE KEY UPDATE uuid=uuid;"; private static String UPDATE_ACCOUNT_PREFERENCES = "UPDATE accountPreferences SET games = ?, visibility = ?, showChat = ?, friendChat = ?, privateMessaging = ?, partyRequests = ?, invisibility = ?, forcefield = ?, showMacReports = ?, ignoreVelocity = ?, pendingFriendRequests = ?, friendDisplayInventoryUI = ? WHERE uuid=?;"; @@ -36,12 +37,12 @@ public class PreferencesRepository extends RepositoryBase public void saveUserPreferences(NautHashMap preferences) { - PreparedStatement preparedStatement = null; - - try + try + ( + Connection connection = getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_ACCOUNT_PREFERENCES); + ) { - preparedStatement = getConnection().prepareStatement(UPDATE_ACCOUNT_PREFERENCES); - for (Entry entry : preferences.entrySet()) { preparedStatement.setBoolean(1, entry.getValue().HubGames); @@ -93,20 +94,6 @@ public class PreferencesRepository extends RepositoryBase { exception.printStackTrace(); } - finally - { - if (preparedStatement != null) - { - try - { - preparedStatement.close(); - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - } } public UserPreferences loadClientInformation(final ResultSet resultSet) throws SQLException diff --git a/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java index 968010e9c..4a9f91215 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/report/ReportRepository.java @@ -7,6 +7,7 @@ import java.util.UUID; import java.util.Map.Entry; import mineplex.core.common.util.NautHashMap; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnInt; @@ -40,7 +41,7 @@ This will be used to determine if staff are handling public ReportRepository(JavaPlugin plugin, String connectionString) { - super(plugin, connectionString, "root", "tAbechAk3wR7tuTh"); // TODO: Config file for host/pass? + super(plugin, DBPool.ACCOUNT); } @Override diff --git a/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java index 69a5e3b64..eb85bae9d 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/spawn/SpawnRepository.java @@ -7,6 +7,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -22,8 +23,7 @@ public class SpawnRepository extends RepositoryBase public SpawnRepository(JavaPlugin plugin, String serverName) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); - + super(plugin, DBPool.ACCOUNT); _serverName = serverName; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java index 827b3605c..58c81c9f8 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsRepository.java @@ -9,6 +9,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.common.util.NautHashMap; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -18,6 +19,7 @@ import org.jooq.DSLContext; import org.jooq.Insert; import org.jooq.Record2; import org.jooq.Result; +import org.jooq.SQLDialect; import org.jooq.Update; import org.jooq.impl.DSL; @@ -31,7 +33,7 @@ public class StatsRepository extends RepositoryBase public StatsRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } @Override @@ -79,8 +81,7 @@ public class StatsRepository extends RepositoryBase { try { - - DSLContext context = DSL.using(getConnection(true)); + DSLContext context = DSL.using(getConnectionPool(), SQLDialect.MYSQL); List updates = new ArrayList<>(); List inserts = new ArrayList<>(); @@ -133,7 +134,7 @@ public class StatsRepository extends RepositoryBase synchronized (this) { - context = DSL.using(getConnection()); + context = DSL.using(getConnectionPool(), SQLDialect.MYSQL); } Result> result = context.select(Tables.stats.name, Tables.accountStats.value).from(Tables.accountStats) diff --git a/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java b/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java index e052ee72e..ba4cd2729 100644 --- a/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java +++ b/Plugins/Mineplex.EnjinTranslator/src/mineplex/enjinTranslator/TempRepository.java @@ -2,6 +2,7 @@ package mineplex.enjinTranslator; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.column.ColumnInt; import mineplex.core.database.column.ColumnVarChar; @@ -12,7 +13,7 @@ public class TempRepository extends RepositoryBase public TempRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } public void addGemBooster(String name, int amount) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java index cad9425ef..f5be7a077 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/fields/repository/FieldRepository.java @@ -7,6 +7,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnByte; @@ -31,7 +32,7 @@ public class FieldRepository extends RepositoryBase public FieldRepository(JavaPlugin plugin) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); + super(plugin, DBPool.ACCOUNT); } public List getFieldBlocks(String server) diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java b/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java index 59e7e796c..af43ab9f5 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/mail/MailRepository.java @@ -6,9 +6,11 @@ import java.util.UUID; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.database.Tables; import mineplex.database.tables.records.MailRecord; + import org.jooq.DSLContext; import org.jooq.Result; import org.jooq.impl.DSL; @@ -19,8 +21,8 @@ public class MailRepository extends RepositoryBase public MailRepository(JavaPlugin plugin, MailManager manager) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); - + super(plugin, DBPool.ACCOUNT); + _manager = manager; } diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java index 796bde45d..20cb041e0 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/password/PasswordRepository.java @@ -7,6 +7,7 @@ import java.util.List; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.database.DBPool; import mineplex.core.database.RepositoryBase; import mineplex.core.database.ResultSetCallable; import mineplex.core.database.column.ColumnVarChar; @@ -23,8 +24,7 @@ public class PasswordRepository extends RepositoryBase public PasswordRepository(JavaPlugin plugin, String serverName) { - super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh"); - + super(plugin, DBPool.ACCOUNT); _serverName = serverName; }