Reformatted to follow PK standards

This commit is contained in:
jayoevans 2019-10-24 13:39:00 +10:00
parent 00093af01b
commit c05022aa01
22 changed files with 537 additions and 885 deletions

View file

@ -2,6 +2,7 @@ package com.projectkorra.projectkorra.ability;
import com.projectkorra.projectkorra.GeneralMethods;
import com.projectkorra.projectkorra.ability.util.MultiAbilityManager;
import com.projectkorra.projectkorra.firebending.FireBlast;
import com.projectkorra.projectkorra.module.DatabaseModule;
import com.projectkorra.projectkorra.module.ModuleManager;
import com.projectkorra.projectkorra.player.BendingPlayer;
@ -13,83 +14,75 @@ import org.bukkit.event.EventHandler;
import java.sql.SQLException;
public class AbilityManager extends DatabaseModule<AbilityRepository>
{
private final BendingPlayerManager _bendingPlayerManager;
public class AbilityManager extends DatabaseModule<AbilityRepository> {
private AbilityManager()
{
private final BendingPlayerManager bendingPlayerManager;
private AbilityManager() {
super("Ability", new AbilityRepository());
_bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class);
this.bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class);
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().createTables();
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
runSync(() ->
{
runSync(() -> {
log("Created database tables.");
});
});
registerAbilities();
}
private void registerAbilities() {
registerAbility(FireBlast.class);
}
private void registerAbility(Class<? extends Ability> abilityClass) {
// TODO
}
@EventHandler
public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event)
{
public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) {
BendingPlayer bendingPlayer = event.getBendingPlayer();
runAsync(() ->
{
try
{
runAsync(() -> {
try {
String[] abilities = getRepository().selectPlayerAbilities(bendingPlayer.getId());
bendingPlayer.setAbilities(abilities);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
}
public boolean bindAbility(Player player, String abilityName, int slot)
{
public boolean bindAbility(Player player, String abilityName, int slot) {
PlayerBindAbilityEvent playerBindAbilityEvent = new PlayerBindAbilityEvent(player, abilityName);
getPlugin().getServer().getPluginManager().callEvent(playerBindAbilityEvent);
if (playerBindAbilityEvent.isCancelled())
{
if (playerBindAbilityEvent.isCancelled()) {
String cancelMessage = playerBindAbilityEvent.getCancelMessage();
if (cancelMessage != null)
{
if (cancelMessage != null) {
GeneralMethods.sendBrandingMessage(player, cancelMessage);
}
return false;
}
BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player);
BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player);
bendingPlayer.setAbility(slot, abilityName);
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().insertPlayerAbility(bendingPlayer.getId(), abilityName, slot);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
@ -97,28 +90,22 @@ public class AbilityManager extends DatabaseModule<AbilityRepository>
return true;
}
public boolean unbindAbility(Player player, int slot)
{
BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player);
public boolean unbindAbility(Player player, int slot) {
BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player);
String abilityName = bendingPlayer.getAbility(slot);
if (abilityName == null)
{
if (abilityName == null) {
player.sendMessage("No ability bound");
return false;
}
bendingPlayer.setAbility(slot, null);
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().deletePlayerAbility(bendingPlayer.getId(), abilityName);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
@ -126,20 +113,15 @@ public class AbilityManager extends DatabaseModule<AbilityRepository>
return true;
}
public void clearBinds(Player player)
{
BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player);
public void clearBinds(Player player) {
BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player);
bendingPlayer.setAbilities(new String[9]);
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().deletePlayerAbilities(bendingPlayer.getId());
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});

View file

@ -8,8 +8,8 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AbilityRepository extends DatabaseRepository
{
public class AbilityRepository extends DatabaseRepository {
private static final DatabaseQuery CREATE_TABLE_PLAYER_ABILITIES = DatabaseQuery.newBuilder()
.mysql("CREATE TABLE IF NOT EXISTS pk_player_abilities (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(50) NOT NULL, slot TINYINT NOT NULL, PRIMARY KEY (player_id, ability_name), INDEX player_index (player_id), INDEX ability_index (ability_name));")
.sqlite("CREATE TABLE IF NOT EXISTS pk_player_abilities (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(50) NOT NULL, slot TINYINT NOT NULL, PRIMARY KEY (player_id, ability_name)); CREATE INDEX player_index ON pk_player_abilities (player_id); CREATE INDEX ability_index ON pk_player_abilities (ability_name);")
@ -31,35 +31,28 @@ public class AbilityRepository extends DatabaseRepository
.query("DELETE FROM pk_player_abilities WHERE player_id = ? AND ability_name = ?;")
.build();
protected void createTables() throws SQLException
{
protected void createTables() throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_PLAYER_ABILITIES.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_PLAYER_ABILITIES.getQuery())) {
statement.executeUpdate();
}
}
protected String[] selectPlayerAbilities(int playerId) throws SQLException
{
protected String[] selectPlayerAbilities(int playerId) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ABILITIES.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ABILITIES.getQuery())) {
statement.setInt(1, playerId);
String[] abilities = new String[9];
try (ResultSet rs = statement.executeQuery())
{
while (rs.next())
{
try (ResultSet rs = statement.executeQuery()) {
while (rs.next()) {
String abilityName = rs.getString("ability_name");
int slot = rs.getInt("slot");
if (slot < 0 || slot >= abilities.length)
{
if (slot < 0 || slot >= abilities.length) {
// TODO Log illegal slot
continue;
}
@ -72,12 +65,10 @@ public class AbilityRepository extends DatabaseRepository
}
}
protected void insertPlayerAbility(int playerId, String abilityName, int slot) throws SQLException
{
protected void insertPlayerAbility(int playerId, String abilityName, int slot) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ABILITY.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ABILITY.getQuery())) {
statement.setInt(1, playerId);
statement.setString(2, abilityName);
statement.setInt(3, slot);
@ -86,24 +77,20 @@ public class AbilityRepository extends DatabaseRepository
}
}
protected void deletePlayerAbilities(int playerId) throws SQLException
{
protected void deletePlayerAbilities(int playerId) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITIES.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITIES.getQuery())) {
statement.setInt(1, playerId);
statement.executeUpdate();
}
}
protected void deletePlayerAbility(int playerId, String abilityName) throws SQLException
{
protected void deletePlayerAbility(int playerId, String abilityName) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITY.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITY.getQuery())) {
statement.setInt(1, playerId);
statement.setString(2, abilityName);

View file

@ -18,63 +18,49 @@ import java.util.PriorityQueue;
import java.util.UUID;
import java.util.function.Function;
public class CooldownManager extends DatabaseModule<CooldownRepository>
{
private final BendingPlayerManager _bendingPlayerManager;
public class CooldownManager extends DatabaseModule<CooldownRepository> {
private final Map<UUID, Map<String, Cooldown>> _cooldownMap = new HashMap<>();
private final Map<UUID, PriorityQueue<Cooldown>> _cooldownQueue = new HashMap<>();
private final BendingPlayerManager bendingPlayerManager;
private final Function<UUID, PriorityQueue<Cooldown>> _queueFunction = uuid -> new PriorityQueue<>(Comparator.comparing(cooldown -> cooldown.ExpireTime));
private final Map<UUID, Map<String, Cooldown>> cooldownMap = new HashMap<>();
private final Map<UUID, PriorityQueue<Cooldown>> cooldownQueue = new HashMap<>();
private CooldownManager()
{
private final Function<UUID, PriorityQueue<Cooldown>> queueFunction = uuid -> new PriorityQueue<>(Comparator.comparing(cooldown -> cooldown.ExpireTime));
private CooldownManager() {
super("Cooldown", new CooldownRepository());
_bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class);
this.bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class);
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().createTables();
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
runTimer(() ->
{
_cooldownQueue.forEach((uuid, cooldowns) ->
{
runTimer(() -> {
this.cooldownQueue.forEach((uuid, cooldowns) -> {
long currentTime = System.currentTimeMillis();
while (!cooldowns.isEmpty())
{
while (!cooldowns.isEmpty()) {
Cooldown cooldown = cooldowns.peek();
if (currentTime < cooldown.ExpireTime)
{
if (currentTime < cooldown.ExpireTime) {
break;
}
_cooldownMap.get(uuid).remove(cooldown.AbilityName);
this.cooldownMap.get(uuid).remove(cooldown.AbilityName);
cooldowns.poll();
if (cooldown.Permanent)
{
int playerId = _bendingPlayerManager.getBendingPlayer(uuid).getId();
if (cooldown.Permanent) {
int playerId = this.bendingPlayerManager.getBendingPlayer(uuid).getId();
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().deleteCooldown(playerId, cooldown.AbilityName);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
@ -82,156 +68,126 @@ public class CooldownManager extends DatabaseModule<CooldownRepository>
}
});
_cooldownMap.values().removeIf(Map::isEmpty);
_cooldownQueue.values().removeIf(PriorityQueue::isEmpty);
this.cooldownMap.values().removeIf(Map::isEmpty);
this.cooldownQueue.values().removeIf(PriorityQueue::isEmpty);
}, 1, 1);
}
@EventHandler
public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event)
{
public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) {
Player player = event.getPlayer();
BendingPlayer bendingPlayer = event.getBendingPlayer();
runAsync(() ->
{
try
{
runAsync(() -> {
try {
Map<String, Cooldown> cooldowns = getRepository().selectCooldowns(bendingPlayer.getId());
_cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).putAll(cooldowns);
_cooldownQueue.computeIfAbsent(player.getUniqueId(), _queueFunction).addAll(cooldowns.values());
}
catch (SQLException e)
{
this.cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).putAll(cooldowns);
this.cooldownQueue.computeIfAbsent(player.getUniqueId(), queueFunction).addAll(cooldowns.values());
} catch (SQLException e) {
e.printStackTrace();
}
});
}
@EventHandler
public void onQuit(PlayerQuitEvent event)
{
_cooldownMap.remove(event.getPlayer().getUniqueId());
_cooldownQueue.remove(event.getPlayer().getUniqueId());
public void onQuit(PlayerQuitEvent event) {
this.cooldownMap.remove(event.getPlayer().getUniqueId());
this.cooldownQueue.remove(event.getPlayer().getUniqueId());
}
public void addCooldown(Player player, String abilityName, long duration, boolean permanent)
{
if (duration <= 0)
{
public void addCooldown(Player player, String abilityName, long duration, boolean permanent) {
if (duration <= 0) {
return;
}
PlayerCooldownChangeEvent event = new PlayerCooldownChangeEvent(player, abilityName, duration, PlayerCooldownChangeEvent.Result.ADDED);
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled())
{
if (event.isCancelled()) {
return;
}
long expireTime = System.currentTimeMillis() + duration;
Cooldown cooldown = new Cooldown(abilityName, expireTime, permanent);
_cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).put(abilityName, cooldown);
_cooldownQueue.computeIfAbsent(player.getUniqueId(), _queueFunction).add(cooldown);
this.cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).put(abilityName, cooldown);
this.cooldownQueue.computeIfAbsent(player.getUniqueId(), queueFunction).add(cooldown);
if (permanent)
{
int playerId = _bendingPlayerManager.getBendingPlayer(player).getId();
if (permanent) {
int playerId = this.bendingPlayerManager.getBendingPlayer(player).getId();
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().insertCooldown(playerId, abilityName, expireTime);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
}
}
public long getCooldown(Player player, String abilityName)
{
Map<String, Cooldown> cooldowns = _cooldownMap.get(player.getUniqueId());
public long getCooldown(Player player, String abilityName) {
Map<String, Cooldown> cooldowns = this.cooldownMap.get(player.getUniqueId());
if (cooldowns != null && cooldowns.containsKey(abilityName))
{
if (cooldowns != null && cooldowns.containsKey(abilityName)) {
return cooldowns.get(abilityName).ExpireTime;
}
return -1L;
}
public boolean isOnCooldown(Player player, String abilityName)
{
Map<String, Cooldown> cooldowns = _cooldownMap.get(player.getUniqueId());
public boolean isOnCooldown(Player player, String abilityName) {
Map<String, Cooldown> cooldowns = this.cooldownMap.get(player.getUniqueId());
return cooldowns != null && cooldowns.containsKey(abilityName);
}
public void removeCooldown(Player player, String abilityName)
{
public void removeCooldown(Player player, String abilityName) {
UUID uuid = player.getUniqueId();
Map<String, Cooldown> cooldowns = _cooldownMap.get(player.getUniqueId());
Map<String, Cooldown> cooldowns = this.cooldownMap.get(player.getUniqueId());
if (cooldowns == null)
{
if (cooldowns == null) {
return;
}
Cooldown cooldown = cooldowns.remove(abilityName);
if (cooldown == null)
{
if (cooldown == null) {
return;
}
if (_cooldownQueue.containsKey(uuid))
{
_cooldownQueue.get(uuid).remove(cooldown);
if (this.cooldownQueue.containsKey(uuid)) {
this.cooldownQueue.get(uuid).remove(cooldown);
}
if (cooldown.Permanent)
{
int playerId = _bendingPlayerManager.getBendingPlayer(player).getId();
if (cooldown.Permanent) {
int playerId = this.bendingPlayerManager.getBendingPlayer(player).getId();
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().deleteCooldown(playerId, cooldown.AbilityName);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
}
}
public static class Cooldown
{
public static class Cooldown {
final String AbilityName;
final long ExpireTime;
final boolean Permanent;
public Cooldown(String abilityName, long expireTime)
{
public Cooldown(String abilityName, long expireTime) {
this(abilityName, expireTime, false);
}
public Cooldown(String abilityName, long expireTime, boolean permanent)
{
public Cooldown(String abilityName, long expireTime, boolean permanent) {
AbilityName = abilityName;
ExpireTime = expireTime;
Permanent = permanent;
}
}
}

View file

@ -10,8 +10,8 @@ import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class CooldownRepository extends DatabaseRepository
{
public class CooldownRepository extends DatabaseRepository {
private static final DatabaseQuery CREATE_TABLE_COOLDOWNS = DatabaseQuery.newBuilder()
.query("CREATE TABLE IF NOT EXISTS pk_cooldowns (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(100) NOT NULL, expire_time BIGINT NOT NULL, PRIMARY KEY (player_id, ability_name));")
.build();
@ -28,30 +28,24 @@ public class CooldownRepository extends DatabaseRepository
.query("DELETE FROM pk_cooldowns WHERE player_id = ? AND ability_name = ?;")
.build();
protected void createTables() throws SQLException
{
protected void createTables() throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_COOLDOWNS.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_COOLDOWNS.getQuery())) {
statement.executeUpdate();
}
}
protected Map<String, CooldownManager.Cooldown> selectCooldowns(int playerId) throws SQLException
{
protected Map<String, CooldownManager.Cooldown> selectCooldowns(int playerId) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(SELECT_COOLDOWNS.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(SELECT_COOLDOWNS.getQuery())) {
statement.setInt(1, playerId);
Map<String, CooldownManager.Cooldown> cooldowns = new HashMap<>();
try (ResultSet rs = statement.executeQuery())
{
while (rs.next())
{
try (ResultSet rs = statement.executeQuery()) {
while (rs.next()) {
String abilityName = rs.getString("ability_name");
long expireTime = rs.getLong("expire_time");
@ -63,12 +57,10 @@ public class CooldownRepository extends DatabaseRepository
}
}
protected void insertCooldown(int playerId, String abilityName, long expireTime) throws SQLException
{
protected void insertCooldown(int playerId, String abilityName, long expireTime) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(INSERT_COOLDOWN.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(INSERT_COOLDOWN.getQuery())) {
statement.setInt(1, playerId);
statement.setString(2, abilityName);
statement.setLong(3, expireTime);
@ -77,12 +69,10 @@ public class CooldownRepository extends DatabaseRepository
}
}
protected void deleteCooldown(int playerId, String abilityName) throws SQLException
{
protected void deleteCooldown(int playerId, String abilityName) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(DELETE_COOLDOWN.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(DELETE_COOLDOWN.getQuery())) {
statement.setInt(1, playerId);
statement.setString(2, abilityName);

View file

@ -2,8 +2,8 @@ package com.projectkorra.projectkorra.database;
import com.projectkorra.projectkorra.configuration.Config;
public class DatabaseConfig implements Config
{
public class DatabaseConfig implements Config {
public final DatabaseManager.Engine Engine = DatabaseManager.Engine.SQLITE;
public final String SQLite_File = "projectkorra.sql";
@ -15,14 +15,12 @@ public class DatabaseConfig implements Config
public final String MySQL_Password = "password";
@Override
public String getName()
{
public String getName() {
return "Database";
}
@Override
public String[] getParents()
{
public String[] getParents() {
return new String[0];
}
}

View file

@ -8,50 +8,45 @@ import com.projectkorra.projectkorra.module.Module;
import java.util.logging.Level;
public class DatabaseManager extends Module
{
private final DatabaseConfig _config;
private final SQLDatabase _database;
public class DatabaseManager extends Module {
private DatabaseManager()
{
private final DatabaseConfig config;
private final SQLDatabase database;
private DatabaseManager() {
super("Database");
_config = ConfigManager.getConfig(DatabaseConfig.class);
this.config = ConfigManager.getConfig(DatabaseConfig.class);
switch (_config.Engine)
{
case MYSQL:
_database = new MySQLDatabase(_config);
break;
case SQLITE:
_database = new SQLiteDatabase(this, _config);
break;
default:
log(Level.SEVERE, "Unknown database engine.");
_database = null;
break;
switch (this.config.Engine) {
case MYSQL:
this.database = new MySQLDatabase(this.config);
break;
case SQLITE:
this.database = new SQLiteDatabase(this, this.config);
break;
default:
log(Level.SEVERE, "Unknown database engine.");
this.database = null;
break;
}
}
public DatabaseConfig getConfig()
{
return _config;
public DatabaseConfig getConfig() {
return this.config;
}
public SQLDatabase getDatabase()
{
return _database;
public SQLDatabase getDatabase() {
return this.database;
}
@Override
public void onDisable()
{
_database.close();
public void onDisable() {
this.database.close();
}
public enum Engine
{
MYSQL, SQLITE;
public enum Engine {
MYSQL,
SQLITE;
}
}

View file

@ -2,62 +2,54 @@ package com.projectkorra.projectkorra.database;
import com.projectkorra.projectkorra.module.ModuleManager;
public class DatabaseQuery
{
private final String _mysql;
private final String _sqlite;
public class DatabaseQuery {
private DatabaseQuery(String mysql, String sqlite)
{
_mysql = mysql;
_sqlite = sqlite;
private final String mysql;
private final String sqlite;
private DatabaseQuery(String mysql, String sqlite) {
this.mysql = mysql;
this.sqlite = sqlite;
}
public String getQuery()
{
switch (ModuleManager.getModule(DatabaseManager.class).getConfig().Engine)
{
case MYSQL:
return _mysql;
case SQLITE:
return _sqlite;
public String getQuery() {
switch (ModuleManager.getModule(DatabaseManager.class).getConfig().Engine) {
case MYSQL:
return this.mysql;
case SQLITE:
return this.sqlite;
}
return null;
}
public static Builder newBuilder()
{
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder
{
private String _mysql;
private String _sqlite;
public static final class Builder {
public Builder mysql(String mysql)
{
_mysql = mysql;
private String mysql;
private String sqlite;
public Builder mysql(String mysql) {
this.mysql = mysql;
return this;
}
public Builder sqlite(String sqlite)
{
_sqlite = sqlite;
public Builder sqlite(String sqlite) {
this.sqlite = sqlite;
return this;
}
public Builder query(String query)
{
_mysql = query;
_sqlite = query;
public Builder query(String query) {
this.mysql = query;
this.sqlite = query;
return this;
}
public DatabaseQuery build()
{
return new DatabaseQuery(_mysql, _sqlite);
public DatabaseQuery build() {
return new DatabaseQuery(this.mysql, this.sqlite);
}
}
}

View file

@ -3,17 +3,15 @@ package com.projectkorra.projectkorra.database;
import com.projectkorra.projectkorra.database.engine.SQLDatabase;
import com.projectkorra.projectkorra.module.ModuleManager;
public abstract class DatabaseRepository
{
public abstract class DatabaseRepository {
private final DatabaseManager databaseManager;
public DatabaseRepository()
{
public DatabaseRepository() {
this.databaseManager = ModuleManager.getModule(DatabaseManager.class);
}
protected SQLDatabase getDatabase()
{
return databaseManager.getDatabase();
protected SQLDatabase getDatabase() {
return this.databaseManager.getDatabase();
}
}

View file

@ -7,12 +7,11 @@ import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class MySQLDatabase implements SQLDatabase
{
private final HikariDataSource _hikari;
public class MySQLDatabase implements SQLDatabase {
public MySQLDatabase(DatabaseConfig databaseConfig)
{
private final HikariDataSource hikari;
public MySQLDatabase(DatabaseConfig databaseConfig) {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl("jdbc:mysql://" + databaseConfig.MySQL_IP + ":" + databaseConfig.MySQL_Port + "/" + databaseConfig.MySQL_DatabaseName);
@ -23,26 +22,21 @@ public class MySQLDatabase implements SQLDatabase
hikariConfig.setMaximumPoolSize(10);
hikariConfig.setConnectionTimeout(10000);
_hikari = new HikariDataSource(hikariConfig);
this.hikari = new HikariDataSource(hikariConfig);
}
@Override
public Connection getConnection()
{
try (Connection connection = _hikari.getConnection())
{
public Connection getConnection() {
try (Connection connection = this.hikari.getConnection()) {
return connection;
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
@Override
public void close()
{
_hikari.close();
public void close() {
this.hikari.close();
}
}

View file

@ -2,8 +2,8 @@ package com.projectkorra.projectkorra.database.engine;
import java.sql.Connection;
public interface SQLDatabase
{
public interface SQLDatabase {
Connection getConnection();
void close();

View file

@ -9,28 +9,22 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLiteDatabase implements SQLDatabase
{
private final File _databaseFile;
private Connection _connection;
public class SQLiteDatabase implements SQLDatabase {
public SQLiteDatabase(DatabaseManager databaseManager, DatabaseConfig databaseConfig)
{
_databaseFile = new File(databaseManager.getPlugin().getDataFolder(), databaseConfig.SQLite_File);
private final File databaseFile;
private Connection connection;
if (!_databaseFile.getParentFile().exists())
{
_databaseFile.getParentFile().mkdirs();
public SQLiteDatabase(DatabaseManager databaseManager, DatabaseConfig databaseConfig) {
this.databaseFile = new File(databaseManager.getPlugin().getDataFolder(), databaseConfig.SQLite_File);
if (!this.databaseFile.getParentFile().exists()) {
this.databaseFile.getParentFile().mkdirs();
}
if (!_databaseFile.exists())
{
try
{
_databaseFile.createNewFile();
}
catch (IOException e)
{
if (!this.databaseFile.exists()) {
try {
this.databaseFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
@ -38,45 +32,32 @@ public class SQLiteDatabase implements SQLDatabase
open();
}
public void open()
{
try
{
_connection = DriverManager.getConnection("jdbc:sqlite:" + _databaseFile.getAbsolutePath());
}
catch (SQLException e)
{
public void open() {
try {
this.connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public Connection getConnection()
{
try
{
if (_connection == null || _connection.isClosed())
{
public Connection getConnection() {
try {
if (this.connection == null || this.connection.isClosed()) {
open();
}
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
return _connection;
return this.connection;
}
@Override
public void close()
{
try
{
_connection.close();
}
catch (SQLException e)
{
public void close() {
try {
this.connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

View file

@ -2,43 +2,37 @@ package com.projectkorra.projectkorra.element;
import org.bukkit.ChatColor;
public class Element
{
private final int _elementId;
private final String _elementName;
private final String _displayName;
private final ChatColor _color;
public class Element {
public Element(int elementId, String elementName, String displayName, ChatColor color)
{
_elementId = elementId;
_elementName = elementName;
_displayName = displayName;
_color = color;
private final int elementId;
private final String elementName;
private final String displayName;
private final ChatColor color;
public Element(int elementId, String elementName, String displayName, ChatColor color) {
this.elementId = elementId;
this.elementName = elementName;
this.displayName = displayName;
this.color = color;
}
public int getId()
{
return _elementId;
public int getId() {
return this.elementId;
}
public String getName()
{
return _elementName;
public String getName() {
return this.elementName;
}
public String getDisplayName()
{
return _displayName;
public String getDisplayName() {
return this.displayName;
}
public ChatColor getColor()
{
return _color;
public ChatColor getColor() {
return this.color;
}
public String getColoredName()
{
return _color + _displayName;
public String getColoredName() {
return this.color + this.displayName;
}
}

View file

@ -17,20 +17,20 @@ import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ElementManager extends DatabaseModule<ElementRepository>
{
public class ElementManager extends DatabaseModule<ElementRepository> {
private static final String WATER = "water", EARTH = "earth", FIRE = "fire", AIR = "air", CHI = "chi", AVATAR = "avatar";
private static final String BLOOD = "blood", HEALING = "healing", ICE = "ice", PLANT = "plant";
private static final String LAVA = "lava", METAL = "metal", SAND = "sand";
private static final String COMBUSTION = "combustion", LIGHTNING = "lightning";
private static final String FLIGHT = "flight", SPIRITUAL = "spiritual";
private final BendingPlayerManager _bendingPlayerManager;
private final BendingPlayerManager bendingPlayerManager;
private final Map<Integer, Element> _elements = new HashMap<>();
private final Map<String, Element> _names = new HashMap<>();
private final Map<Integer, Element> elements = new HashMap<>();
private final Map<String, Element> names = new HashMap<>();
private final String _nameRegex = "[a-zA-Z]+";
private final String nameRegex = "[a-zA-Z]+";
private Element water, earth, fire, air, chi, avatar;
private SubElement blood, healing, ice, plant;
@ -38,98 +38,79 @@ public class ElementManager extends DatabaseModule<ElementRepository>
private SubElement combustion, lightning;
private SubElement flight, spiritual;
private ElementManager()
{
private ElementManager() {
super("Element", new ElementRepository());
_bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class);
this.bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class);
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().createTables();
// Waterbending
water = addElement(WATER, "Water", ChatColor.AQUA);
blood = addSubElement(BLOOD, "Blood", ChatColor.DARK_AQUA, water);
healing = addSubElement(HEALING, "Healing", ChatColor.DARK_AQUA, water);
ice = addSubElement(ICE, "Ice", ChatColor.DARK_AQUA, water);
plant = addSubElement(PLANT, "Plant", ChatColor.DARK_AQUA, water);
this.water = addElement(WATER, "Water", ChatColor.AQUA);
this.blood = addSubElement(BLOOD, "Blood", ChatColor.DARK_AQUA, this.water);
this.healing = addSubElement(HEALING, "Healing", ChatColor.DARK_AQUA, this.water);
this.ice = addSubElement(ICE, "Ice", ChatColor.DARK_AQUA, this.water);
this.plant = addSubElement(PLANT, "Plant", ChatColor.DARK_AQUA, this.water);
// Earthbending
earth = addElement(EARTH, "Earth", ChatColor.AQUA);
lava =addSubElement(LAVA, "Lava", ChatColor.DARK_GREEN, earth);
metal = addSubElement(METAL, "Metal", ChatColor.DARK_GREEN, earth);
sand = addSubElement(SAND, "Sand", ChatColor.DARK_GREEN, earth);
this.earth = addElement(EARTH, "Earth", ChatColor.AQUA);
this.lava = addSubElement(LAVA, "Lava", ChatColor.DARK_GREEN, this.earth);
this.metal = addSubElement(METAL, "Metal", ChatColor.DARK_GREEN, this.earth);
this.sand = addSubElement(SAND, "Sand", ChatColor.DARK_GREEN, this.earth);
// Firebending
fire = addElement(FIRE, "Fire", ChatColor.RED);
combustion = addSubElement(COMBUSTION, "Combustion", ChatColor.DARK_RED, fire);
lightning = addSubElement(LIGHTNING, "Lightning", ChatColor.DARK_RED, fire);
this.fire = addElement(FIRE, "Fire", ChatColor.RED);
this.combustion = addSubElement(COMBUSTION, "Combustion", ChatColor.DARK_RED, this.fire);
this.lightning = addSubElement(LIGHTNING, "Lightning", ChatColor.DARK_RED, this.fire);
// Airbending
air = addElement(AIR, "Air", ChatColor.GRAY);
flight = addSubElement(FLIGHT, "Flight", ChatColor.DARK_GRAY, air);
spiritual = addSubElement(SPIRITUAL, "Spiritual", ChatColor.DARK_GRAY, air);
this.air = addElement(AIR, "Air", ChatColor.GRAY);
this.flight = addSubElement(FLIGHT, "Flight", ChatColor.DARK_GRAY, this.air);
this.spiritual = addSubElement(SPIRITUAL, "Spiritual", ChatColor.DARK_GRAY, this.air);
// Chiblocking
chi = addElement(CHI, "Chi", ChatColor.GOLD);
this.chi = addElement(CHI, "Chi", ChatColor.GOLD);
// Avatar
avatar = addElement(AVATAR, "Avatar", ChatColor.DARK_PURPLE);
}
catch (SQLException e)
{
this.avatar = addElement(AVATAR, "Avatar", ChatColor.DARK_PURPLE);
} catch (SQLException e) {
e.printStackTrace();
}
runSync(() ->
{
runSync(() -> {
log("Populated element database tables.");
});
});
}
@EventHandler
public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event)
{
public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) {
BendingPlayer bendingPlayer = event.getBendingPlayer();
runAsync(() ->
{
try
{
List<Element> elements = getRepository().selectPlayerElements(bendingPlayer.getId()).stream()
.map(_elements::get)
.collect(Collectors.toList());
runAsync(() -> {
try {
List<Element> elements = getRepository().selectPlayerElements(bendingPlayer.getId()).stream().map(this.elements::get).collect(Collectors.toList());
elements.forEach(bendingPlayer::addElement);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
}
public boolean addElement(Player player, Element element)
{
BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player);
public boolean addElement(Player player, Element element) {
BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player);
if (!bendingPlayer.addElement(element))
{
if (!bendingPlayer.addElement(element)) {
return false;
}
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().insertPlayerElement(bendingPlayer.getId(), element.getId());
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
@ -137,44 +118,33 @@ public class ElementManager extends DatabaseModule<ElementRepository>
return true;
}
public void setElement(Player player, Element element)
{
BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player);
public void setElement(Player player, Element element) {
BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player);
bendingPlayer.clearElements();
bendingPlayer.addElement(element);
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().deletePlayerElements(bendingPlayer.getId());
getRepository().insertPlayerElement(bendingPlayer.getId(), element.getId());
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
}
public boolean removeElement(Player player, Element element)
{
BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player);
public boolean removeElement(Player player, Element element) {
BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player);
if (!bendingPlayer.removeElement(element))
{
if (!bendingPlayer.removeElement(element)) {
return false;
}
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().deletePlayerElement(bendingPlayer.getId(), element.getId());
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
@ -182,148 +152,120 @@ public class ElementManager extends DatabaseModule<ElementRepository>
return true;
}
public void clearElements(Player player)
{
BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player);
public void clearElements(Player player) {
BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player);
bendingPlayer.clearElements();
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().deletePlayerElements(bendingPlayer.getId());
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
}
private Element addElement(String elementName, String displayName, ChatColor color)
{
private Element addElement(String elementName, String displayName, ChatColor color) {
int elementId = registerElement(elementName);
Element element = new Element(elementId, elementName, displayName, color);
_elements.put(elementId, element);
_names.put(elementName, element);
this.elements.put(elementId, element);
this.names.put(elementName, element);
return element;
}
private SubElement addSubElement(String elementName, String displayName, ChatColor color, Element parent)
{
private SubElement addSubElement(String elementName, String displayName, ChatColor color, Element parent) {
int elementId = registerElement(elementName);
SubElement element = new SubElement(elementId, elementName, displayName, color, parent);
_elements.put(elementId, element);
_names.put(elementName, element);
this.elements.put(elementId, element);
this.names.put(elementName, element);
return element;
}
private int registerElement(String elementName)
{
private int registerElement(String elementName) {
Preconditions.checkNotNull(elementName, "Element name cannot be null");
Preconditions.checkArgument(Pattern.matches(_nameRegex, elementName), "Element name must only contain letters and spaces");
Preconditions.checkArgument(Pattern.matches(this.nameRegex, elementName), "Element name must only contain letters and spaces");
try
{
try {
return getRepository().selectElemenetId(elementName);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
public Element getWater()
{
return water;
public Element getWater() {
return this.water;
}
public SubElement getBlood()
{
return blood;
public SubElement getBlood() {
return this.blood;
}
public SubElement getHealing()
{
return healing;
public SubElement getHealing() {
return this.healing;
}
public SubElement getIce()
{
return ice;
public SubElement getIce() {
return this.ice;
}
public SubElement getPlant()
{
return plant;
public SubElement getPlant() {
return this.plant;
}
public Element getEarth()
{
return earth;
public Element getEarth() {
return this.earth;
}
public SubElement getLava()
{
return lava;
public SubElement getLava() {
return this.lava;
}
public SubElement getMetal()
{
return metal;
public SubElement getMetal() {
return this.metal;
}
public SubElement getSand()
{
return sand;
public SubElement getSand() {
return this.sand;
}
public Element getFire()
{
return fire;
public Element getFire() {
return this.fire;
}
public SubElement getCombustion()
{
return combustion;
public SubElement getCombustion() {
return this.combustion;
}
public SubElement getLightning()
{
return lightning;
public SubElement getLightning() {
return this.lightning;
}
public Element getAir()
{
return air;
public Element getAir() {
return this.air;
}
public SubElement getFlight()
{
return flight;
public SubElement getFlight() {
return this.flight;
}
public SubElement getSpiritual()
{
return spiritual;
public SubElement getSpiritual() {
return this.spiritual;
}
public Element getChi()
{
return chi;
public Element getChi() {
return this.chi;
}
public Element getAvatar()
{
return avatar;
public Element getAvatar() {
return this.avatar;
}
}

View file

@ -3,20 +3,17 @@ package com.projectkorra.projectkorra.element;
import com.projectkorra.projectkorra.database.DatabaseQuery;
import com.projectkorra.projectkorra.database.DatabaseRepository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import java.util.HashSet;
import java.util.Set;
public class ElementRepository extends DatabaseRepository
{
public class ElementRepository extends DatabaseRepository {
private static final DatabaseQuery CREATE_TABLE_ELEMENTS = DatabaseQuery.newBuilder()
.mysql("CREATE TABLE IF NOT EXISTS pk_elements (element_id INTEGER PRIMARY KEY AUTO_INCREMENT, element_name VARCHAR(50) NOT NULL, UNIQUE INDEX name_index (element_name));")
.sqlite("CREATE TABLE IF NOT EXISTS pk_elements (element_id INTEGER PRIMARY KEY AUTOINCREMENT, element_name VARCHAR(50) NOT NULL); CREATE UNIQUE INDEX name_index ON pk_elements (element_name);")
.build();
private static final DatabaseQuery CREATE_TABLE_PLAYER_ELEMENTS = DatabaseQuery.newBuilder()
.mysql("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id), INDEX player_index (player_id), INDEX element_index (element_id));")
.sqlite("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id)); CREATE INDEX player_index ON pk_player_elements (player_id); CREATE INDEX element_index ON pk_player_elements (element_id);")
@ -46,33 +43,23 @@ public class ElementRepository extends DatabaseRepository
.query("DELETE FROM pk_player_elements WHERE player_id = ? AND element_id = ?;")
.build();
protected void createTables() throws SQLException
{
protected void createTables() throws SQLException {
Connection connection = getDatabase().getConnection();
try
(
PreparedStatement elements = connection.prepareStatement(CREATE_TABLE_ELEMENTS.getQuery());
PreparedStatement playerElements = connection.prepareStatement(CREATE_TABLE_PLAYER_ELEMENTS.getQuery())
)
{
try (PreparedStatement elements = connection.prepareStatement(CREATE_TABLE_ELEMENTS.getQuery()); PreparedStatement playerElements = connection.prepareStatement(CREATE_TABLE_PLAYER_ELEMENTS.getQuery())) {
elements.executeUpdate();
playerElements.executeUpdate();
}
}
protected int selectElemenetId(String elementName) throws SQLException
{
protected int selectElemenetId(String elementName) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(SELECT_ELEMENT_ID.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(SELECT_ELEMENT_ID.getQuery())) {
statement.setString(1, elementName);
try (ResultSet rs = statement.executeQuery())
{
if (!rs.next())
{
try (ResultSet rs = statement.executeQuery()) {
if (!rs.next()) {
return insertElementId(elementName);
}
@ -81,18 +68,15 @@ public class ElementRepository extends DatabaseRepository
}
}
private int insertElementId(String elementName) throws SQLException
{
private int insertElementId(String elementName) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(INSERT_ELEMENT_ID.getQuery(), Statement.RETURN_GENERATED_KEYS))
{
try (PreparedStatement statement = connection.prepareStatement(INSERT_ELEMENT_ID.getQuery(), Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, elementName);
statement.executeUpdate();
try (ResultSet rs = statement.getGeneratedKeys())
{
try (ResultSet rs = statement.getGeneratedKeys()) {
rs.next();
return rs.getInt(1);
@ -100,20 +84,16 @@ public class ElementRepository extends DatabaseRepository
}
}
protected Set<Integer> selectPlayerElements(int playerId) throws SQLException
{
protected Set<Integer> selectPlayerElements(int playerId) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ELEMENTS.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ELEMENTS.getQuery())) {
statement.setInt(1, playerId);
Set<Integer> elements = new HashSet<>();
try (ResultSet rs = statement.executeQuery())
{
while (rs.next())
{
try (ResultSet rs = statement.executeQuery()) {
while (rs.next()) {
elements.add(rs.getInt("element_id"));
}
@ -122,12 +102,10 @@ public class ElementRepository extends DatabaseRepository
}
}
protected void insertPlayerElement(int playerId, int elementId) throws SQLException
{
protected void insertPlayerElement(int playerId, int elementId) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ELEMENT.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ELEMENT.getQuery())) {
statement.setInt(1, playerId);
statement.setInt(2, elementId);
@ -135,24 +113,20 @@ public class ElementRepository extends DatabaseRepository
}
}
protected void deletePlayerElements(int playerId) throws SQLException
{
protected void deletePlayerElements(int playerId) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENTS.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENTS.getQuery())) {
statement.setInt(1, playerId);
statement.executeUpdate();
}
}
protected void deletePlayerElement(int playerId, int elementId) throws SQLException
{
protected void deletePlayerElement(int playerId, int elementId) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENT.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENT.getQuery())) {
statement.setInt(1, playerId);
statement.setInt(2, elementId);

View file

@ -2,19 +2,17 @@ package com.projectkorra.projectkorra.element;
import org.bukkit.ChatColor;
public class SubElement extends Element
{
private final Element _parent;
public class SubElement extends Element {
public SubElement(int elementId, String elementName, String displayName, ChatColor color, Element parent)
{
private final Element parent;
public SubElement(int elementId, String elementName, String displayName, ChatColor color, Element parent) {
super(elementId, elementName, displayName, color);
_parent = parent;
this.parent = parent;
}
public Element getParent()
{
return _parent;
public Element getParent() {
return this.parent;
}
}

View file

@ -2,19 +2,17 @@ package com.projectkorra.projectkorra.module;
import com.projectkorra.projectkorra.database.DatabaseRepository;
public abstract class DatabaseModule<T extends DatabaseRepository> extends Module
{
public abstract class DatabaseModule<T extends DatabaseRepository> extends Module {
private final T repository;
protected DatabaseModule(String name, T repository)
{
protected DatabaseModule(String name, T repository) {
super(name);
this.repository = repository;
}
protected T getRepository()
{
protected T getRepository() {
return this.repository;
}
}

View file

@ -9,20 +9,18 @@ import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Level;
public abstract class Module implements Listener
{
public abstract class Module implements Listener {
private static final String LOG_FORMAT = "(%s) %s";
private final String name;
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
protected Module(String name)
{
protected Module(String name) {
this.name = name;
}
protected final void enable()
{
protected final void enable() {
long startTime = System.currentTimeMillis();
log("Enabling...");
@ -33,13 +31,11 @@ public abstract class Module implements Listener
log(String.format("Enabled! [%sms]", finishTime - startTime));
}
public void onEnable()
{
public void onEnable() {
}
protected final void disable()
{
protected final void disable() {
long startTime = System.currentTimeMillis();
log("Disabling...");
@ -50,53 +46,43 @@ public abstract class Module implements Listener
log(String.format("Disabled! [%sms]", finishTime - startTime));
}
public void onDisable()
{
public void onDisable() {
}
protected final void runSync(Runnable runnable)
{
protected final void runSync(Runnable runnable) {
getPlugin().getServer().getScheduler().runTask(getPlugin(), runnable);
}
protected final void runAsync(Runnable runnable)
{
protected final void runAsync(Runnable runnable) {
getPlugin().getServer().getScheduler().runTaskAsynchronously(getPlugin(), runnable);
}
protected final void runTimer(Runnable runnable, long delay, long period)
{
protected final void runTimer(Runnable runnable, long delay, long period) {
getPlugin().getServer().getScheduler().runTaskTimer(getPlugin(), runnable, delay, period);
}
protected final void runAsyncTimer(Runnable runnable, long delay, long period)
{
protected final void runAsyncTimer(Runnable runnable, long delay, long period) {
getPlugin().getServer().getScheduler().runTaskTimerAsynchronously(getPlugin(), runnable, delay, period);
}
public String getName()
{
public String getName() {
return this.name;
}
protected Gson getGson()
{
protected Gson getGson() {
return this.gson;
}
public final void log(String message)
{
public final void log(String message) {
log(Level.INFO, message);
}
public final void log(Level level, String message)
{
public final void log(Level level, String message) {
getPlugin().getLogger().log(level, String.format(LOG_FORMAT, getName(), message));
}
public ProjectKorra getPlugin()
{
public ProjectKorra getPlugin() {
return JavaPlugin.getPlugin(ProjectKorra.class);
}
}

View file

@ -79,5 +79,4 @@ public class ModuleManager {
getModule(BendingPlayerManager.class).disable();
getModule(DatabaseManager.class).disable();
}
}

View file

@ -11,14 +11,10 @@ import com.projectkorra.projectkorra.element.ElementManager;
import com.projectkorra.projectkorra.module.ModuleManager;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.*;
public class BendingPlayer {
public class BendingPlayer
{
private final BendingPlayerManager manager;
private final ElementManager elementManager;
private final AbilityManager abilityManager;
@ -42,8 +38,7 @@ public class BendingPlayer
private boolean chiBlocked;
private long slowTime;
public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin)
{
public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin) {
this.manager = ModuleManager.getModule(BendingPlayerManager.class);
this.elementManager = ModuleManager.getModule(ElementManager.class);
this.abilityManager = ModuleManager.getModule(AbilityManager.class);
@ -60,267 +55,213 @@ public class BendingPlayer
this.abilities = new String[9];
}
public Set<Element> getElements()
{
public Set<Element> getElements() {
return new HashSet<>(this.elements);
}
public boolean addElement(Element element)
{
public boolean addElement(Element element) {
return this.elements.add(element);
}
public boolean removeElement(Element element)
{
public boolean removeElement(Element element) {
return this.elements.remove(element);
}
public void clearElements()
{
public void clearElements() {
this.elements.clear();
}
public boolean hasElement(Element element)
{
if (element.equals(elementManager.getAvatar()))
{
public boolean hasElement(Element element) {
if (element.equals(this.elementManager.getAvatar())) {
return this.player.hasPermission("bending.avatar");
}
return this.elements.contains(element);
}
public boolean canBloodbend()
{
return this.elements.contains(elementManager.getBlood());
public boolean canBloodbend() {
return this.elements.contains(this.elementManager.getBlood());
}
public boolean canUseHealing()
{
return this.elements.contains(elementManager.getHealing());
public boolean canUseHealing() {
return this.elements.contains(this.elementManager.getHealing());
}
public boolean canIcebend()
{
return this.elements.contains(elementManager.getIce());
public boolean canIcebend() {
return this.elements.contains(this.elementManager.getIce());
}
public boolean canPlantbend()
{
return this.elements.contains(elementManager.getPlant());
public boolean canPlantbend() {
return this.elements.contains(this.elementManager.getPlant());
}
public boolean canLavabend()
{
return this.elements.contains(elementManager.getLava());
public boolean canLavabend() {
return this.elements.contains(this.elementManager.getLava());
}
public boolean canMetalbend()
{
return this.elements.contains(elementManager.getMetal());
public boolean canMetalbend() {
return this.elements.contains(this.elementManager.getMetal());
}
public boolean canSandbend()
{
return this.elements.contains(elementManager.getSand());
public boolean canSandbend() {
return this.elements.contains(this.elementManager.getSand());
}
public boolean canCombustionbend()
{
return this.elements.contains(elementManager.getCombustion());
public boolean canCombustionbend() {
return this.elements.contains(this.elementManager.getCombustion());
}
public boolean canUseLightning()
{
return this.elements.contains(elementManager.getLightning());
public boolean canUseLightning() {
return this.elements.contains(this.elementManager.getLightning());
}
public boolean canUseFlight()
{
return this.elements.contains(elementManager.getFlight());
public boolean canUseFlight() {
return this.elements.contains(this.elementManager.getFlight());
}
public boolean canUseSpiritual()
{
return this.elements.contains(elementManager.getSpiritual());
public boolean canUseSpiritual() {
return this.elements.contains(this.elementManager.getSpiritual());
}
public boolean isElementToggled(Element element)
{
public boolean isElementToggled(Element element) {
return this.toggledElements.contains(element);
}
public void toggleElement(Element element)
{
if (this.toggledElements.contains(element))
{
public void toggleElement(Element element) {
if (this.toggledElements.contains(element)) {
this.toggledElements.remove(element);
}
else
{
} else {
this.toggledElements.add(element);
}
}
public CoreAbility getBoundAbility()
{
public CoreAbility getBoundAbility() {
return CoreAbility.getAbility(getBoundAbilityName());
}
public String getBoundAbilityName()
{
public String getBoundAbilityName() {
int slot = this.player.getInventory().getHeldItemSlot();
return this.abilities[slot];
}
public String getAbility(int slot)
{
public String getAbility(int slot) {
return this.abilities[slot];
}
public List<String> getAbilities()
{
public List<String> getAbilities() {
return Arrays.asList(this.abilities);
}
public void setAbilities(String[] abilities)
{
public void setAbilities(String[] abilities) {
System.arraycopy(abilities, 0, this.abilities, 0, 9);
}
public void setAbility(int slot, String abilityName)
{
public void setAbility(int slot, String abilityName) {
this.abilities[slot] = abilityName;
}
public void addCooldown(Ability ability)
{
public void addCooldown(Ability ability) {
addCooldown(ability, ability.getCooldown());
}
public void addCooldown(Ability ability, long duration)
{
public void addCooldown(Ability ability, long duration) {
addCooldown(ability.getName(), duration);
}
public void addCooldown(Ability ability, long duration, boolean permanent)
{
public void addCooldown(Ability ability, long duration, boolean permanent) {
addCooldown(ability.getName(), duration, permanent);
}
public void addCooldown(String abilityName, long duration)
{
public void addCooldown(String abilityName, long duration) {
addCooldown(abilityName, duration, false);
}
public void addCooldown(String abilityName, long duration, boolean permanent)
{
cooldownManager.addCooldown(this.player, abilityName, duration, permanent);
public void addCooldown(String abilityName, long duration, boolean permanent) {
this.cooldownManager.addCooldown(this.player, abilityName, duration, permanent);
}
public boolean isOnCooldown(Ability ability)
{
public boolean isOnCooldown(Ability ability) {
return isOnCooldown(ability.getName());
}
public boolean isOnCooldown(String abilityName)
{
return cooldownManager.isOnCooldown(this.player, abilityName);
public boolean isOnCooldown(String abilityName) {
return this.cooldownManager.isOnCooldown(this.player, abilityName);
}
public void removeCooldown(Ability ability)
{
public void removeCooldown(Ability ability) {
removeCoolldown(ability.getName());
}
public void removeCoolldown(String abilityName)
{
cooldownManager.removeCooldown(this.player, abilityName);
public void removeCoolldown(String abilityName) {
this.cooldownManager.removeCooldown(this.player, abilityName);
}
public ChiAbility getStance()
{
public ChiAbility getStance() {
return this.stance;
}
public void setStance(ChiAbility stance)
{
public void setStance(ChiAbility stance) {
this.stance = stance;
}
public boolean isBendingRemoved()
{
public boolean isBendingRemoved() {
return this.bendingRemoved;
}
protected void setBendingRemoved(boolean bendingRemoved)
{
protected void setBendingRemoved(boolean bendingRemoved) {
this.bendingRemoved = bendingRemoved;
}
public boolean isToggled()
{
public boolean isToggled() {
return this.toggled;
}
public void toggleBending()
{
public void toggleBending() {
this.toggled = !this.toggled;
PassiveManager.registerPassives(this.player); // TODO redo this passive system
}
public boolean isTremorSensing()
{
public boolean isTremorSensing() {
return this.tremorSense;
}
public void toggleTremorSense()
{
public void toggleTremorSense() {
this.tremorSense = !this.tremorSense;
}
public boolean isIlluminating()
{
public boolean isIlluminating() {
return this.illumination;
}
public void toggleIllumination()
{
public void toggleIllumination() {
this.illumination = !this.illumination;
}
public boolean isChiBlocked()
{
public boolean isChiBlocked() {
return this.chiBlocked;
}
public void blockChi()
{
public void blockChi() {
this.chiBlocked = true;
}
public void unblockChi()
{
public void unblockChi() {
this.chiBlocked = false;
}
public boolean canBeSlowed()
{
public boolean canBeSlowed() {
return System.currentTimeMillis() > this.slowTime;
}
public void slow(long cooldown)
{
public void slow(long cooldown) {
this.slowTime = System.currentTimeMillis() + cooldown;
}
public int getId()
{
public int getId() {
return this.playerId;
}
public long getFirstLogin()
{
public long getFirstLogin() {
return this.firstLogin;
}
}

View file

@ -4,32 +4,28 @@ import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
public class BendingPlayerLoadedEvent extends PlayerEvent
{
public class BendingPlayerLoadedEvent extends PlayerEvent {
private static final HandlerList HANDLER_LIST = new HandlerList();
private final BendingPlayer _bendingPlayer;
private final BendingPlayer bendingPlayer;
public BendingPlayerLoadedEvent(Player player, BendingPlayer bendingPlayer)
{
public BendingPlayerLoadedEvent(Player player, BendingPlayer bendingPlayer) {
super(player);
_bendingPlayer = bendingPlayer;
this.bendingPlayer = bendingPlayer;
}
public BendingPlayer getBendingPlayer()
{
return _bendingPlayer;
public BendingPlayer getBendingPlayer() {
return this.bendingPlayer;
}
@Override
public HandlerList getHandlers()
{
public HandlerList getHandlers() {
return HANDLER_LIST;
}
public static HandlerList getHandlerList()
{
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
}

View file

@ -10,141 +10,110 @@ import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.*;
public class BendingPlayerManager extends DatabaseModule<BendingPlayerRepository>
{
private final Map<UUID, BendingPlayer> _players = new HashMap<>();
public class BendingPlayerManager extends DatabaseModule<BendingPlayerRepository> {
private final Set<UUID> _disconnected = new HashSet<>();
private final long _databaseSyncInterval = 20 * 30;
private final Map<UUID, BendingPlayer> players = new HashMap<>();
private BendingPlayerManager()
{
private final Set<UUID> disconnected = new HashSet<>();
private final long databaseSyncInterval = 20 * 30;
private BendingPlayerManager() {
super("Bending Player", new BendingPlayerRepository());
runAsync(() ->
{
try
{
runAsync(() -> {
try {
getRepository().createTables();
for (Player player : getPlugin().getServer().getOnlinePlayers())
{
for (Player player : getPlugin().getServer().getOnlinePlayers()) {
loadBendingPlayer(player);
}
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
runTimer(() ->
{
_disconnected.forEach(_players::remove);
_disconnected.clear();
}, _databaseSyncInterval, _databaseSyncInterval);
runTimer(() -> {
this.disconnected.forEach(this.players::remove);
this.disconnected.clear();
}, this.databaseSyncInterval, this.databaseSyncInterval);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onLogin(PlayerLoginEvent event)
{
if (_disconnected.remove(event.getPlayer().getUniqueId()))
{
public void onLogin(PlayerLoginEvent event) {
if (this.disconnected.remove(event.getPlayer().getUniqueId())) {
return;
}
runAsync(() ->
{
runAsync(() -> {
loadBendingPlayer(event.getPlayer());
});
}
@EventHandler
public void onQuit(PlayerQuitEvent event)
{
_disconnected.add(event.getPlayer().getUniqueId());
public void onQuit(PlayerQuitEvent event) {
this.disconnected.add(event.getPlayer().getUniqueId());
}
@EventHandler
public void onCooldownChange(PlayerCooldownChangeEvent event)
{
public void onCooldownChange(PlayerCooldownChangeEvent event) {
Player player = event.getPlayer();
BendingPlayer bendingPlayer = _players.get(player.getUniqueId());
BendingPlayer bendingPlayer = this.players.get(player.getUniqueId());
String ability = bendingPlayer.getBoundAbilityName();
if (ability != null && ability.equals(event.getAbility()))
{
if (ability != null && ability.equals(event.getAbility())) {
GeneralMethods.displayMovePreview(player);
}
}
public void removeBending(Player player)
{
BendingPlayer bendingPlayer = _players.get(player.getUniqueId());
public void removeBending(Player player) {
BendingPlayer bendingPlayer = this.players.get(player.getUniqueId());
bendingPlayer.setBendingRemoved(true);
updateBendingRemoved(bendingPlayer);
}
public void returnBending(Player player)
{
BendingPlayer bendingPlayer = _players.get(player.getUniqueId());
public void returnBending(Player player) {
BendingPlayer bendingPlayer = this.players.get(player.getUniqueId());
bendingPlayer.setBendingRemoved(false);
updateBendingRemoved(bendingPlayer);
}
private void updateBendingRemoved(BendingPlayer bendingPlayer)
{
runAsync(() ->
{
try
{
private void updateBendingRemoved(BendingPlayer bendingPlayer) {
runAsync(() -> {
try {
getRepository().updateBendingRemoved(bendingPlayer);
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
});
}
private void loadBendingPlayer(Player player)
{
try
{
private void loadBendingPlayer(Player player) {
try {
BendingPlayer bendingPlayer = getRepository().selectPlayer(player);
runSync(() ->
{
_players.put(player.getUniqueId(), bendingPlayer);
runSync(() -> {
this.players.put(player.getUniqueId(), bendingPlayer);
BendingPlayerLoadedEvent bendingPlayerLoadedEvent = new BendingPlayerLoadedEvent(player, bendingPlayer);
getPlugin().getServer().getPluginManager().callEvent(bendingPlayerLoadedEvent);
});
}
catch (SQLException e)
{
} catch (SQLException e) {
e.printStackTrace();
}
}
public BendingPlayer getBendingPlayer(Player player)
{
public BendingPlayer getBendingPlayer(Player player) {
return getBendingPlayer(player.getUniqueId());
}
public BendingPlayer getBendingPlayer(UUID uuid)
{
return _players.get(uuid);
public BendingPlayer getBendingPlayer(UUID uuid) {
return this.players.get(uuid);
}
}

View file

@ -5,15 +5,11 @@ import com.projectkorra.projectkorra.database.DatabaseRepository;
import org.bukkit.entity.Player;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import java.util.UUID;
public class BendingPlayerRepository extends DatabaseRepository
{
public class BendingPlayerRepository extends DatabaseRepository {
private static final DatabaseQuery CREATE_TABLE_BENDING_PLAYERS = DatabaseQuery.newBuilder()
.mysql("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTO_INCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL, bending_removed BOOLEAN, INDEX uuid_index (uuid));")
.sqlite("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTOINCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL, bending_removed BOOLEAN); CREATE INDEX uuid_index ON pk_bending_players (uuid);")
@ -35,31 +31,25 @@ public class BendingPlayerRepository extends DatabaseRepository
.query("UPDATE pk_bending_players SET bending_removed = ? WHERE player_id = ?;")
.build();
protected void createTables() throws SQLException
{
protected void createTables() throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_BENDING_PLAYERS.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_BENDING_PLAYERS.getQuery())) {
statement.executeUpdate();
}
}
protected BendingPlayer selectPlayer(Player player) throws SQLException
{
protected BendingPlayer selectPlayer(Player player) throws SQLException {
UUID uuid = player.getUniqueId();
byte[] binaryUUID = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array();
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(SELECT_BENDING_PLAYER.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(SELECT_BENDING_PLAYER.getQuery())) {
statement.setBytes(1, binaryUUID);
try (ResultSet rs = statement.executeQuery())
{
if (!rs.next())
{
try (ResultSet rs = statement.executeQuery()) {
if (!rs.next()) {
return insertPlayer(player.getUniqueId(), player.getName());
}
@ -68,8 +58,7 @@ public class BendingPlayerRepository extends DatabaseRepository
long firstLogin = rs.getLong("first_login");
boolean bendingRemoved = rs.getBoolean("bending_removed");
if (!player.getName().equals(playerName))
{
if (!player.getName().equals(playerName)) {
updatePlayerName(playerId, player.getName());
}
@ -82,23 +71,20 @@ public class BendingPlayerRepository extends DatabaseRepository
}
}
private BendingPlayer insertPlayer(UUID uuid, String playerName) throws SQLException
{
private BendingPlayer insertPlayer(UUID uuid, String playerName) throws SQLException {
byte[] binaryUUID = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array();
Connection connection = getDatabase().getConnection();
long firstLogin = System.currentTimeMillis();
try (PreparedStatement statement = connection.prepareStatement(INSERT_BENDING_PLAYER.getQuery(), Statement.RETURN_GENERATED_KEYS))
{
try (PreparedStatement statement = connection.prepareStatement(INSERT_BENDING_PLAYER.getQuery(), Statement.RETURN_GENERATED_KEYS)) {
statement.setBytes(1, binaryUUID);
statement.setString(2, playerName);
statement.setLong(3, firstLogin);
statement.executeUpdate();
try (ResultSet rs = statement.getGeneratedKeys())
{
try (ResultSet rs = statement.getGeneratedKeys()) {
rs.next();
int playerId = rs.getInt(1);
@ -108,12 +94,10 @@ public class BendingPlayerRepository extends DatabaseRepository
}
}
protected void updatePlayerName(int playerId, String playerName) throws SQLException
{
protected void updatePlayerName(int playerId, String playerName) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(UPDATE_PLAYER_NAME.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(UPDATE_PLAYER_NAME.getQuery())) {
statement.setInt(1, playerId);
statement.setString(2, playerName);
@ -121,12 +105,10 @@ public class BendingPlayerRepository extends DatabaseRepository
}
}
protected void updateBendingRemoved(BendingPlayer bendingPlayer) throws SQLException
{
protected void updateBendingRemoved(BendingPlayer bendingPlayer) throws SQLException {
Connection connection = getDatabase().getConnection();
try (PreparedStatement statement = connection.prepareStatement(UPDATE_BENDING_REMOVED.getQuery()))
{
try (PreparedStatement statement = connection.prepareStatement(UPDATE_BENDING_REMOVED.getQuery())) {
statement.setInt(1, bendingPlayer.getId());
statement.setBoolean(2, bendingPlayer.isBendingRemoved());