From f7be00486ae4da294f053f28bafdfbd2f512fb4e Mon Sep 17 00:00:00 2001 From: Heliosares Date: Sat, 14 Jan 2023 13:33:08 -0500 Subject: [PATCH] Code optimization --- .../auxprotect/bungee/AuxProtectBungee.java | 18 ++-- .../auxprotect/database/SQLManager.java | 92 +++++++------------ .../auxprotect/spigot/AuxProtectSpigot.java | 29 +++--- 3 files changed, 51 insertions(+), 88 deletions(-) diff --git a/src/dev/heliosares/auxprotect/bungee/AuxProtectBungee.java b/src/dev/heliosares/auxprotect/bungee/AuxProtectBungee.java index a4fd632..52a0260 100644 --- a/src/dev/heliosares/auxprotect/bungee/AuxProtectBungee.java +++ b/src/dev/heliosares/auxprotect/bungee/AuxProtectBungee.java @@ -9,7 +9,6 @@ import dev.heliosares.auxprotect.database.DbEntry; import dev.heliosares.auxprotect.database.SQLManager; import dev.heliosares.auxprotect.utils.StackUtil; import net.md_5.bungee.api.CommandSender; -import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; @@ -36,15 +35,12 @@ public class AuxProtectBungee extends Plugin implements IAuxProtect { Set stackHashHistory = new HashSet<>(); private boolean isShuttingDown; private String stackLog = ""; + private boolean enabled; public AuxProtectBungee() { instance = this; } - public static void tell(CommandSender to, String message) { - to.sendMessage(TextComponent.fromLegacyText(message)); - } - public static IAuxProtect getInstance() { return instance; } @@ -54,7 +50,7 @@ public class AuxProtectBungee extends Plugin implements IAuxProtect { return "#null"; } if (o instanceof UUID) { - return "$" + ((UUID) o).toString(); + return "$" + o; } if (o instanceof ProxiedPlayer) { return "$" + ((ProxiedPlayer) o).getUniqueId().toString(); @@ -64,9 +60,10 @@ public class AuxProtectBungee extends Plugin implements IAuxProtect { @Override public void onEnable() { + enabled = true; try { config.load(this, new BungeeConfigAdapter(this.getDataFolder(), "config.yml", null, - (s) -> getResourceAsStream(s), false)); + this::getResourceAsStream, false)); } catch (IOException e1) { warning("Failed to load config"); print(e1); @@ -76,7 +73,7 @@ public class AuxProtectBungee extends Plugin implements IAuxProtect { Language.load(this, () -> new BungeeConfigAdapter(getDataFolder(), "lang/" + config.getConfig().getString("lang") + ".yml", null, - (s) -> getResourceAsStream(s), false)); + this::getResourceAsStream, false)); } catch (FileNotFoundException e1) { warning("Language file not found"); @@ -158,6 +155,7 @@ public class AuxProtectBungee extends Plugin implements IAuxProtect { @Override public void onDisable() { + enabled = false; isShuttingDown = true; getProxy().getPluginManager().unregisterListeners(this); getProxy().getPluginManager().unregisterCommands(this); @@ -293,12 +291,12 @@ public class AuxProtectBungee extends Plugin implements IAuxProtect { @Override public List listPlayers() { - return getProxy().getPlayers().stream().map((p) -> p.getName()).collect(Collectors.toList()); + return getProxy().getPlayers().stream().map(CommandSender::getName).collect(Collectors.toList()); } @Override public boolean isEnabled() { - return this.isEnabled(); + return enabled; } @Override diff --git a/src/dev/heliosares/auxprotect/database/SQLManager.java b/src/dev/heliosares/auxprotect/database/SQLManager.java index 9e31e48..ae022ea 100644 --- a/src/dev/heliosares/auxprotect/database/SQLManager.java +++ b/src/dev/heliosares/auxprotect/database/SQLManager.java @@ -350,20 +350,20 @@ public class SQLManager { int i = 0; int count = 0; final String hdr = "DELETE FROM " + Table.AUXPROTECT_UIDS + " WHERE uid IN "; - String stmt = ""; + StringBuilder stmt = new StringBuilder(); for (int uid : savedUids) { - if (!stmt.isEmpty()) { - stmt += ","; + if (stmt.length() > 0) { + stmt.append(","); } plugin.debug("Purging UID " + uid, 5); - stmt += uid; + stmt.append(uid); if (++i >= 1000) { count += executeWriteReturnRows(hdr + "(" + stmt + ")"); - stmt = ""; + stmt = new StringBuilder(); i = 0; } } - if (!stmt.isEmpty()) + if (stmt.length() > 0) count += executeWriteReturnRows(hdr + "(" + stmt + ")"); return count; } @@ -423,13 +423,7 @@ public class SQLManager { } /** - * {@link PreparedStatement#execute()} - * - * @param stmt - * @param args - * @return - * @throws SQLException - * @throws BusyException + * @see PreparedStatement#execute() */ public boolean executeWrite(String stmt, Object... args) throws SQLException, BusyException { plugin.debug(stmt, 5); @@ -442,13 +436,7 @@ public class SQLManager { } /** - * {@link PreparedStatement#execute()} - * - * @param stmt - * @param args - * @return - * @throws SQLException - * @throws BusyException + * @see PreparedStatement#execute() */ public boolean executeWrite(Connection connection, String stmt, Object... args) throws SQLException { plugin.debug(stmt, 5); @@ -459,13 +447,7 @@ public class SQLManager { } /** - * {@link PreparedStatement#executeUpdate()} - * - * @param stmt - * @param args - * @return - * @throws SQLException - * @throws BusyException + * @see PreparedStatement#executeUpdate() */ public int executeWriteReturnRows(String stmt, Object... args) throws SQLException, BusyException { plugin.debug(stmt, 5); @@ -549,10 +531,9 @@ public class SQLManager { * done with this Connection * * @return returns a READ-ONLY connection to the database - * @throws SQLException * @throws BusyException if the database is busy for longer than 3 seconds */ - public Connection getConnection(boolean wait) throws SQLException, BusyException { + public Connection getConnection(boolean wait) throws SQLException { return conn.getConnection(wait); } @@ -588,7 +569,7 @@ public class SQLManager { protected boolean put(Connection connection, Table table) throws SQLException, IOException { long start = System.nanoTime(); - int count = 0; + int count; List entries = new ArrayList<>(); DbEntry entry; @@ -599,29 +580,28 @@ public class SQLManager { if (count == 0) { return false; } - String stmt = "INSERT INTO " + table + " "; + StringBuilder stmt = new StringBuilder("INSERT INTO " + table + " "); int numColumns = table.getNumColumns(plugin.getPlatform()); String inc = Table.getValuesTemplate(numColumns); final boolean hasLocation = plugin.getPlatform() == PlatformType.SPIGOT && table.hasLocation(); final boolean hasData = table.hasData(); final boolean hasAction = table.hasActionId(); final boolean hasLook = table.hasLook(); - stmt += table.getValuesHeader(plugin.getPlatform()); - stmt += " VALUES"; + stmt.append(table.getValuesHeader(plugin.getPlatform())); + stmt.append(" VALUES"); for (int i = 0; i < entries.size(); i++) { - stmt += "\n" + inc; + stmt.append("\n").append(inc); if (i + 1 == entries.size()) { - stmt += ";"; + stmt.append(";"); } else { - stmt += ","; + stmt.append(","); } } - try (PreparedStatement statement = connection.prepareStatement(stmt)) { + try (PreparedStatement statement = connection.prepareStatement(stmt.toString())) { int i = 1; for (DbEntry dbEntry : entries) { int prior = i; - // statement.setString(i++, table); statement.setLong(i++, dbEntry.getTime()); statement.setInt(i++, dbEntry.getUid()); int action = dbEntry.getState() ? dbEntry.getAction().idPos : dbEntry.getAction().id; @@ -702,24 +682,14 @@ public class SQLManager { bytes /= 1024; oom++; } - String out = ""; - switch (oom) { - case 0: - out = "B"; - break; - case 1: - out = "KB"; - break; - case 2: - out = "MB"; - break; - case 3: - out = "GB"; - break; - case 4: - out = "TB"; - break; - } + String out = switch (oom) { + case 0 -> "B"; + case 1 -> "KB"; + case 2 -> "MB"; + case 3 -> "GB"; + case 4 -> "TB"; + default -> ""; + }; return (Math.round(bytes * 100.0) / 100.0) + " " + out; } @@ -855,11 +825,11 @@ public class SQLManager { * negative actions. * @param ptext The text which will be displayed for this action in looks for * positive actions, or null for singular actions. + * @return The created EntryAction. * @throws AlreadyExistsException if the action you are attempting to create * already exists or the name is taken. * @throws SQLException if there is a problem connecting to the * database. - * @returns The created EntryAction. */ public EntryAction createAction(String key, String ntext, String ptext) throws AlreadyExistsException, SQLException { @@ -961,18 +931,18 @@ public class SQLManager { public void getMultipleBlobs(DbEntry... entries) throws SQLException, IOException { Table table = null; - String stmt = "SELECT time,ablob FROM %s WHERE time IN ("; + StringBuilder stmt = new StringBuilder("SELECT time,ablob FROM %s WHERE time IN ("); HashMap entryHash = new HashMap<>(); for (DbEntry entry : entries) { if (table == null) table = entry.getAction().getTable(); else if (table != entry.getAction().getTable()) throw new IllegalArgumentException("Incompatible actions"); - stmt += entry.getTime() + ","; + stmt.append(entry.getTime()).append(","); entryHash.put(entry.getTime(), entry); } if (table == null) return; - stmt = String.format(stmt.substring(0, stmt.length() - 1), table.toString()) + ")"; + stmt = new StringBuilder(String.format(stmt.substring(0, stmt.length() - 1), table.toString()) + ")"); Connection connection = getConnection(false); - try (PreparedStatement pstmt = connection.prepareStatement(stmt)) { + try (PreparedStatement pstmt = connection.prepareStatement(stmt.toString())) { try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { entryHash.get(rs.getLong("time")).setBlob(getBlob(rs, "ablob")); diff --git a/src/dev/heliosares/auxprotect/spigot/AuxProtectSpigot.java b/src/dev/heliosares/auxprotect/spigot/AuxProtectSpigot.java index 141331a..bc6c882 100644 --- a/src/dev/heliosares/auxprotect/spigot/AuxProtectSpigot.java +++ b/src/dev/heliosares/auxprotect/spigot/AuxProtectSpigot.java @@ -70,10 +70,10 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { return "#null"; } if (o instanceof UUID) { - return "$" + ((UUID) o).toString(); + return "$" + o; } if (o instanceof Player) { - return "$" + ((Player) o).getUniqueId().toString(); + return "$" + ((Player) o).getUniqueId(); } if (o instanceof Entity) { return "#" + ((Entity) o).getType().name().toLowerCase(); @@ -85,7 +85,7 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { return "#" + ((Block) o).getType().toString().toLowerCase(); } if (o instanceof Material) { - return ((Material) o).toString().toLowerCase(); + return o.toString().toLowerCase(); } return "#null"; } @@ -111,7 +111,7 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { try { config.load(this, new SpigotConfigAdapter(this.getRootDirectory(), "config.yml", this.getConfig(), - s -> this.getResource(s), false)); + this::getResource, false)); } catch (IOException e1) { warning("Failed to load config"); print(e1); @@ -119,7 +119,7 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { try { Language.load(this, () -> new SpigotConfigAdapter(this.getRootDirectory(), - "lang/" + config.getConfig().getString("lang") + ".yml", null, s -> this.getResource(s), false)); + "lang/" + config.getConfig().getString("lang") + ".yml", null, this::getResource, false)); } catch (FileNotFoundException e1) { warning("Language file not found"); } catch (IOException e1) { @@ -134,7 +134,7 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { debug("Parsing: " + Bukkit.getBukkitVersion()); try { - SERVER_VERSION = Integer.parseInt(Bukkit.getBukkitVersion().split("[\\.-]")[1]); + SERVER_VERSION = Integer.parseInt(Bukkit.getBukkitVersion().split("[.-]")[1]); } catch (Exception e) { warning("Failed to parse version string: \"" + Bukkit.getBukkitVersion() + "\". Defaulting to 1.16"); SERVER_VERSION = 16; @@ -171,11 +171,6 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { } sqlManager = new SQLManager(this, uri, getAPConfig().getTablePrefix(), sqliteFile); - if (sqlManager == null) { - this.getLogger().severe("Failed to connect to database. Disabling"); - this.setEnabled(false); - return; - } veinManager = new VeinManager(); new BukkitRunnable() { @@ -300,9 +295,9 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { EntryAction.TOWNYNAME.setEnabled(false); } - this.getCommand("claiminv").setExecutor(claiminvcommand = new ClaimInvCommand(this)); - this.getCommand("auxprotect").setExecutor((apcommand = new APSCommand(this))); - this.getCommand("auxprotect").setTabCompleter(apcommand); + Objects.requireNonNull(this.getCommand("claiminv")).setExecutor(claiminvcommand = new ClaimInvCommand(this)); + Objects.requireNonNull(this.getCommand("auxprotect")).setExecutor((apcommand = new APSCommand(this))); + Objects.requireNonNull(this.getCommand("auxprotect")).setTabCompleter(apcommand); new BukkitRunnable() { @@ -325,8 +320,8 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { warning(output); if (config.isOverrideCommands()) { warning("Attempting to re-register tab completer."); - getCommand("auxprotect").setTabCompleter(apcommand); - getCommand(getCommandAlias()).setTabCompleter(apcommand); + Objects.requireNonNull(getCommand("auxprotect")).setTabCompleter(apcommand); + Objects.requireNonNull(getCommand(getCommandAlias())).setTabCompleter(apcommand); } else { warning("If this is causing issues, try enabling 'OverrideCommands' in the config."); } @@ -769,7 +764,7 @@ public class AuxProtectSpigot extends JavaPlugin implements IAuxProtect { @Override public List listPlayers() { - return getServer().getOnlinePlayers().stream().map((p) -> p.getName()).collect(Collectors.toList()); + return getServer().getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); } @Override