Database calls now async

All database calls (excluding the ones on plugin onEnable) are now run
asynchronously. Fix a small bug with the GUI and opening a previously
stored inventory.
This commit is contained in:
Esophose 2018-03-03 14:49:31 -07:00
parent 900d6785be
commit 95a400a42c
3 changed files with 346 additions and 278 deletions

View file

@ -332,10 +332,8 @@ public class PlayerParticlesGui extends BukkitRunnable implements Listener {
if (playerGuiInventories.containsKey(p.getUniqueId())) {
GuiInventory guiInventory = playerGuiInventories.get(p.getUniqueId());
guiInventory.setGuiState(state);
if (player.getOpenInventory().getTopInventory() != guiInventory.getInventory()) {
Inventory ppInventory = Bukkit.createInventory(null, INVENTORY_SIZE, "PlayerParticles");
player.openInventory(ppInventory);
guiInventory.setInventory(ppInventory);
if (!player.getOpenInventory().getTopInventory().equals(guiInventory.getInventory())) {
player.openInventory(guiInventory.getInventory());
}
} else {
Inventory ppInventory = Bukkit.createInventory(null, INVENTORY_SIZE, "PlayerParticles");

View file

@ -24,6 +24,7 @@ import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.scheduler.BukkitRunnable;
import com.esophose.playerparticles.PPlayer;
import com.esophose.playerparticles.PlayerParticles;
@ -46,7 +47,7 @@ public class ConfigManager {
/**
* The file the data is located in for the instance
*/
private File file;
private File playerDataYamlFile;
/**
* The configuration used to edit the .yaml file
*/
@ -81,17 +82,17 @@ public class ConfigManager {
if (!PlayerParticles.useMySQL) { // Don't bother creating the playerData.yml file if we aren't going to use it
if (!PlayerParticles.getPlugin().getDataFolder().exists()) PlayerParticles.getPlugin().getDataFolder().mkdir();
file = new File(PlayerParticles.getPlugin().getDataFolder(), fileName + ".yml");
playerDataYamlFile = new File(PlayerParticles.getPlugin().getDataFolder(), fileName + ".yml");
if (!file.exists()) {
if (!playerDataYamlFile.exists()) {
try {
file.createNewFile();
playerDataYamlFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
playerDataYaml = YamlConfiguration.loadConfiguration(file);
playerDataYaml = YamlConfiguration.loadConfiguration(playerDataYamlFile);
}
}
@ -100,7 +101,7 @@ public class ConfigManager {
*/
private void save() {
try {
playerDataYaml.save(file);
playerDataYaml.save(playerDataYamlFile);
} catch (IOException e) {
e.printStackTrace();
}
@ -180,6 +181,7 @@ public class ConfigManager {
callback.execute(pplayer);
}
} else {
async(() -> {
String id = playerUUID.toString(); // @formatter:off
PlayerParticles.mySQL.connect((connection) -> {
String query = "SELECT * FROM pp_users u " +
@ -200,18 +202,18 @@ public class ConfigManager {
OrdinaryColor particleColorData = new OrdinaryColor(res.getInt("c.r"), res.getInt("c.g"), res.getInt("c.b"));
NoteColor particleNoteColorData = new NoteColor(res.getByte("n.note"));
callback.execute(new PPlayer(playerUUID, particleEffect, particleStyle, particleItemData, particleBlockData, particleColorData, particleNoteColorData));
sync(() -> callback.execute(new PPlayer(playerUUID, particleEffect, particleStyle, particleItemData, particleBlockData, particleColorData, particleNoteColorData)));
return;
}
if (createIfNotFound) {
// Didn't find an existing PPlayer, create and return a new one
if (createIfNotFound) { // Didn't find an existing PPlayer, create and return a new one
PPlayer pplayer = PPlayer.getNewPPlayer(playerUUID);
saveNewPPlayer(pplayer);
callback.execute(pplayer);
sync(() -> callback.execute(pplayer));
}
}
});
});
}
}
@ -254,6 +256,7 @@ public class ConfigManager {
save();
} else {
async(() -> {
PlayerParticles.mySQL.connect((connection) -> {
try (Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM pp_users WHERE player_uuid = '" + pplayer.getUniqueId() + "'")) {
@ -290,6 +293,7 @@ public class ConfigManager {
}
}
});
});
}
ParticleManager.updateIfContains(pplayer); // Update the player in case this is a /pp reset
@ -338,11 +342,13 @@ public class ConfigManager {
section.set("name", particleEffect.getName());
save();
} else {
async(() -> {
try {
PlayerParticles.mySQL.updateSQL("UPDATE pp_users SET effect = '" + particleEffect.getName() + "' WHERE player_uuid = '" + playerUUID + "';");
} catch (SQLException e) {
e.printStackTrace();
}
});
}
getPPlayer(playerUUID, (pplayer) -> {
@ -362,11 +368,13 @@ public class ConfigManager {
section.set("name", particleStyle.getName());
save();
} else {
async(() -> {
try {
PlayerParticles.mySQL.updateSQL("UPDATE pp_users SET style = '" + particleStyle.getName() + "' WHERE player_uuid = '" + playerUUID + "';");
} catch (SQLException e) {
e.printStackTrace();
}
});
}
getPPlayer(playerUUID, (pplayer) -> {
@ -387,11 +395,13 @@ public class ConfigManager {
section.set("data", particleItemData.getData());
save();
} else {
async(() -> {
try {
PlayerParticles.mySQL.updateSQL("UPDATE pp_data_item SET material = '" + particleItemData.getMaterial().name() + "', data = '" + particleItemData.getData() + "' WHERE uuid = '" + playerUUID + "';");
} catch (SQLException e) {
e.printStackTrace();
}
});
}
getPPlayer(playerUUID, (pplayer) -> {
@ -412,11 +422,13 @@ public class ConfigManager {
section.set("data", particleBlockData.getData());
save();
} else {
async(() -> {
try {
PlayerParticles.mySQL.updateSQL("UPDATE pp_data_block SET material = '" + particleBlockData.getMaterial().name() + "', data = '" + particleBlockData.getData() + "' WHERE uuid = '" + playerUUID + "';");
} catch (SQLException e) {
e.printStackTrace();
}
});
}
getPPlayer(playerUUID, (pplayer) -> {
@ -438,11 +450,13 @@ public class ConfigManager {
section.set("b", particleColorData.getBlue());
save();
} else {
async(() -> {
try {
PlayerParticles.mySQL.updateSQL("UPDATE pp_data_color SET r = " + particleColorData.getRed() + ", g = " + particleColorData.getGreen() + ", b = " + particleColorData.getBlue() + " WHERE uuid = '" + playerUUID + "';");
} catch (SQLException e) {
e.printStackTrace();
}
});
}
getPPlayer(playerUUID, (pplayer) -> {
@ -462,11 +476,13 @@ public class ConfigManager {
section.set("note", (byte) (particleNoteColorData.getValueX() * 24));
save();
} else {
async(() -> {
try {
PlayerParticles.mySQL.updateSQL("UPDATE pp_data_note SET note = " + (byte) (particleNoteColorData.getValueX() * 24) + " WHERE uuid = '" + playerUUID + "';");
} catch (SQLException e) {
e.printStackTrace();
}
});
}
getPPlayer(playerUUID, (pplayer) -> {
@ -522,6 +538,7 @@ public class ConfigManager {
save();
ParticleManager.addFixedEffect(fixedEffect);
} else {
async(() -> {
PlayerParticles.mySQL.connect((connection) -> {
try (Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM pp_fixed WHERE player_uuid = '" + fixedEffect.getOwnerUniqueId() + "' AND id = " + fixedEffect.getId())) {
@ -566,9 +583,10 @@ public class ConfigManager {
");"
);
ParticleManager.addFixedEffect(fixedEffect);
sync(() -> ParticleManager.addFixedEffect(fixedEffect));
}
});
});
}
}
@ -577,7 +595,7 @@ public class ConfigManager {
*
* @param playerUUID The player who owns the effect
* @param id The id of the effect to remove
* @return If the effect was removed
* @param callback The callback to execute with if the fixed effect was removed or not
*/
public void removeFixedEffect(UUID playerUUID, int id, ConfigurationCallback<Boolean> callback) {
if (!PlayerParticles.useMySQL) {
@ -592,6 +610,7 @@ public class ConfigManager {
ParticleManager.removeFixedEffectForPlayer(playerUUID, id);
callback.execute(true);
} else {
async(() -> {
PlayerParticles.mySQL.connect((connection) -> {
try (Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT uuid FROM pp_fixed WHERE player_uuid = '" + playerUUID.toString() + "' AND id = " + id)) {
@ -608,10 +627,14 @@ public class ConfigManager {
"DELETE FROM pp_data_color WHERE uuid = '" + uuid + "';" +
"DELETE FROM pp_data_note WHERE uuid = '" + uuid + "';"
);
sync(() -> {
ParticleManager.removeFixedEffectForPlayer(playerUUID, id);
callback.execute(true);
});
}
});
});
}
}
@ -625,6 +648,7 @@ public class ConfigManager {
playerDataYaml.set(playerUUID.toString() + ".fixedEffect", null);
save();
} else {
async(() -> {
try { // @formatter:off
PlayerParticles.mySQL.updateSQL("DELETE FROM pp_data_item WHERE uuid IN (SELECT uuid FROM pp_fixed WHERE player_uuid = '" + playerUUID.toString() + "');" +
"DELETE FROM pp_data_block WHERE uuid IN (SELECT uuid FROM pp_fixed WHERE player_uuid = '" + playerUUID.toString() + "');" +
@ -635,6 +659,7 @@ public class ConfigManager {
} catch (SQLException e) {
e.printStackTrace();
}
});
}
ParticleManager.removeAllFixedEffectsForPlayer(playerUUID);
@ -643,7 +668,7 @@ public class ConfigManager {
/**
* Gets a list of all saved fixed particle effects
*
* @return A list of all saved fixed particle effects
* @param callback The callback to execute with a list of all saved fixed particle effects
*/
public void getAllFixedEffects(ConfigurationCallback<List<FixedParticleEffect>> callback) {
if (!PlayerParticles.useMySQL) {
@ -682,6 +707,7 @@ public class ConfigManager {
callback.execute(fixedEffects);
} else { // @formatter:off
async(() -> {
PlayerParticles.mySQL.connect((connection) -> {
String query = "SELECT * FROM pp_fixed f " +
"JOIN pp_data_item i ON f.uuid = i.uuid " +
@ -710,9 +736,10 @@ public class ConfigManager {
fixedEffects.add(new FixedParticleEffect(pplayerUUID, id, worldName, xPos, yPos, zPos, particleEffect, particleStyle, particleItemData, particleBlockData, particleColorData, particleNoteColorData));
}
callback.execute(fixedEffects);
sync(() -> callback.execute(fixedEffects));
}
});
});
}
}
@ -721,7 +748,7 @@ public class ConfigManager {
*
* @param pplayerUUID The player who owns the effect
* @param id The id for the effect to get
* @return The effect if one exists
* @param callback The callback to execute with the effect, if one exists
*/
public void getFixedEffectForPlayerById(UUID pplayerUUID, int id, ConfigurationCallback<FixedParticleEffect> callback) {
if (!PlayerParticles.useMySQL) {
@ -748,6 +775,7 @@ public class ConfigManager {
callback.execute(new FixedParticleEffect(pplayerUUID, id, worldName, xPos, yPos, zPos, particleEffect, particleStyle, particleItemData, particleBlockData, particleColorData, particleNoteColorData));
}
} else {
async(() -> {
PlayerParticles.mySQL.connect((connection) -> { // @formatter:off
String query = "SELECT * FROM pp_fixed f " +
"JOIN pp_data_item i ON f.uuid = i.uuid " +
@ -770,10 +798,11 @@ public class ConfigManager {
OrdinaryColor particleColorData = new OrdinaryColor(res.getInt("c.r"), res.getInt("c.g"), res.getInt("c.b"));
NoteColor particleNoteColorData = new NoteColor(res.getByte("n.note"));
callback.execute(new FixedParticleEffect(pplayerUUID, id, worldName, xPos, yPos, zPos, particleEffect, particleStyle, particleItemData, particleBlockData, particleColorData, particleNoteColorData));
sync(() -> callback.execute(new FixedParticleEffect(pplayerUUID, id, worldName, xPos, yPos, zPos, particleEffect, particleStyle, particleItemData, particleBlockData, particleColorData, particleNoteColorData)));
}
}
});
});
}
}
@ -781,7 +810,7 @@ public class ConfigManager {
* Gets a list of all fixed effect ids for a player
*
* @param pplayerUUID The player
* @return A list of all fixed effect ids for the given player
* @param callback The callback to execute with a list of all fixed effect ids for the given player
*/
public void getFixedEffectIdsForPlayer(UUID pplayerUUID, ConfigurationCallback<List<Integer>> callback) {
if (!PlayerParticles.useMySQL) {
@ -796,6 +825,7 @@ public class ConfigManager {
callback.execute(ids);
} else {
async(() -> {
PlayerParticles.mySQL.connect((connection) -> {
try (Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT id FROM pp_fixed WHERE player_uuid = '" + pplayerUUID.toString() + "'")) {
@ -806,9 +836,10 @@ public class ConfigManager {
ids.add(res.getInt(1));
}
callback.execute(ids);
sync(() -> callback.execute(ids));
}
});
});
}
}
@ -816,7 +847,7 @@ public class ConfigManager {
* Checks if the given player has reached the max number of fixed effects
*
* @param pplayerUUID The player to check
* @return If the player can create any more fixed effects
* @param callback The callback to execute with if the player can create any more fixed effects
*/
public void hasPlayerReachedMaxFixedEffects(UUID pplayerUUID, ConfigurationCallback<Boolean> callback) {
if (maxFixedEffects == -1) { // Initialize on the fly
@ -833,15 +864,21 @@ public class ConfigManager {
callback.execute(playerDataYaml.getConfigurationSection(pplayerUUID.toString() + ".fixedEffect").getKeys(false).size() >= maxFixedEffects);
} else callback.execute(false);
} else {
async(() -> {
PlayerParticles.mySQL.connect((connection) -> {
try (Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT COUNT(1) FROM pp_fixed WHERE player_uuid = '" + pplayerUUID.toString() + "'")) {
if (res.next()) {
callback.execute(res.getInt(1) >= maxFixedEffects);
} else callback.execute(false);
boolean hasReachedMax;
if (res.next())
hasReachedMax = res.getInt(1) >= maxFixedEffects;
else
hasReachedMax = false;
sync(() -> callback.execute(hasReachedMax));
}
});
});
}
}
@ -849,7 +886,7 @@ public class ConfigManager {
* Gets the next Id for a player's fixed effects
*
* @param pplayerUUID The player to get the Id for
* @return The smallest available Id the player can use
* @param callback The callback to execute with the smallest available Id the player can use
*/
public void getNextFixedEffectId(UUID pplayerUUID, ConfigurationCallback<Integer> callback) {
if (!PlayerParticles.useMySQL) {
@ -869,6 +906,7 @@ public class ConfigManager {
callback.execute(ParticleUtils.getSmallestPositiveInt(ids));
} else {
async(() -> {
PlayerParticles.mySQL.connect((connection) -> {
try (Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT id FROM pp_fixed WHERE player_uuid = '" + pplayerUUID.toString() + "'")) {
@ -879,7 +917,7 @@ public class ConfigManager {
idsSet.add(res.getInt(1) + "");
if (idsSet.isEmpty()) {
callback.execute(1);
sync(() -> callback.execute(1));
return;
}
@ -888,9 +926,10 @@ public class ConfigManager {
for (String key : idsSet)
ids[i++] = Integer.parseInt(key);
callback.execute(ParticleUtils.getSmallestPositiveInt(ids));
sync(() -> callback.execute(ParticleUtils.getSmallestPositiveInt(ids)));
}
});
});
}
}
@ -928,6 +967,41 @@ public class ConfigManager {
return disabledWorlds;
}
/**
* Asynchronizes the callback with it's own thread
*
* @param asyncCallback The callback to run on a separate thread
*/
private void async(SyncInterface asyncCallback) {
new BukkitRunnable() {
public void run() {
System.out.println("Async with thread: " + Thread.currentThread().getName());
asyncCallback.execute();
}
}.runTaskAsynchronously(PlayerParticles.getPlugin());
}
/**
* Synchronizes the callback with the main thread
*
* @param syncCallback The callback to run on the main thread
*/
private void sync(SyncInterface syncCallback) {
new BukkitRunnable() {
public void run() {
System.out.println("Resynced with thread: " + Thread.currentThread().getName());
syncCallback.execute();
}
}.runTask(PlayerParticles.getPlugin());
}
/**
* Provides an easy way to run a section of code either synchronously or asynchronously using a callback
*/
private static interface SyncInterface {
public void execute();
}
/**
* Allows callbacks to be passed between configuration methods and executed for returning objects after database queries
*/

View file

@ -53,13 +53,9 @@ public class DatabaseManager {
}
/**
* Executes a callback with a Connection passed
* Automatically closes connection
* You need to close any resulting Statements or ResultSets on your own
* Executes a callback with a Connection passed and automatically closes it
*
* @param callback The callback to execute once the connection is retrieved
* @return
* @throws SQLException
*/
public void connect(ConnectionCallback callback) {
try (Connection connection = hikari.getConnection()) {
@ -73,8 +69,8 @@ public class DatabaseManager {
* Executes an update statement and cleans up all resources
*
* @param query The update statement to run
* @return
* @throws SQLException
* @return An int with the status of the first statement in the query
* @throws SQLException If an SQL problem occurs executing the statement
*/
public int updateSQL(String query) throws SQLException {
Connection connection = null;