From 5c0f77c7c57e00b504dc11e761931a61a9d90462 Mon Sep 17 00:00:00 2001 From: Paldiu Date: Fri, 25 Dec 2020 14:46:43 -0500 Subject: [PATCH 01/15] Removal of Lombok Lombok implementation removal. I have also gone through and replaced things with inline methods and variables, lambdas, and simplified loops down, removed unnecessary guard clauses, and overall cleaned up every single class. This took a long time, please do remember to follow proper naming conventions, don't include unnecessary guard clauses, follow exception rules and comment rules, and please PLEASE remember to use the DIAMOND OPERATOR rather than just inferring RAW TYPES!!! Thank you!! --- .gitignore | 1 + pom.xml | 6 - .../totalfreedommod/Announcer.java | 23 +- .../totalfreedommod/AntiNuke.java | 1 - .../totalfreedommod/AntiSpam.java | 12 +- .../totalfreedommod/AutoEject.java | 11 +- .../totalfreedommod/AutoKick.java | 3 +- .../totalfreedommod/ChatManager.java | 11 +- .../totalfreedommod/EntityWiper.java | 3 +- .../totalfreedommod/FreedomService.java | 6 +- .../FreedomServiceHandler.java | 9 +- .../totalfreedommod/GameRuleHandler.java | 1 + .../totalfreedommod/LogViewer.java | 9 +- .../totalfreedommod/LoginProcess.java | 16 +- .../totalfreedommod/Monitors.java | 17 +- .../totalfreedommod/MovementValidator.java | 6 +- .../totalfreedommod/Pterodactyl.java | 42 +- .../totalfreedommod/SavedFlags.java | 3 +- .../totalfreedommod/ServerInterface.java | 20 +- .../totalfreedommod/TotalFreedomMod.java | 57 +- .../totalfreedommod/admin/ActivityLog.java | 29 +- .../admin/ActivityLogEntry.java | 65 +- .../totalfreedommod/admin/Admin.java | 137 +++- .../totalfreedommod/admin/AdminList.java | 48 +- .../totalfreedommod/banning/Ban.java | 116 ++- .../totalfreedommod/banning/BanManager.java | 11 +- .../banning/IndefiniteBan.java | 49 +- .../banning/IndefiniteBanList.java | 37 +- .../blocking/BlockBlocker.java | 4 +- .../blocking/EventBlocker.java | 45 +- .../totalfreedommod/blocking/MobBlocker.java | 11 +- .../totalfreedommod/blocking/SignBlocker.java | 1 + .../blocking/command/CommandBlocker.java | 40 +- .../command/CommandBlockerAction.java | 10 +- .../blocking/command/CommandBlockerEntry.java | 36 +- .../blocking/command/CommandBlockerRank.java | 25 +- .../bridge/BukkitTelnetBridge.java | 3 +- .../bridge/CoreProtectBridge.java | 81 +- .../bridge/EssentialsBridge.java | 16 +- .../bridge/LibsDisguisesBridge.java | 10 +- .../bridge/WorldEditBridge.java | 6 +- .../totalfreedommod/caging/CageData.java | 298 ++++--- .../totalfreedommod/caging/Cager.java | 5 +- .../command/Command_adminworld.java | 44 +- .../command/Command_attributelist.java | 8 +- .../totalfreedommod/command/Command_ban.java | 9 +- .../command/Command_banip.java | 2 +- .../totalfreedommod/command/Command_cake.java | 1 + .../command/Command_cartsit.java | 3 +- .../command/Command_cmdspy.java | 2 +- .../command/Command_commandlist.java | 11 +- .../command/Command_cookie.java | 18 +- .../command/Command_deafen.java | 24 +- .../command/Command_debugstick.java | 1 + .../command/Command_dispfill.java | 22 +- .../totalfreedommod/command/Command_doom.java | 9 +- .../command/Command_eject.java | 2 +- .../command/Command_enchant.java | 48 +- .../command/Command_entitywipe.java | 46 +- .../command/Command_expel.java | 6 +- .../command/Command_health.java | 2 +- .../command/Command_hubworld.java | 14 +- .../command/Command_invis.java | 5 +- .../command/Command_invsee.java | 5 - .../command/Command_landmine.java | 2 +- .../command/Command_linkdiscord.java | 2 +- .../totalfreedommod/command/Command_list.java | 4 +- .../command/Command_lockup.java | 2 +- .../command/Command_makeopregion.java | 2 +- .../command/Command_manageshop.java | 6 +- .../command/Command_manuallyverify.java | 2 +- .../command/Command_masterbuilderworld.java | 14 +- .../command/Command_mbconfig.java | 4 +- .../command/Command_moblimiter.java | 2 +- .../command/Command_mobpurge.java | 20 +- .../command/Command_modifyitem.java | 25 +- .../totalfreedommod/command/Command_mp44.java | 3 +- .../command/Command_myadmin.java | 2 +- .../command/Command_nickclean.java | 4 +- .../command/Command_nickfilter.java | 76 +- .../command/Command_notes.java | 4 +- .../totalfreedommod/command/Command_ops.java | 3 +- .../command/Command_panel.java | 23 +- .../command/Command_playerverification.java | 13 +- .../command/Command_playtime.java | 26 +- .../command/Command_plugincontrol.java | 2 +- .../command/Command_potion.java | 8 +- .../command/Command_potionspy.java | 15 +- .../command/Command_premium.java | 2 +- .../command/Command_releaseparrots.java | 1 + .../totalfreedommod/command/Command_ro.java | 85 +- .../totalfreedommod/command/Command_rock.java | 1 + .../command/Command_saconfig.java | 55 +- .../command/Command_setlever.java | 11 +- .../command/Command_setplayerlimit.java | 1 + .../command/Command_smite.java | 90 +-- .../command/Command_spawnmob.java | 2 - .../totalfreedommod/command/Command_tban.java | 12 +- .../command/Command_tempban.java | 24 +- .../command/Command_toggle.java | 5 +- .../command/Command_tossmob.java | 76 +- .../command/Command_unban.java | 3 +- .../command/Command_unbanip.java | 2 +- .../command/Command_vanish.java | 5 +- .../command/Command_verify.java | 5 +- .../command/Command_whitelist.java | 3 +- .../command/Command_whohas.java | 23 +- .../command/Command_wipeuserdata.java | 7 +- .../command/Command_wipewarps.java | 1 + .../command/FreedomCommand.java | 296 +++---- .../totalfreedommod/command/SourceType.java | 3 +- .../totalfreedommod/config/ConfigEntry.java | 41 +- .../totalfreedommod/config/MainConfig.java | 32 +- .../totalfreedommod/config/YamlConfig.java | 4 - .../totalfreedommod/discord/Discord.java | 729 +++++++++--------- .../discord/DiscordToAdminChatListener.java | 7 +- .../discord/DiscordToMinecraftListener.java | 8 +- .../discord/PrivateMessageListener.java | 7 +- .../totalfreedommod/freeze/FreezeData.java | 14 +- .../totalfreedommod/freeze/Freezer.java | 21 +- .../totalfreedommod/fun/ItemFun.java | 20 +- .../totalfreedommod/fun/Jumppads.java | 38 +- .../totalfreedommod/fun/Landminer.java | 8 +- .../totalfreedommod/fun/Trailer.java | 3 +- .../httpd/HTMLGenerationTools.java | 5 +- .../totalfreedommod/httpd/HTTPDaemon.java | 82 +- .../httpd/ModuleExecutable.java | 53 +- .../totalfreedommod/httpd/NanoHTTPD.java | 431 +++++------ .../httpd/module/HTTPDModule.java | 3 +- .../httpd/module/Module_activitylog.java | 9 +- .../httpd/module/Module_admins.java | 7 +- .../httpd/module/Module_bans.java | 7 +- .../httpd/module/Module_file.java | 88 +-- .../httpd/module/Module_help.java | 63 +- .../httpd/module/Module_indefbans.java | 7 +- .../httpd/module/Module_index.java | 7 +- .../httpd/module/Module_list.java | 4 +- .../httpd/module/Module_logfile.java | 84 +- .../httpd/module/Module_players.java | 4 +- .../httpd/module/Module_punishments.java | 4 +- .../httpd/module/Module_schematic.java | 86 +-- .../permissions/PermissionConfig.java | 8 +- .../permissions/PermissionEntry.java | 3 +- .../totalfreedommod/player/FPlayer.java | 328 +++++++- .../totalfreedommod/player/PlayerData.java | 214 +++-- .../totalfreedommod/player/PlayerList.java | 42 +- .../punishments/Punishment.java | 94 ++- .../punishments/PunishmentList.java | 12 +- .../totalfreedommod/rank/Rank.java | 92 ++- .../totalfreedommod/rank/RankManager.java | 9 +- .../totalfreedommod/rank/Title.java | 59 +- .../totalfreedommod/shop/Shop.java | 59 +- .../totalfreedommod/shop/ShopItem.java | 63 +- .../totalfreedommod/sql/SQLite.java | 10 +- .../totalfreedommod/util/FLog.java | 20 +- .../totalfreedommod/util/FSync.java | 6 + .../totalfreedommod/util/FUtil.java | 63 +- .../totalfreedommod/util/History.java | 13 +- .../totalfreedommod/util/Response.java | 19 +- .../totalfreedommod/util/UUIDFetcher.java | 2 +- .../totalfreedommod/world/AdminWorld.java | 9 +- .../world/CleanroomChunkGenerator.java | 11 +- .../totalfreedommod/world/CustomWorld.java | 8 +- .../totalfreedommod/world/Flatlands.java | 4 +- .../totalfreedommod/world/HubWorld.java | 7 +- .../world/MasterBuilderWorld.java | 7 +- .../totalfreedommod/world/WorldManager.java | 4 +- .../world/WorldRestrictions.java | 2 +- .../totalfreedommod/world/WorldTime.java | 24 +- .../totalfreedommod/world/WorldWeather.java | 18 +- 170 files changed, 3302 insertions(+), 2383 deletions(-) diff --git a/.gitignore b/.gitignore index 931fd6fb..c0ab2daf 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,4 @@ manifest.mf .Trashes ehthumbs.db Thumbs.db +.idea/inspectionProfiles/Project_Default.xml diff --git a/pom.xml b/pom.xml index ebfad76c..c6003dc2 100644 --- a/pom.xml +++ b/pom.xml @@ -122,12 +122,6 @@ - - org.projectlombok - lombok - 1.18.16 - provided - commons-io diff --git a/src/main/java/me/totalfreedom/totalfreedommod/Announcer.java b/src/main/java/me/totalfreedom/totalfreedommod/Announcer.java index 2fd04e50..c6a0e470 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/Announcer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/Announcer.java @@ -3,7 +3,6 @@ package me.totalfreedom.totalfreedommod; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; -import lombok.Getter; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.scheduler.BukkitRunnable; @@ -13,11 +12,8 @@ public class Announcer extends FreedomService { private final List announcements = Lists.newArrayList(); - @Getter private boolean enabled; - @Getter private long interval; - @Getter private String prefix; private BukkitTask announcer; @@ -80,4 +76,23 @@ public class Announcer extends FreedomService FUtil.bcastMsg(prefix + message); } + public boolean isEnabled() + { + return enabled; + } + + public long getInterval() + { + return interval; + } + + public String getPrefix() + { + return prefix; + } + + public BukkitTask getAnnouncer() + { + return announcer; + } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/AntiNuke.java b/src/main/java/me/totalfreedom/totalfreedommod/AntiNuke.java index 444368d0..ecefb7dd 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/AntiNuke.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/AntiNuke.java @@ -42,7 +42,6 @@ public class AntiNuke extends FreedomService fPlayer.resetBlockDestroyCount(); event.setCancelled(true); - return; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/AntiSpam.java b/src/main/java/me/totalfreedom/totalfreedommod/AntiSpam.java index f6eb2404..48065562 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/AntiSpam.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/AntiSpam.java @@ -20,9 +20,9 @@ public class AntiSpam extends FreedomService public static final int MSG_PER_CYCLE = 8; public static final int TICKS_PER_CYCLE = 2 * 10; - List markedForDeath = new ArrayList<>(); // public BukkitTask cycleTask = null; + List markedForDeath = new ArrayList<>(); @Override public void onStart() @@ -73,7 +73,7 @@ public class AntiSpam extends FreedomService // Check for spam if (playerdata.incrementAndGetMsgCount() > MSG_PER_CYCLE) - { + { if (!markedForDeath.contains(player)) { markedForDeath.add(player); @@ -84,14 +84,13 @@ public class AntiSpam extends FreedomService event.setCancelled(true); } - return; } else if (playerdata.incrementAndGetMsgCount() > MSG_PER_CYCLE / 2) { FUtil.playerMsg(player, "Please refrain from spamming chat.", ChatColor.GRAY); event.setCancelled(true); } - + } @EventHandler(priority = EventPriority.LOW) @@ -127,9 +126,6 @@ public class AntiSpam extends FreedomService @EventHandler(priority = EventPriority.NORMAL) public void onPlayerKick(PlayerKickEvent event) { - if (markedForDeath.contains(event.getPlayer())) - { - markedForDeath.remove(event.getPlayer()); - } + markedForDeath.remove(event.getPlayer()); } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/AutoEject.java b/src/main/java/me/totalfreedom/totalfreedommod/AutoEject.java index a3055f1f..63c9818a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/AutoEject.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/AutoEject.java @@ -43,11 +43,7 @@ public class AutoEject extends FreedomService ejects.put(ip, kicks); - if (kicks <= 1) - { - method = EjectMethod.STRIKE_ONE; - } - else if (kicks == 2) + if (kicks == 2) { method = EjectMethod.STRIKE_TWO; } @@ -101,10 +97,9 @@ public class AutoEject extends FreedomService } } - public static enum EjectMethod + public enum EjectMethod { - - STRIKE_ONE, STRIKE_TWO, STRIKE_THREE; + STRIKE_ONE, STRIKE_TWO, STRIKE_THREE } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/AutoKick.java b/src/main/java/me/totalfreedom/totalfreedommod/AutoKick.java index b7016dc3..e15a424e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/AutoKick.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/AutoKick.java @@ -46,9 +46,10 @@ public class AutoKick extends FreedomService private void autoKickCheck() { + // No type cast was provided, one has been supplied. final boolean doAwayKickCheck = plugin.esb.isEnabled() - && ((server.getOnlinePlayers().size() / server.getMaxPlayers()) > autoKickThreshold); + && (((float)server.getOnlinePlayers().size() / (float)server.getMaxPlayers()) > autoKickThreshold); if (!doAwayKickCheck) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/ChatManager.java b/src/main/java/me/totalfreedom/totalfreedommod/ChatManager.java index 8d6d642d..19054c8a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/ChatManager.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/ChatManager.java @@ -1,11 +1,11 @@ package me.totalfreedom.totalfreedommod; import com.google.common.base.Strings; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Displayable; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FSync; import me.totalfreedom.totalfreedommod.util.FUtil; @@ -96,8 +96,8 @@ public class ChatManager extends FreedomService } // Check for 4chan trigger - Boolean green = ChatColor.stripColor(message).toLowerCase().startsWith(">"); - Boolean orange = ChatColor.stripColor(message).toLowerCase().endsWith("<"); + boolean green = ChatColor.stripColor(message).toLowerCase().startsWith(">"); + boolean orange = ChatColor.stripColor(message).toLowerCase().endsWith("<"); if (ConfigEntry.FOURCHAN_ENABLED.getBoolean()) { if (green) @@ -123,7 +123,7 @@ public class ChatManager extends FreedomService } // Check for mentions - Boolean mentionEveryone = ChatColor.stripColor(message).toLowerCase().contains("@everyone") && plugin.al.isAdmin(player); + boolean mentionEveryone = ChatColor.stripColor(message).toLowerCase().contains("@everyone") && plugin.al.isAdmin(player); for (Player p : server.getOnlinePlayers()) { if (ChatColor.stripColor(message).toLowerCase().contains("@" + p.getName().toLowerCase()) || mentionEveryone) @@ -144,8 +144,7 @@ public class ChatManager extends FreedomService public ChatColor getColor(Displayable display) { - ChatColor color = display.getColor(); - return color; + return display.getColor(); } public String getColoredTag(Displayable display) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/EntityWiper.java b/src/main/java/me/totalfreedom/totalfreedommod/EntityWiper.java index 61c2400c..67a61cc2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/EntityWiper.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/EntityWiper.java @@ -14,8 +14,6 @@ import org.bukkit.scheduler.BukkitTask; public class EntityWiper extends FreedomService { - private BukkitTask wiper; - public List BLACKLIST = Arrays.asList( EntityType.ARMOR_STAND, EntityType.PAINTING, @@ -24,6 +22,7 @@ public class EntityWiper extends FreedomService EntityType.ITEM_FRAME, EntityType.MINECART ); + private BukkitTask wiper; @Override public void onStart() diff --git a/src/main/java/me/totalfreedom/totalfreedommod/FreedomService.java b/src/main/java/me/totalfreedom/totalfreedommod/FreedomService.java index e324847c..7b66bbe5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/FreedomService.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/FreedomService.java @@ -1,5 +1,6 @@ package me.totalfreedom.totalfreedommod; +import java.util.logging.Logger; import me.totalfreedom.totalfreedommod.util.FLog; import org.bukkit.Server; import org.bukkit.event.Listener; @@ -8,17 +9,18 @@ public abstract class FreedomService implements Listener { protected final TotalFreedomMod plugin; protected final Server server; - protected final FLog logger; + protected final Logger logger; public FreedomService() { plugin = TotalFreedomMod.getPlugin(); server = plugin.getServer(); - logger = new FLog(); + logger = FLog.getPluginLogger(); plugin.getServer().getPluginManager().registerEvents(this, plugin); plugin.fsh.add(this); } public abstract void onStart(); + public abstract void onStop(); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/FreedomServiceHandler.java b/src/main/java/me/totalfreedom/totalfreedommod/FreedomServiceHandler.java index bb13eebf..ffd397b2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/FreedomServiceHandler.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/FreedomServiceHandler.java @@ -2,12 +2,10 @@ package me.totalfreedom.totalfreedommod; import java.util.ArrayList; import java.util.List; -import lombok.Getter; public class FreedomServiceHandler { - @Getter - private List services; + private final List services; public FreedomServiceHandler() { @@ -53,4 +51,9 @@ public class FreedomServiceHandler } } } + + public List getServices() + { + return services; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/GameRuleHandler.java b/src/main/java/me/totalfreedom/totalfreedommod/GameRuleHandler.java index b8a72d2d..c528b7a9 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/GameRuleHandler.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/GameRuleHandler.java @@ -56,6 +56,7 @@ public class GameRuleHandler extends FreedomService } } + @SuppressWarnings("deprecation") public void commitGameRules() { List worlds = Bukkit.getWorlds(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/LogViewer.java b/src/main/java/me/totalfreedom/totalfreedommod/LogViewer.java index 802256bc..1c302f99 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/LogViewer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/LogViewer.java @@ -10,7 +10,6 @@ import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import me.totalfreedom.totalfreedommod.config.ConfigEntry; @@ -131,10 +130,10 @@ public class LogViewer extends FreedomService }.runTaskAsynchronously(plugin); } - public static enum LogsRegistrationMode + public enum LogsRegistrationMode { - ADD, DELETE, VERIFY; + ADD, DELETE, VERIFY } private static class URLBuilder @@ -157,10 +156,8 @@ public class LogViewer extends FreedomService public URL getURL() throws MalformedURLException { List pairs = new ArrayList<>(); - Iterator> it = queryStringMap.entrySet().iterator(); - while (it.hasNext()) + for (Map.Entry pair : queryStringMap.entrySet()) { - Map.Entry pair = it.next(); try { pairs.add(URLEncoder.encode(pair.getKey(), "UTF-8") + "=" + URLEncoder.encode(pair.getValue(), "UTF-8")); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/LoginProcess.java b/src/main/java/me/totalfreedom/totalfreedommod/LoginProcess.java index 5624d998..07e1ac54 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/LoginProcess.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/LoginProcess.java @@ -4,8 +4,6 @@ import io.papermc.lib.PaperLib; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; -import lombok.Getter; -import lombok.Setter; import me.rayzr522.jsonmessage.JSONMessage; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; @@ -29,12 +27,19 @@ public class LoginProcess extends FreedomService public static final int MIN_USERNAME_LENGTH = 2; public static final int MAX_USERNAME_LENGTH = 20; public static final Pattern USERNAME_REGEX = Pattern.compile("^[\\w\\d_]{3,20}$"); + private static boolean lockdownEnabled = false; public List TELEPORT_ON_JOIN = new ArrayList<>(); public List CLEAR_ON_JOIN = new ArrayList<>(); - @Getter - @Setter - private static boolean lockdownEnabled = false; + public static boolean isLockdownEnabled() + { + return lockdownEnabled; + } + + public static void setLockdownEnabled(boolean lockdownEnabled) + { + LoginProcess.lockdownEnabled = lockdownEnabled; + } @Override public void onStart() @@ -174,7 +179,6 @@ public class LoginProcess extends FreedomService if (!plugin.si.getWhitelisted().contains(username.toLowerCase())) { event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "You are not whitelisted on this server."); - return; } } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/Monitors.java b/src/main/java/me/totalfreedom/totalfreedommod/Monitors.java index 9b771d7d..910d4501 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/Monitors.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/Monitors.java @@ -6,7 +6,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -20,7 +19,6 @@ import org.bukkit.potion.PotionEffectType; public class Monitors extends FreedomService { - @Getter private final List> allThrownPotions = new ArrayList<>(); private final Map> recentlyThrownPotions = new HashMap<>(); private final List badPotionEffects = new ArrayList<>(Arrays.asList(PotionEffectType.BLINDNESS, @@ -141,4 +139,19 @@ public class Monitors extends FreedomService return badEffectsDetected > 0; } + + public List> getAllThrownPotions() + { + return allThrownPotions; + } + + public Map> getRecentlyThrownPotions() + { + return recentlyThrownPotions; + } + + public List getBadPotionEffects() + { + return badPotionEffects; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/MovementValidator.java b/src/main/java/me/totalfreedom/totalfreedommod/MovementValidator.java index 12a11d35..c44d06c5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/MovementValidator.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/MovementValidator.java @@ -41,7 +41,7 @@ public class MovementValidator extends FreedomService public void onPlayerTeleport(PlayerTeleportEvent event) { // Check absolute value to account for negatives - if (Math.abs(event.getTo().getX()) >= MAX_XYZ_COORD || Math.abs(event.getTo().getZ()) >= MAX_XYZ_COORD || Math.abs(event.getTo().getY()) >= MAX_XYZ_COORD) + if (Math.abs(Objects.requireNonNull(event.getTo()).getX()) >= MAX_XYZ_COORD || Math.abs(event.getTo().getZ()) >= MAX_XYZ_COORD || Math.abs(event.getTo().getY()) >= MAX_XYZ_COORD) { event.setCancelled(true); // illegal position, cancel it } @@ -53,6 +53,7 @@ public class MovementValidator extends FreedomService final Player player = event.getPlayer(); Location from = event.getFrom(); Location to = event.getTo(); + assert to != null; if (to.getX() >= from.getX() + MAX_DISTANCE_TRAVELED || to.getY() >= from.getY() + MAX_DISTANCE_TRAVELED || to.getZ() >= from.getZ() + MAX_DISTANCE_TRAVELED) { event.setCancelled(true); @@ -146,8 +147,9 @@ public class MovementValidator extends FreedomService { if (Objects.equals(key, "Amount")) //null-safe .equals() { + @SuppressWarnings("rawtypes") List values = compound.get(key); - for (MojangsonValue val : values) + for (MojangsonValue val : values) { if (val.getValue().toString().equals("Infinityd")) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java b/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java index c5120a6a..22566205 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java @@ -4,10 +4,9 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; import joptsimple.internal.Strings; -import lombok.Getter; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; import me.totalfreedom.totalfreedommod.util.Response; @@ -23,7 +22,6 @@ public class Pterodactyl extends FreedomService private final List SERVER_HEADERS = Arrays.asList("Accept:Application/vnd.pterodactyl.v1+json", "Content-Type:application/json", "Authorization:Bearer " + SERVER_KEY); private final List ADMIN_HEADERS = Arrays.asList("Accept:Application/vnd.pterodactyl.v1+json", "Content-Type:application/json", "Authorization:Bearer " + ADMIN_KEY); - @Getter private boolean enabled = !Strings.isNullOrEmpty(URL); public void onStart() @@ -54,6 +52,7 @@ public class Pterodactyl extends FreedomService addAccountToServer(id); } + @SuppressWarnings("unchecked") public String createAccount(String username, String password) { JSONObject json = new JSONObject(); @@ -94,6 +93,7 @@ public class Pterodactyl extends FreedomService } } + @SuppressWarnings("unchecked") public void addAccountToServer(String id) { String url = URL + "/api/client/servers/" + ConfigEntry.PTERO_SERVER_UUID.getString() + "/users"; @@ -161,6 +161,7 @@ public class Pterodactyl extends FreedomService } // API patch function on users doesnt work rn, it throws 500 errors, so it's probably not written yet + @SuppressWarnings("unchecked") public void setPassword(String id, String password) { JSONObject json = new JSONObject(); @@ -175,4 +176,39 @@ public class Pterodactyl extends FreedomService FLog.severe(e); } } + + public String getURL() + { + return URL; + } + + public String getSERVER_KEY() + { + return SERVER_KEY; + } + + public String getADMIN_KEY() + { + return ADMIN_KEY; + } + + public List getSERVER_HEADERS() + { + return SERVER_HEADERS; + } + + public List getADMIN_HEADERS() + { + return ADMIN_HEADERS; + } + + public boolean isEnabled() + { + return enabled; + } + + public void setEnabled(boolean enabled) + { + this.enabled = enabled; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java b/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java index 8a0cd287..cbb7bfd8 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java @@ -7,6 +7,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import me.totalfreedom.totalfreedommod.util.FLog; import static me.totalfreedom.totalfreedommod.util.FUtil.SAVED_FLAGS_FILENAME; @@ -27,7 +28,7 @@ public class SavedFlags extends FreedomService { Map flags = null; - File input = new File(TotalFreedomMod.plugin().getDataFolder(), SAVED_FLAGS_FILENAME); + File input = new File(Objects.requireNonNull(TotalFreedomMod.plugin()).getDataFolder(), SAVED_FLAGS_FILENAME); if (input.exists()) { try diff --git a/src/main/java/me/totalfreedom/totalfreedommod/ServerInterface.java b/src/main/java/me/totalfreedom/totalfreedommod/ServerInterface.java index 5ed4f8e5..40abc384 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/ServerInterface.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/ServerInterface.java @@ -13,16 +13,6 @@ public class ServerInterface extends FreedomService { public static final String COMPILE_NMS_VERSION = "v1_16_R3"; - @Override - public void onStart() - { - } - - @Override - public void onStop() - { - } - public static void warnVersion() { final String nms = FUtil.getNMSVersion(); @@ -34,6 +24,16 @@ public class ServerInterface extends FreedomService } } + @Override + public void onStart() + { + } + + @Override + public void onStop() + { + } + public void setOnlineMode(boolean mode) { getServer().setOnlineMode(mode); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java b/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java index 7cbc3b8f..dc87115b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java @@ -3,6 +3,8 @@ package me.totalfreedom.totalfreedommod; import java.io.File; import java.io.InputStream; import java.util.Properties; +import me.totalfreedom.totalfreedommod.admin.ActivityLog; +import me.totalfreedom.totalfreedommod.admin.AdminList; import me.totalfreedom.totalfreedommod.banning.BanManager; import me.totalfreedom.totalfreedommod.banning.IndefiniteBanList; import me.totalfreedom.totalfreedommod.blocking.BlockBlocker; @@ -41,8 +43,6 @@ import me.totalfreedom.totalfreedommod.rank.RankManager; import me.totalfreedom.totalfreedommod.shop.Shop; import me.totalfreedom.totalfreedommod.shop.Votifier; import me.totalfreedom.totalfreedommod.sql.SQLite; -import me.totalfreedom.totalfreedommod.admin.ActivityLog; -import me.totalfreedom.totalfreedommod.admin.AdminList; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; import me.totalfreedom.totalfreedommod.util.MethodTimer; @@ -54,23 +54,18 @@ import org.bukkit.Bukkit; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; import org.spigotmc.SpigotConfig; public class TotalFreedomMod extends JavaPlugin { - private static TotalFreedomMod plugin; - - public static TotalFreedomMod getPlugin() - { - return plugin; - } - public static final String CONFIG_FILENAME = "config.yml"; // public static final BuildProperties build = new BuildProperties(); // public static String pluginName; public static String pluginVersion; + private static TotalFreedomMod plugin; // public MainConfig config; public PermissionConfig permissions; @@ -134,7 +129,6 @@ public class TotalFreedomMod extends JavaPlugin public Sitter st; public VanishHandler vh; public Pterodactyl ptero; - //public HubWorldRestrictions hwr; // // Bridges @@ -146,6 +140,23 @@ public class TotalFreedomMod extends JavaPlugin public WorldEditBridge web; public WorldGuardBridge wgb; + public static TotalFreedomMod getPlugin() + { + return plugin; + } + + public static TotalFreedomMod plugin() + { + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) + { + if (plugin.getName().equalsIgnoreCase(pluginName)) + { + return (TotalFreedomMod)plugin; + } + } + return null; + } + @Override public void onLoad() { @@ -192,7 +203,7 @@ public class TotalFreedomMod extends JavaPlugin BackupManager backups = new BackupManager(); backups.createAllBackups(); - permissions = new PermissionConfig(this); + permissions = new PermissionConfig(); permissions.load(); // Start services @@ -291,6 +302,12 @@ public class TotalFreedomMod extends JavaPlugin FLog.info("Plugin disabled"); } + @Override + public ChunkGenerator getDefaultWorldGenerator(@NotNull String worldName, String id) + { + return new CleanroomChunkGenerator(id); + } + public static class BuildProperties { public String author; @@ -332,22 +349,4 @@ public class TotalFreedomMod extends JavaPlugin return pluginVersion + "." + number + " (" + head + ")"; } } - - public static TotalFreedomMod plugin() - { - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) - { - if (plugin.getName().equalsIgnoreCase(pluginName)) - { - return (TotalFreedomMod)plugin; - } - } - return null; - } - - @Override - public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) - { - return new CleanroomChunkGenerator(id); - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/admin/ActivityLog.java b/src/main/java/me/totalfreedom/totalfreedommod/admin/ActivityLog.java index 02dd3023..8c29fdac 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/admin/ActivityLog.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/admin/ActivityLog.java @@ -2,7 +2,6 @@ package me.totalfreedom.totalfreedommod.admin; import com.google.common.collect.Maps; import java.util.Map; -import lombok.Getter; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.YamlConfig; import me.totalfreedom.totalfreedommod.util.FLog; @@ -20,7 +19,6 @@ public class ActivityLog extends FreedomService public static final String FILENAME = "activitylog.yml"; - @Getter private final Map allActivityLogs = Maps.newHashMap(); private final Map nameTable = Maps.newHashMap(); private final Map ipTable = Maps.newHashMap(); @@ -32,6 +30,11 @@ public class ActivityLog extends FreedomService this.config = new YamlConfig(plugin, FILENAME, true); } + public static String getFILENAME() + { + return FILENAME; + } + @Override public void onStart() { @@ -56,7 +59,7 @@ public class ActivityLog extends FreedomService ConfigurationSection section = config.getConfigurationSection(key); if (section == null) { - logger.warning("Invalid activity log format: " + key); + FLog.warning("Invalid activity log format: " + key); continue; } @@ -186,4 +189,24 @@ public class ActivityLog extends FreedomService plugin.acl.updateTables(); } } + + public Map getAllActivityLogs() + { + return allActivityLogs; + } + + public Map getNameTable() + { + return nameTable; + } + + public Map getIpTable() + { + return ipTable; + } + + public YamlConfig getConfig() + { + return config; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/admin/ActivityLogEntry.java b/src/main/java/me/totalfreedom/totalfreedommod/admin/ActivityLogEntry.java index 12b67460..d384d221 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/admin/ActivityLogEntry.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/admin/ActivityLogEntry.java @@ -4,8 +4,6 @@ import com.google.common.collect.Lists; import java.time.Instant; import java.util.Date; import java.util.List; -import lombok.Getter; -import lombok.Setter; import me.totalfreedom.totalfreedommod.config.IConfig; import me.totalfreedom.totalfreedommod.util.FUtil; import org.apache.commons.lang.Validate; @@ -14,21 +12,13 @@ import org.bukkit.entity.Player; public class ActivityLogEntry implements IConfig { - @Getter - private String configKey; - @Getter - @Setter - private String name; - @Getter - private final List ips = Lists.newArrayList(); - @Getter - @Setter - private List timestamps = Lists.newArrayList(); - @Getter - @Setter - private List durations = Lists.newArrayList(); public static final String FILENAME = "activitylog.yml"; + private final List ips = Lists.newArrayList(); + private final List timestamps = Lists.newArrayList(); + private final List durations = Lists.newArrayList(); + private String configKey; + private String name; public ActivityLogEntry(Player player) { @@ -41,6 +31,11 @@ public class ActivityLogEntry implements IConfig this.configKey = configKey; } + public static String getFILENAME() + { + return FILENAME; + } + public void loadFrom(Player player) { configKey = player.getName().toLowerCase(); @@ -108,10 +103,7 @@ public class ActivityLogEntry implements IConfig public void removeIp(String ip) { - if (ips.contains(ip)) - { - ips.remove(ip); - } + ips.remove(ip); } public void clearIPs() @@ -138,4 +130,39 @@ public class ActivityLogEntry implements IConfig return configKey != null && name != null; } + + public String getConfigKey() + { + return configKey; + } + + public void setConfigKey(String configKey) + { + this.configKey = configKey; + } + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public List getIps() + { + return ips; + } + + public List getTimestamps() + { + return timestamps; + } + + public List getDurations() + { + return durations; + } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/admin/Admin.java b/src/main/java/me/totalfreedom/totalfreedommod/admin/Admin.java index 151f4d5d..e04b14a9 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/admin/Admin.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/admin/Admin.java @@ -7,42 +7,35 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import lombok.Getter; -import lombok.Setter; import me.totalfreedom.totalfreedommod.LogViewer.LogsRegistrationMode; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class Admin { - @Getter - @Setter - private String name; - @Getter - private boolean active = true; - @Getter - @Setter - private Rank rank = Rank.ADMIN; - @Getter + + private final List ips = new ArrayList<>(); - @Getter - @Setter + private String name; + private boolean active = true; + private Rank rank = Rank.ADMIN; private Date lastLogin = new Date(); - @Getter - @Setter + + private Boolean commandSpy = false; - @Getter - @Setter + + private Boolean potionSpy = false; - @Getter - @Setter + + private String acFormat = null; - @Getter - @Setter + + private String pteroID = null; public Admin(Player player) @@ -125,10 +118,7 @@ public class Admin public void removeIp(String ip) { - if (ips.contains(ip)) - { - ips.remove(ip); - } + ips.remove(ip); } public void clearIPs() @@ -136,12 +126,42 @@ public class Admin ips.clear(); } + public boolean isValid() + { + return name != null + && rank != null + && !ips.isEmpty() + && lastLogin != null; + } + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public boolean isActive() + { + return active; + } + public void setActive(boolean active) { this.active = active; final TotalFreedomMod plugin = TotalFreedomMod.plugin(); + // Avoiding stupid NPE compiler warnings + if (plugin == null) + { + Bukkit.getLogger().severe("The plugin is null!! This is a major issue and WILL break the plugin!"); + return; + } + if (!active) { if (getRank().isAtLeast(Rank.ADMIN)) @@ -156,11 +176,68 @@ public class Admin } } - public boolean isValid() + public Rank getRank() { - return name != null - && rank != null - && !ips.isEmpty() - && lastLogin != null; + return rank; + } + + public void setRank(Rank rank) + { + this.rank = rank; + } + + public List getIps() + { + return ips; + } + + public Date getLastLogin() + { + return lastLogin; + } + + public void setLastLogin(Date lastLogin) + { + this.lastLogin = lastLogin; + } + + public Boolean getCommandSpy() + { + return commandSpy; + } + + public void setCommandSpy(Boolean commandSpy) + { + this.commandSpy = commandSpy; + } + + public Boolean getPotionSpy() + { + return potionSpy; + } + + public void setPotionSpy(Boolean potionSpy) + { + this.potionSpy = potionSpy; + } + + public String getAcFormat() + { + return acFormat; + } + + public void setAcFormat(String acFormat) + { + this.acFormat = acFormat; + } + + public String getPteroID() + { + return pteroID; + } + + public void setPteroID(String pteroID) + { + this.pteroID = pteroID; } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/admin/AdminList.java b/src/main/java/me/totalfreedom/totalfreedommod/admin/AdminList.java index 18452402..7ed0b9fa 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/admin/AdminList.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/admin/AdminList.java @@ -10,7 +10,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; -import lombok.Getter; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -22,16 +21,19 @@ import org.bukkit.entity.Player; public class AdminList extends FreedomService { - @Getter + public static final List vanished = new ArrayList<>(); + public final List verifiedNoAdmin = new ArrayList<>(); + public final Map> verifiedNoAdminIps = Maps.newHashMap(); private final Set allAdmins = Sets.newHashSet(); // Includes disabled admins // Only active admins below - @Getter private final Set activeAdmins = Sets.newHashSet(); private final Map nameTable = Maps.newHashMap(); private final Map ipTable = Maps.newHashMap(); - public final List verifiedNoAdmin = new ArrayList<>(); - public final Map> verifiedNoAdminIps = Maps.newHashMap(); - public static final List vanished = new ArrayList<>(); + + public static List getVanished() + { + return vanished; + } @Override public void onStart() @@ -249,14 +251,14 @@ public class AdminList extends FreedomService } Admin admin = getAdmin(player); - return admin == null ? false : admin.getName().equalsIgnoreCase(player.getName()); + return admin != null && admin.getName().equalsIgnoreCase(player.getName()); } public boolean addAdmin(Admin admin) { if (!admin.isValid()) { - logger.warning("Could not add admin: " + admin.getName() + ". Admin is missing details!"); + FLog.warning("Could not add admin: " + admin.getName() + ". Admin is missing details!"); return false; } @@ -380,4 +382,34 @@ public class AdminList extends FreedomService { return vanished.contains(player); } + + public Set getAllAdmins() + { + return allAdmins; + } + + public Set getActiveAdmins() + { + return activeAdmins; + } + + public Map getNameTable() + { + return nameTable; + } + + public Map getIpTable() + { + return ipTable; + } + + public List getVerifiedNoAdmin() + { + return verifiedNoAdmin; + } + + public Map> getVerifiedNoAdminIps() + { + return verifiedNoAdminIps; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/banning/Ban.java b/src/main/java/me/totalfreedom/totalfreedommod/banning/Ban.java index e1a96955..36940683 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/banning/Ban.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/banning/Ban.java @@ -4,15 +4,12 @@ import com.google.common.collect.Lists; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; -import lombok.Getter; -import lombok.Setter; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.ChatColor; @@ -22,27 +19,19 @@ import org.bukkit.entity.Player; public class Ban { - public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd \'at\' HH:mm:ss z"); - - @Getter - @Setter - private String username = null; - @Getter - @Setter - private UUID uuid = null; - @Getter + public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); private final List ips = Lists.newArrayList(); - @Getter - @Setter + private String username = null; + private UUID uuid = null; private String by = null; - @Getter - @Setter + + private Date at = null; - @Getter - @Setter + + private String reason = null; // Unformatted, &[0-9,a-f] instead of ChatColor - @Getter - @Setter + + private long expiryUnix = -1; public Ban() @@ -53,7 +42,7 @@ public class Ban { this(username, uuid, - Arrays.asList(ip), + Collections.singletonList(ip), by, at, expire, @@ -88,7 +77,7 @@ public class Ban public static Ban forPlayerIp(Player player, CommandSender by, Date expiry, String reason) { - return new Ban(null, null, Arrays.asList(FUtil.getIp(player)), by.getName(), Date.from(Instant.now()), expiry, reason); + return new Ban(null, null, Collections.singletonList(FUtil.getIp(player)), by.getName(), Date.from(Instant.now()), expiry, reason); } public static Ban forPlayerIp(String ip, CommandSender by, Date expiry, String reason) @@ -143,6 +132,11 @@ public class Ban reason); } + public static SimpleDateFormat getDateFormat() + { + return DATE_FORMAT; + } + public boolean hasUsername() { return username != null && !username.isEmpty(); @@ -256,16 +250,74 @@ public class Ban private void dedupeIps() { - Set uniqueIps = new HashSet<>(); - Iterator it = ips.iterator(); - while (it.hasNext()) - { - if (!uniqueIps.add(it.next())) - { - it.remove(); - } - } + //Fancy Collections.removeIf lets you do all that while loop work in one lambda. + ips.removeIf(s -> !uniqueIps.add(s)); + } + + public List getIps() + { + return ips; + } + + public String getUsername() + { + return username; + } + + public void setUsername(String username) + { + this.username = username; + } + + public UUID getUuid() + { + return uuid; + } + + public void setUuid(UUID uuid) + { + this.uuid = uuid; + } + + public String getBy() + { + return by; + } + + public void setBy(String by) + { + this.by = by; + } + + public Date getAt() + { + return at; + } + + public void setAt(Date at) + { + this.at = at; + } + + public String getReason() + { + return reason; + } + + public void setReason(String reason) + { + this.reason = reason; + } + + public long getExpiryUnix() + { + return expiryUnix; + } + + public void setExpiryUnix(long expiryUnix) + { + this.expiryUnix = expiryUnix; } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/banning/BanManager.java b/src/main/java/me/totalfreedom/totalfreedommod/banning/BanManager.java index 81afad25..03b6465a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/banning/BanManager.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/banning/BanManager.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.ConfigEntry; -import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.entity.Player; @@ -74,7 +73,7 @@ public class BanManager extends FreedomService // Load unbannable usernames unbannableUsernames.clear(); - unbannableUsernames.addAll((Collection)ConfigEntry.FAMOUS_PLAYERS.getList()); + unbannableUsernames.addAll(ConfigEntry.FAMOUS_PLAYERS.getStringList()); FLog.info("Loaded " + unbannableUsernames.size() + " unbannable usernames."); } @@ -190,7 +189,7 @@ public class BanManager extends FreedomService return getByUsername(username) != null; } - public boolean addBan(Ban ban) + public void addBan(Ban ban) { if (ban.getUsername() != null && getByUsername(ban.getUsername()) != null) { @@ -213,22 +212,18 @@ public class BanManager extends FreedomService { plugin.sql.addBan(ban); updateViews(); - return true; } - return false; } - public boolean removeBan(Ban ban) + public void removeBan(Ban ban) { if (bans.remove(ban)) { plugin.sql.removeBan(ban); updateViews(); - return true; } - return false; } public int purge() diff --git a/src/main/java/me/totalfreedom/totalfreedommod/banning/IndefiniteBan.java b/src/main/java/me/totalfreedom/totalfreedommod/banning/IndefiniteBan.java index a6c38690..8f9eb229 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/banning/IndefiniteBan.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/banning/IndefiniteBan.java @@ -3,25 +3,15 @@ package me.totalfreedom.totalfreedommod.banning; import com.google.common.collect.Lists; import java.util.List; import java.util.UUID; -import lombok.Getter; -import lombok.Setter; import me.totalfreedom.totalfreedommod.config.IConfig; import me.totalfreedom.totalfreedommod.util.FLog; import org.bukkit.configuration.ConfigurationSection; public class IndefiniteBan implements IConfig { - - @Getter - @Setter - private String username = null; - @Getter - @Setter - private UUID uuid = null; - @Getter private final List ips = Lists.newArrayList(); - @Getter - @Setter + private String username = null; + private UUID uuid = null; private String reason = null; public IndefiniteBan() @@ -60,4 +50,39 @@ public class IndefiniteBan implements IConfig { return username != null; } + + public String getUsername() + { + return username; + } + + public void setUsername(String username) + { + this.username = username; + } + + public UUID getUuid() + { + return uuid; + } + + public void setUuid(UUID uuid) + { + this.uuid = uuid; + } + + public List getIps() + { + return ips; + } + + public String getReason() + { + return reason; + } + + public void setReason(String reason) + { + this.reason = reason; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/banning/IndefiniteBanList.java b/src/main/java/me/totalfreedom/totalfreedommod/banning/IndefiniteBanList.java index ab2009ab..0ea5b73b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/banning/IndefiniteBanList.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/banning/IndefiniteBanList.java @@ -4,7 +4,6 @@ import com.google.common.base.Strings; import com.google.common.collect.Sets; import java.util.Set; import java.util.UUID; -import lombok.Getter; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.config.YamlConfig; @@ -21,18 +20,23 @@ public class IndefiniteBanList extends FreedomService public static final String CONFIG_FILENAME = "indefinitebans.yml"; - @Getter + private final Set indefBans = Sets.newHashSet(); - @Getter + private int nameBanCount = 0; - @Getter + private int uuidBanCount = 0; - @Getter + private int ipBanCount = 0; + public static String getConfigFilename() + { + return CONFIG_FILENAME; + } + @Override public void onStart() { @@ -51,6 +55,7 @@ public class IndefiniteBanList extends FreedomService IndefiniteBan indefBan = new IndefiniteBan(); ConfigurationSection cs = config.getConfigurationSection(name); + assert cs != null; indefBan.loadFrom(cs); if (!indefBan.isValid()) @@ -84,7 +89,7 @@ public class IndefiniteBanList extends FreedomService for (IndefiniteBan indefBan : indefBans) { - if (username.toLowerCase().equals(indefBan.getUsername().toLowerCase())) + if (username.equalsIgnoreCase(indefBan.getUsername())) { bannedBy = "username"; ban = indefBan; @@ -137,4 +142,24 @@ public class IndefiniteBanList extends FreedomService ipBanCount += indefBan.getIps().size(); } } + + public Set getIndefBans() + { + return indefBans; + } + + public int getNameBanCount() + { + return nameBanCount; + } + + public int getUuidBanCount() + { + return uuidBanCount; + } + + public int getIpBanCount() + { + return ipBanCount; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/BlockBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/BlockBlocker.java index 4f29a21e..db80dff9 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/BlockBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/BlockBlocker.java @@ -29,6 +29,7 @@ public class BlockBlocker extends FreedomService { } + @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGH) public void onBlockPlace(BlockPlaceEvent event) { @@ -143,6 +144,7 @@ public class BlockBlocker extends FreedomService { ItemStack newHead = new ItemStack(Material.PLAYER_HEAD, 1); ItemMeta headMeta = newHead.getItemMeta(); + assert headMeta != null; headMeta.setDisplayName(ChatColor.YELLOW + "C-sectioned Head"); newHead.setItemMeta(headMeta); player.getInventory().setItem(player.getInventory().getHeldItemSlot(), newHead); @@ -175,7 +177,7 @@ public class BlockBlocker extends FreedomService { Banner banner = (Banner)event.getBlockPlaced().getState(); List patterns = banner.getPatterns(); - ; + if (patterns.size() >= 2) { banner.setPatterns(patterns.subList(0, 2)); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java index 3daa67e9..73e7bc7a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java @@ -3,6 +3,7 @@ package me.totalfreedom.totalfreedommod.blocking; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.util.FUtil; @@ -24,7 +25,6 @@ import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockRedstoneEvent; import org.bukkit.event.block.LeavesDecayEvent; import org.bukkit.event.entity.EntityCombustEvent; import org.bukkit.event.entity.EntityDamageEvent; @@ -38,6 +38,20 @@ import org.bukkit.event.player.PlayerRespawnEvent; public class EventBlocker extends FreedomService { + /** + * /@EventHandler(priority = EventPriority.HIGH) + * /public void onBlockRedstone(BlockRedstoneEvent event) + * /{ + * / if (!ConfigEntry.ALLOW_REDSTONE.getBoolean()) + * / { + * / event.setNewCurrent(0); + * / } + * /} + **/ + + // TODO: Revert back to old redstone block system when (or if) it is fixed in Bukkit, Spigot or Paper. + private final ArrayList redstoneBlocks = new ArrayList<>(Arrays.asList(Material.REDSTONE, Material.DISPENSER, Material.DROPPER, Material.REDSTONE_LAMP)); + @Override public void onStart() { @@ -120,15 +134,12 @@ public class EventBlocker extends FreedomService @EventHandler(priority = EventPriority.HIGH) public void onEntityDamage(EntityDamageEvent event) { - switch (event.getCause()) + if (event.getCause() == EntityDamageEvent.DamageCause.LAVA) { - case LAVA: + if (!ConfigEntry.ALLOW_LAVA_DAMAGE.getBoolean()) { - if (!ConfigEntry.ALLOW_LAVA_DAMAGE.getBoolean()) - { - event.setCancelled(true); - return; - } + event.setCancelled(true); + return; } } @@ -203,18 +214,6 @@ public class EventBlocker extends FreedomService } } - //@EventHandler(priority = EventPriority.HIGH) - public void onBlockRedstone(BlockRedstoneEvent event) - { - if (!ConfigEntry.ALLOW_REDSTONE.getBoolean()) - { - event.setNewCurrent(0); - } - } - - // TODO: Revert back to old redstone block system when (or if) it is fixed in Bukkit, Spigot or Paper. - private ArrayList redstoneBlocks = new ArrayList<>(Arrays.asList(Material.REDSTONE, Material.DISPENSER, Material.DROPPER, Material.REDSTONE_LAMP)); - @EventHandler public void onBlockPhysics(BlockPhysicsEvent event) { @@ -231,12 +230,12 @@ public class EventBlocker extends FreedomService @EventHandler(priority = EventPriority.NORMAL) public void onPlayerRespawn(PlayerRespawnEvent event) { - double maxHealth = event.getPlayer().getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(); + double maxHealth = Objects.requireNonNull(event.getPlayer().getAttribute(Attribute.GENERIC_MAX_HEALTH)).getValue(); if (maxHealth < 1) { - for (AttributeModifier attributeModifier : event.getPlayer().getAttribute(Attribute.GENERIC_MAX_HEALTH).getModifiers()) + for (AttributeModifier attributeModifier : Objects.requireNonNull(event.getPlayer().getAttribute(Attribute.GENERIC_MAX_HEALTH)).getModifiers()) { - event.getPlayer().getAttribute(Attribute.GENERIC_MAX_HEALTH).removeModifier(attributeModifier); + Objects.requireNonNull(event.getPlayer().getAttribute(Attribute.GENERIC_MAX_HEALTH)).removeModifier(attributeModifier); } } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/MobBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/MobBlocker.java index a727e10a..2dae585b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/MobBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/MobBlocker.java @@ -1,5 +1,6 @@ package me.totalfreedom.totalfreedommod.blocking; +import java.util.Objects; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import org.bukkit.attribute.Attributable; @@ -42,13 +43,13 @@ public class MobBlocker extends FreedomService Entity entity = e.getEntity(); if (entity instanceof Attributable) { - if (((Attributable)entity).getAttribute(Attribute.GENERIC_FOLLOW_RANGE).getBaseValue() > 255.0) + if (Objects.requireNonNull(((Attributable)entity).getAttribute(Attribute.GENERIC_FOLLOW_RANGE)).getBaseValue() > 255.0) { - ((Attributable)entity).getAttribute(Attribute.GENERIC_FOLLOW_RANGE).setBaseValue(255.0); + Objects.requireNonNull(((Attributable)entity).getAttribute(Attribute.GENERIC_FOLLOW_RANGE)).setBaseValue(255.0); } - if (((Attributable)entity).getAttribute(Attribute.GENERIC_MOVEMENT_SPEED).getBaseValue() > 10.0) + if (Objects.requireNonNull(((Attributable)entity).getAttribute(Attribute.GENERIC_MOVEMENT_SPEED)).getBaseValue() > 10.0) { - ((Attributable)entity).getAttribute(Attribute.GENERIC_MOVEMENT_SPEED).setBaseValue(10.0); + Objects.requireNonNull(((Attributable)entity).getAttribute(Attribute.GENERIC_MOVEMENT_SPEED)).setBaseValue(10.0); } } } @@ -117,7 +118,7 @@ public class MobBlocker extends FreedomService } int mobcount = 0; - for (Entity entity : event.getLocation().getWorld().getLivingEntities()) + for (Entity entity : Objects.requireNonNull(event.getLocation().getWorld()).getLivingEntities()) { if (!(entity instanceof HumanEntity) && entity instanceof LivingEntity) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/SignBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/SignBlocker.java index c98cb8b9..261ce274 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/SignBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/SignBlocker.java @@ -37,6 +37,7 @@ public class SignBlocker extends FreedomService ItemStack sign = event.getItemInHand(); net.minecraft.server.v1_16_R3.ItemStack nmsSign = CraftItemStack.asNMSCopy(sign); NBTTagCompound compound = (nmsSign.hasTag()) ? nmsSign.getTag() : new NBTTagCompound(); + assert compound != null; NBTTagCompound bet = compound.getCompound("BlockEntityTag"); String line1 = bet.getString("Text1"); String line2 = bet.getString("Text2"); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlocker.java index 84934a25..2074f3e5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlocker.java @@ -30,6 +30,24 @@ public class CommandBlocker extends FreedomService private final Map entryList = Maps.newHashMap(); private final List unknownCommands = Lists.newArrayList(); + public static CommandMap getCommandMap() + { + try + { + SimplePluginManager simplePluginManager = (SimplePluginManager)Bukkit.getServer().getPluginManager(); + + Field commandMapField = SimplePluginManager.class.getDeclaredField("commandMap"); + commandMapField.setAccessible(true); + + return (SimpleCommandMap)commandMapField.get(simplePluginManager); + } + catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) + { + FLog.severe("Failed to get command map field (" + e.getMessage() + ")"); + } + return null; + } + @Override public void onStart() { @@ -42,25 +60,6 @@ public class CommandBlocker extends FreedomService entryList.clear(); } - public static CommandMap getCommandMap() - { - try - { - SimplePluginManager simplePluginManager = (SimplePluginManager)Bukkit.getServer().getPluginManager(); - - Field commandMapField = SimplePluginManager.class.getDeclaredField("commandMap"); - commandMapField.setAccessible(true); - - SimpleCommandMap simpleCommandMap = (SimpleCommandMap)commandMapField.get(simplePluginManager); - return simpleCommandMap; - } - catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) - { - FLog.severe("Failed to get command map field (" + e.getMessage() + ")"); - } - return null; - } - public void load() { entryList.clear(); @@ -84,7 +83,7 @@ public class CommandBlocker extends FreedomService String commandName = parts[2].toLowerCase().substring(1); final String message = (parts.length > 3 ? parts[3] : null); - if (rank == null || action == null || commandName == null || commandName.isEmpty()) + if (rank == null || action == null || commandName.isEmpty()) { FLog.warning("Invalid command blocker entry: " + rawEntry); continue; @@ -98,6 +97,7 @@ public class CommandBlocker extends FreedomService subCommand = StringUtils.join(commandParts, " ", 1, commandParts.length).trim().toLowerCase(); } + assert commandMap != null; final Command command = commandMap.getCommand(commandName); // Obtain command from alias diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerAction.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerAction.java index 615e5fb2..07b76d18 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerAction.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerAction.java @@ -13,11 +13,6 @@ public enum CommandBlockerAction this.token = token; } - public String getToken() - { - return this.token; - } - public static CommandBlockerAction fromToken(String token) { for (CommandBlockerAction action : CommandBlockerAction.values()) @@ -29,4 +24,9 @@ public enum CommandBlockerAction } return null; } + + public String getToken() + { + return this.token; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerEntry.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerEntry.java index deb43964..f5d2e25c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerEntry.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerEntry.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.blocking.command; -import lombok.Getter; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.ChatColor; @@ -11,15 +10,15 @@ import org.spigotmc.SpigotConfig; public class CommandBlockerEntry { - @Getter + private final CommandBlockerRank rank; - @Getter + private final CommandBlockerAction action; - @Getter + private final String command; - @Getter + private final String subCommand; - @Getter + private final String message; public CommandBlockerEntry(CommandBlockerRank rank, CommandBlockerAction action, String command, String message) @@ -51,4 +50,29 @@ public class CommandBlockerEntry } FUtil.playerMsg(sender, FUtil.colorize(message)); } + + public CommandBlockerRank getRank() + { + return rank; + } + + public CommandBlockerAction getAction() + { + return action; + } + + public String getCommand() + { + return command; + } + + public String getSubCommand() + { + return subCommand; + } + + public String getMessage() + { + return message; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerRank.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerRank.java index 83e7bdf7..83b8c009 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerRank.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerRank.java @@ -1,8 +1,9 @@ package me.totalfreedom.totalfreedommod.blocking.command; +import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; -import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.command.CommandSender; public enum CommandBlockerRank @@ -20,19 +21,9 @@ public enum CommandBlockerRank this.token = token; } - public String getToken() - { - return this.token; - } - - public boolean hasPermission(CommandSender sender) - { - return fromSender(sender).ordinal() >= ordinal(); - } - public static CommandBlockerRank fromSender(CommandSender sender) { - Admin admin = TotalFreedomMod.plugin().al.getAdmin(sender); + Admin admin = Objects.requireNonNull(TotalFreedomMod.plugin()).al.getAdmin(sender); if (admin != null) { if (admin.getRank() == Rank.SENIOR_ADMIN) @@ -61,4 +52,14 @@ public enum CommandBlockerRank } return EVERYONE; } + + public String getToken() + { + return this.token; + } + + public boolean hasPermission(CommandSender sender) + { + return fromSender(sender).ordinal() >= ordinal(); + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/BukkitTelnetBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/BukkitTelnetBridge.java index 42312e50..479a30e1 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/BukkitTelnetBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/BukkitTelnetBridge.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.bridge; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Map; import me.totalfreedom.bukkittelnet.BukkitTelnet; @@ -10,8 +9,8 @@ import me.totalfreedom.bukkittelnet.api.TelnetPreLoginEvent; import me.totalfreedom.bukkittelnet.api.TelnetRequestDataTagsEvent; import me.totalfreedom.bukkittelnet.session.ClientSession; import me.totalfreedom.totalfreedommod.FreedomService; -import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FLog; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/CoreProtectBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/CoreProtectBridge.java index 0f496d01..8c60857d 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/CoreProtectBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/CoreProtectBridge.java @@ -36,16 +36,47 @@ import org.bukkit.scheduler.BukkitTask; public class CoreProtectBridge extends FreedomService { - private CoreProtectAPI coreProtectAPI = null; - + public static Map> HISTORY_MAP = new HashMap<>(); private final List tables = Arrays.asList("co_sign", "co_session", "co_container", "co_block"); private final HashMap cooldown = new HashMap<>(); - - public static Map> HISTORY_MAP = new HashMap<>(); - + private CoreProtectAPI coreProtectAPI = null; private BukkitTask wiper; + public static Long getSecondsLeft(long prevTime, int timeAdd) + { + return prevTime / 1000L + timeAdd - System.currentTimeMillis() / 1000L; + } + + // Unix timestamp converter taken from Functions class in CoreProtect, not my code + public static String getTimeAgo(int logTime, int currentTime) + { + StringBuilder message = new StringBuilder(); + double timeSince = (double)currentTime - ((double)logTime + 0.0D); + timeSince /= 60.0D; + if (timeSince < 60.0D) + { + message.append((new DecimalFormat("0.00")).format(timeSince)).append("/m ago"); + } + + if (message.length() == 0) + { + timeSince /= 60.0D; + if (timeSince < 24.0D) + { + message.append((new DecimalFormat("0.00")).format(timeSince)).append("/h ago"); + } + } + + if (message.length() == 0) + { + timeSince /= 24.0D; + message.append((new DecimalFormat("0.00")).format(timeSince)).append("/d ago"); + } + + return message.toString(); + } + @Override public void onStart() { @@ -62,8 +93,8 @@ public class CoreProtectBridge extends FreedomService try { final Plugin coreProtectPlugin = Bukkit.getServer().getPluginManager().getPlugin("CoreProtect"); - - if (coreProtectPlugin != null && coreProtectPlugin instanceof CoreProtect) + assert coreProtectPlugin != null; + if (coreProtectPlugin instanceof CoreProtect) { coreProtect = (CoreProtect)coreProtectPlugin; } @@ -187,7 +218,7 @@ public class CoreProtectBridge extends FreedomService /* As CoreProtect doesn't have an API method for deleting all of the data for a specific world we have to do this manually via SQL */ - Connection connection = null; + Connection connection; try { String host = ConfigEntry.COREPROTECT_MYSQL_HOST.getString(); @@ -237,40 +268,6 @@ public class CoreProtectBridge extends FreedomService } } - public static Long getSecondsLeft(long prevTime, int timeAdd) - { - return prevTime / 1000L + timeAdd - System.currentTimeMillis() / 1000L; - } - - // Unix timestamp converter taken from Functions class in CoreProtect, not my code - public static String getTimeAgo(int logTime, int currentTime) - { - StringBuilder message = new StringBuilder(); - double timeSince = (double)currentTime - ((double)logTime + 0.0D); - timeSince /= 60.0D; - if (timeSince < 60.0D) - { - message.append((new DecimalFormat("0.00")).format(timeSince)).append("/m ago"); - } - - if (message.length() == 0) - { - timeSince /= 60.0D; - if (timeSince < 24.0D) - { - message.append((new DecimalFormat("0.00")).format(timeSince)).append("/h ago"); - } - } - - if (message.length() == 0) - { - timeSince /= 24.0D; - message.append((new DecimalFormat("0.00")).format(timeSince)).append("/d ago"); - } - - return message.toString(); - } - @EventHandler(priority = EventPriority.MONITOR) public void onPlayerInteract(PlayerInteractEvent event) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java index 7e53a5e6..83670976 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java @@ -42,7 +42,8 @@ public class EssentialsBridge extends FreedomService try { final Plugin essentials = server.getPluginManager().getPlugin("Essentials"); - if (essentials != null && essentials instanceof Essentials) + assert essentials != null; + if (essentials instanceof Essentials) { essentialsPlugin = (Essentials)essentials; } @@ -113,7 +114,15 @@ public class EssentialsBridge extends FreedomService User user = getEssentialsUser(username); if (user != null) { - return FUtil.getField(user, "lastActivity"); + Long l = FUtil.getField(user, "lastActivity"); + if (l != null) + { + return l; + } + else + { + return 0L; + } } } catch (Exception ex) @@ -150,7 +159,7 @@ public class EssentialsBridge extends FreedomService if (inventoryType == InventoryType.PLAYER && fPlayer.isInvSee()) { final InventoryHolder inventoryHolder = inventory.getHolder(); - if (inventoryHolder != null && inventoryHolder instanceof HumanEntity) + if (inventoryHolder instanceof HumanEntity) { Player invOwner = (Player)inventoryHolder; Rank recieverRank = plugin.rm.getRank(player); @@ -203,6 +212,7 @@ public class EssentialsBridge extends FreedomService } } + // TODO: Actually use this for something or remove it. @EventHandler(priority = EventPriority.MONITOR) public void onPlayerQuit(PlayerQuitEvent event) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/LibsDisguisesBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/LibsDisguisesBridge.java index 99e9739e..88db08ab 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/LibsDisguisesBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/LibsDisguisesBridge.java @@ -75,6 +75,11 @@ public class LibsDisguisesBridge extends FreedomService } } + public boolean isDisguisesEnabled() + { + return !BlockedDisguises.disabled; + } + public void setDisguisesEnabled(boolean state) { final LibsDisguises libsDisguises = getLibsDisguisesPlugin(); @@ -87,11 +92,6 @@ public class LibsDisguisesBridge extends FreedomService BlockedDisguises.disabled = !state; } - public boolean isDisguisesEnabled() - { - return !BlockedDisguises.disabled; - } - public boolean isEnabled() { final LibsDisguises libsDisguises = getLibsDisguisesPlugin(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/WorldEditBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/WorldEditBridge.java index 90e02e66..79ccaa6f 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/WorldEditBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/WorldEditBridge.java @@ -60,8 +60,7 @@ public class WorldEditBridge extends FreedomService { for (int i = 0; i < count; i++) { - com.sk89q.worldedit.entity.Player fuckyou = bukkitPlayer; - session.undo(session.getBlockBag(fuckyou), fuckyou); + session.undo(session.getBlockBag(bukkitPlayer), bukkitPlayer); } } } @@ -84,8 +83,7 @@ public class WorldEditBridge extends FreedomService { for (int i = 0; i < count; i++) { - com.sk89q.worldedit.entity.Player fuckyou = (com.sk89q.worldedit.entity.Player)bukkitPlayer; - session.redo(session.getBlockBag(fuckyou), fuckyou); + session.redo(session.getBlockBag(bukkitPlayer), bukkitPlayer); } } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/caging/CageData.java b/src/main/java/me/totalfreedom/totalfreedommod/caging/CageData.java index bac9127e..16408f09 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/caging/CageData.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/caging/CageData.java @@ -2,7 +2,6 @@ package me.totalfreedom.totalfreedommod.caging; import java.util.ArrayList; import java.util.List; -import lombok.Getter; import me.totalfreedom.totalfreedommod.player.FPlayer; import org.bukkit.Location; import org.bukkit.Material; @@ -12,141 +11,21 @@ import org.bukkit.block.Skull; public class CageData { + private static String input = null; private final FPlayer fPlayer; // - private final List cageHistory = new ArrayList<>(); // - @Getter + private final List cageHistory = new ArrayList<>(); private boolean caged = false; - @Getter private Location location; - @Getter private Material outerMaterial = Material.GLASS; - @Getter private Material innerMaterial = Material.AIR; - @Getter - private static String input = null; public CageData(FPlayer player) { this.fPlayer = player; } - public void setCaged(boolean cage) - { - if (cage) - { - cage(fPlayer.getPlayer().getLocation(), Material.GLASS, Material.GLASS); - } - else - { - this.caged = false; - regenerateHistory(); - clearHistory(); - } - - } - - public void cage(Location location, Material outer, Material inner) - { - if (isCaged()) - { - setCaged(false); - } - - this.caged = true; - this.location = location; - this.outerMaterial = outer; - this.innerMaterial = inner; - this.input = null; - - buildHistory(location, 2, fPlayer); - regenerate(); - } - - public void cage(Location location, Material outer, Material inner, String input) - { - if (isCaged()) - { - setCaged(false); - } - - this.caged = true; - this.location = location; - this.outerMaterial = outer; - this.innerMaterial = inner; - this.input = input; - - buildHistory(location, 2, fPlayer); - regenerate(); - } - - public void regenerate() - { - - if (!caged - || location == null - || outerMaterial == null - || innerMaterial == null) - { - return; - } - - generateHollowCube(location, 2, outerMaterial); - generateCube(location, 1, innerMaterial); - } - - // TODO: EventHandlerize this? - public void playerJoin() - { - if (!isCaged()) - { - return; - } - - cage(fPlayer.getPlayer().getLocation(), outerMaterial, innerMaterial, input); - } - - public void playerQuit() - { - regenerateHistory(); - clearHistory(); - } - - public void clearHistory() - { - cageHistory.clear(); - } - - private void insertHistoryBlock(Location location, Material material) - { - cageHistory.add(new BlockData(location, material)); - } - - private void regenerateHistory() - { - for (BlockData blockdata : this.cageHistory) - { - blockdata.location.getBlock().setType(blockdata.material); - } - } - - private void buildHistory(Location location, int length, FPlayer playerdata) - { - final Block center = location.getBlock(); - for (int xOffset = -length; xOffset <= length; xOffset++) - { - for (int yOffset = -length; yOffset <= length; yOffset++) - { - for (int zOffset = -length; zOffset <= length; zOffset++) - { - final Block block = center.getRelative(xOffset, yOffset, zOffset); - insertHistoryBlock(block.getLocation(), block.getType()); - } - } - } - } - // Util methods public static void generateCube(Location location, int length, Material material) { @@ -167,6 +46,7 @@ public class CageData } } + @SuppressWarnings("deprecation") public static void generateHollowCube(Location location, int length, Material material) { final Block center = location.getBlock(); @@ -213,7 +93,7 @@ public class CageData skull.setOwner(input); skull.update(); } - catch (ClassCastException e) + catch (ClassCastException ignored) { } } @@ -223,6 +103,176 @@ public class CageData } } + public static String getInput() + { + return input; + } + + public static void setInput(String input) + { + CageData.input = input; + } + + public void cage(Location location, Material outer, Material inner) + { + if (isCaged()) + { + setCaged(false); + } + + this.caged = true; + this.location = location; + this.outerMaterial = outer; + this.innerMaterial = inner; + input = null; + + buildHistory(location, fPlayer); + regenerate(); + } + + public void cage(Location location, Material outer, Material inner, String input) + { + if (isCaged()) + { + setCaged(false); + } + + this.caged = true; + this.location = location; + this.outerMaterial = outer; + this.innerMaterial = inner; + CageData.input = input; + + buildHistory(location, fPlayer); + regenerate(); + } + + public void regenerate() + { + + if (!caged + || location == null + || outerMaterial == null + || innerMaterial == null) + { + return; + } + + generateHollowCube(location, 2, outerMaterial); + generateCube(location, 1, innerMaterial); + } + + // TODO: EventHandler this? + public void playerJoin() + { + if (!isCaged()) + { + return; + } + + cage(fPlayer.getPlayer().getLocation(), outerMaterial, innerMaterial, input); + } + + public void playerQuit() + { + regenerateHistory(); + clearHistory(); + } + + public void clearHistory() + { + cageHistory.clear(); + } + + private void insertHistoryBlock(Location location, Material material) + { + cageHistory.add(new BlockData(location, material)); + } + + private void regenerateHistory() + { + for (BlockData blockdata : this.cageHistory) + { + blockdata.location.getBlock().setType(blockdata.material); + } + } + + private void buildHistory(Location location, FPlayer playerdata) + { + final Block center = location.getBlock(); + for (int xOffset = -2; xOffset <= 2; xOffset++) + { + for (int yOffset = -2; yOffset <= 2; yOffset++) + { + for (int zOffset = -2; zOffset <= 2; zOffset++) + { + final Block block = center.getRelative(xOffset, yOffset, zOffset); + insertHistoryBlock(block.getLocation(), block.getType()); + } + } + } + } + + public FPlayer getfPlayer() + { + return fPlayer; + } + + public List getCageHistory() + { + return cageHistory; + } + + public boolean isCaged() + { + return caged; + } + + public void setCaged(boolean cage) + { + if (cage) + { + cage(fPlayer.getPlayer().getLocation(), Material.GLASS, Material.GLASS); + } + else + { + this.caged = false; + regenerateHistory(); + clearHistory(); + } + + } + + public Location getLocation() + { + return location; + } + + public void setLocation(Location location) + { + this.location = location; + } + + public Material getOuterMaterial() + { + return outerMaterial; + } + + public void setOuterMaterial(Material outerMaterial) + { + this.outerMaterial = outerMaterial; + } + + public Material getInnerMaterial() + { + return innerMaterial; + } + + public void setInnerMaterial(Material innerMaterial) + { + this.innerMaterial = innerMaterial; + } + private static class BlockData { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/caging/Cager.java b/src/main/java/me/totalfreedom/totalfreedommod/caging/Cager.java index 3f7be6fe..d520f7ba 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/caging/Cager.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/caging/Cager.java @@ -1,6 +1,7 @@ package me.totalfreedom.totalfreedommod.caging; import io.papermc.lib.PaperLib; +import java.util.Objects; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.util.FUtil; @@ -31,7 +32,7 @@ public class Cager extends FreedomService public void onBreakBlock(BlockBreakEvent event) { Player player = event.getPlayer(); - if (player == null || plugin.al.isAdmin(player)) + if (plugin.al.isAdmin(player)) { return; } @@ -60,7 +61,7 @@ public class Cager extends FreedomService Location cageLoc = cage.getLocation(); final boolean outOfCage; - if (!playerLoc.getWorld().equals(cageLoc.getWorld())) + if (!Objects.equals(playerLoc.getWorld(), cageLoc.getWorld())) { outOfCage = true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_adminworld.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_adminworld.java index 6713f34d..9067e1b7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_adminworld.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_adminworld.java @@ -19,11 +19,6 @@ import org.bukkit.entity.Player; public class Command_adminworld extends FreedomCommand { - private enum CommandMode - { - TELEPORT, TIME, WEATHER - } - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -66,7 +61,7 @@ public class Command_adminworld extends FreedomCommand { adminWorld = plugin.wm.adminworld.getWorld(); } - catch (Exception ex) + catch (Exception ignored) { } @@ -158,22 +153,6 @@ public class Command_adminworld extends FreedomCommand } } - private class PermissionDeniedException extends Exception - { - - private static final long serialVersionUID = 1L; - - private PermissionDeniedException() - { - super(""); - } - - private PermissionDeniedException(String string) - { - super(string); - } - } - @Override public List getTabCompleteOptions(CommandSender sender, Command command, String alias, String[] args) { @@ -198,4 +177,25 @@ public class Command_adminworld extends FreedomCommand } return Collections.emptyList(); } + + private enum CommandMode + { + TELEPORT, TIME, WEATHER + } + + private static class PermissionDeniedException extends Exception + { + + private static final long serialVersionUID = 1L; + + private PermissionDeniedException() + { + super(""); + } + + private PermissionDeniedException(String string) + { + super(string); + } + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_attributelist.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_attributelist.java index 8cb9a189..6a7697d7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_attributelist.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_attributelist.java @@ -14,17 +14,17 @@ public class Command_attributelist extends FreedomCommand @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { - String list = "All possible attributes: "; + StringBuilder list = new StringBuilder("All possible attributes: "); for (Attribute attribute : Attribute.values()) { - list += attribute.name() + ", "; + list.append(attribute.name()).append(", "); } // Remove extra comma at the end of the list - list = list.substring(0, list.length() - 2); + list = new StringBuilder(list.substring(0, list.length() - 2)); - msg(list); + msg(list.toString()); return true; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ban.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ban.java index 51e642c9..c6b38381 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ban.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ban.java @@ -2,6 +2,7 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.banning.Ban; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.punishments.Punishment; @@ -31,8 +32,8 @@ public class Command_ban extends FreedomCommand } String reason = null; - Boolean silent = false; - Boolean cancelRollback = false; + boolean silent = false; + boolean cancelRollback = false; if (args.length >= 2) { if (args[args.length - 1].equalsIgnoreCase("-nrb") || args[args.length - 1].equalsIgnoreCase("-q")) @@ -100,7 +101,7 @@ public class Command_ban extends FreedomCommand for (int z = -1; z <= 1; z++) { final Location strike_pos = new Location(targetPos.getWorld(), targetPos.getBlockX() + x, targetPos.getBlockY(), targetPos.getBlockZ() + z); - targetPos.getWorld().strikeLightning(strike_pos); + Objects.requireNonNull(targetPos.getWorld()).strikeLightning(strike_pos); } } } @@ -154,7 +155,7 @@ public class Command_ban extends FreedomCommand bcast.append(" - Reason: ").append(ChatColor.YELLOW).append(reason); } msg(sender, ChatColor.GRAY + username + " has been banned and IP is: " + StringUtils.join(ips, ", ")); - FUtil.adminAction(sender.getName(), String.format(bcast.toString()), true); + FUtil.adminAction(sender.getName(), bcast.toString(), true); } // Kick player and handle others on IP diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_banip.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_banip.java index 8d1f758f..a727c8e2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_banip.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_banip.java @@ -30,7 +30,7 @@ public class Command_banip extends FreedomCommand String ip = args[0]; - if (!FUtil.isValidIPv4(ip)) + if (FUtil.isValidIPv4(ip)) { msg(ip + " is not a valid IP address", ChatColor.RED); return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cake.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cake.java index d15785cc..908e711a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cake.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cake.java @@ -29,6 +29,7 @@ public class Command_cake extends FreedomCommand final ItemStack heldItem = new ItemStack(Material.CAKE); final ItemMeta heldItemMeta = heldItem.getItemMeta(); + assert heldItemMeta != null; heldItemMeta.setDisplayName(ChatColor.WHITE + "The " + ChatColor.DARK_GRAY + "Lie"); heldItem.setItemMeta(heldItemMeta); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cartsit.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cartsit.java index 106603f2..8d5cdc9c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cartsit.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cartsit.java @@ -1,5 +1,6 @@ package me.totalfreedom.totalfreedommod.command; +import java.util.Objects; import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -38,7 +39,7 @@ public class Command_cartsit extends FreedomCommand if (targetPlayer.isInsideVehicle()) { - targetPlayer.getVehicle().eject(); + Objects.requireNonNull(targetPlayer.getVehicle()).eject(); } else { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cmdspy.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cmdspy.java index 527f310f..4d31ca04 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cmdspy.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cmdspy.java @@ -1,7 +1,7 @@ package me.totalfreedom.totalfreedommod.command; -import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_commandlist.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_commandlist.java index d4a1fe56..d2af1cef 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_commandlist.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_commandlist.java @@ -30,16 +30,13 @@ public class Command_commandlist extends FreedomCommand PluginDescriptionFile desc = targetPlugin.getDescription(); Map> map = desc.getCommands(); - if (map != null) + for (Entry> entry : map.entrySet()) { - for (Entry> entry : map.entrySet()) - { - String command_name = entry.getKey(); - commands.add(command_name); - } + String command_name = entry.getKey(); + commands.add(command_name); } } - catch (Throwable ex) + catch (Throwable ignored) { } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cookie.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cookie.java index 156cd1cf..e404ef14 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cookie.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_cookie.java @@ -28,15 +28,6 @@ public class Command_cookie extends FreedomCommand output.append(FUtil.randomChatColor()).append(word).append(" "); } - final StringBuilder name = new StringBuilder(); - - name.append(ChatColor.DARK_RED).append("C") - .append(ChatColor.GOLD).append("o") - .append(ChatColor.YELLOW).append("o") - .append(ChatColor.DARK_GREEN).append("k") - .append(ChatColor.DARK_BLUE).append("i") - .append(ChatColor.DARK_PURPLE).append("e"); - final StringBuilder lore = new StringBuilder(); for (final String word : LORE.split(" ")) @@ -46,7 +37,14 @@ public class Command_cookie extends FreedomCommand final ItemStack heldItem = new ItemStack(Material.COOKIE); final ItemMeta heldItemMeta = heldItem.getItemMeta(); - heldItemMeta.setDisplayName(name.toString()); + String name = ChatColor.DARK_RED + "C" + + ChatColor.GOLD + "o" + + ChatColor.YELLOW + "o" + + ChatColor.DARK_GREEN + "k" + + ChatColor.DARK_BLUE + "i" + + ChatColor.DARK_PURPLE + "e"; + assert heldItemMeta != null; + heldItemMeta.setDisplayName(name); heldItemMeta.setLore(Arrays.asList(lore.toString().split("\n"))); heldItem.setItemMeta(heldItemMeta); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deafen.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deafen.java index f8c2e113..eb15c609 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deafen.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deafen.java @@ -14,8 +14,18 @@ import org.bukkit.scheduler.BukkitRunnable; public class Command_deafen extends FreedomCommand { - private static final Random random = new Random(); public static final double STEPS = 10.0; + private static final Random random = new Random(); + + private static Location randomOffset(Location a) + { + return a.clone().add(randomDoubleRange() * 5.0, randomDoubleRange() * 5.0, randomDoubleRange() * 5.0); + } + + private static Double randomDoubleRange() + { + return -1.0 + (random.nextDouble() * ((1.0 - -1.0) + 1.0)); + } @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) @@ -30,7 +40,7 @@ public class Command_deafen extends FreedomCommand @Override public void run() { - playerSender.playSound(randomOffset(playerSender.getLocation(), 5.0), Sound.values()[random.nextInt(Sound.values().length)], 100.0f, pitch); + playerSender.playSound(randomOffset(playerSender.getLocation()), Sound.values()[random.nextInt(Sound.values().length)], 100.0f, pitch); } }.runTaskLater(plugin, Math.round(20.0 * percent * 2.0)); } @@ -38,14 +48,4 @@ public class Command_deafen extends FreedomCommand return true; } - - private static Location randomOffset(Location a, double magnitude) - { - return a.clone().add(randomDoubleRange(-1.0, 1.0) * magnitude, randomDoubleRange(-1.0, 1.0) * magnitude, randomDoubleRange(-1.0, 1.0) * magnitude); - } - - private static Double randomDoubleRange(double min, double max) - { - return min + (random.nextDouble() * ((max - min) + 1.0)); - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_debugstick.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_debugstick.java index a3390ee9..ea0e0b3d 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_debugstick.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_debugstick.java @@ -21,6 +21,7 @@ public class Command_debugstick extends FreedomCommand { ItemStack itemStack = new ItemStack(Material.DEBUG_STICK); ItemMeta itemMeta = itemStack.getItemMeta(); + assert itemMeta != null; itemMeta.setDisplayName(ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "Stick of Happiness"); List lore = Arrays.asList( ChatColor.RED + "This is the most powerful stick in the game.", diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_dispfill.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_dispfill.java index 93f7df4a..f8d26d64 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_dispfill.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_dispfill.java @@ -20,6 +20,16 @@ import org.bukkit.inventory.ItemStack; public class Command_dispfill extends FreedomCommand { + private static void setDispenserContents(final Block targetBlock, final ItemStack[] items) + { + if (targetBlock.getType() == Material.DISPENSER) + { + final Inventory dispenserInv = ((Dispenser)targetBlock.getState()).getInventory(); + dispenserInv.clear(); + dispenserInv.addItem(items); + } + } + @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -54,7 +64,7 @@ public class Command_dispfill extends FreedomCommand } } - final ItemStack[] itemsArray = items.toArray(new ItemStack[items.size()]); + final ItemStack[] itemsArray = items.toArray(new ItemStack[0]); int affected = 0; final Location centerLocation = playerSender.getLocation(); @@ -88,14 +98,4 @@ public class Command_dispfill extends FreedomCommand return true; } - - private static void setDispenserContents(final Block targetBlock, final ItemStack[] items) - { - if (targetBlock.getType() == Material.DISPENSER) - { - final Inventory dispenserInv = ((Dispenser)targetBlock.getState()).getInventory(); - dispenserInv.clear(); - dispenserInv.addItem(items); - } - } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_doom.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_doom.java index ebbab3e9..92126067 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_doom.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_doom.java @@ -1,11 +1,13 @@ package me.totalfreedom.totalfreedommod.command; +import java.util.Objects; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.banning.Ban; import me.totalfreedom.totalfreedommod.config.ConfigEntry; +import me.totalfreedom.totalfreedommod.discord.Discord; import me.totalfreedom.totalfreedommod.punishments.Punishment; import me.totalfreedom.totalfreedommod.punishments.PunishmentType; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; @@ -41,7 +43,7 @@ public class Command_doom extends FreedomCommand FUtil.adminAction(sender.getName(), "Casting oblivion over " + player.getName(), true); FUtil.bcastMsg(player.getName() + " will be completely obliviated!", ChatColor.RED); - final String ip = player.getAddress().getAddress().getHostAddress().trim(); + final String ip = Objects.requireNonNull(player.getAddress()).getAddress().getHostAddress().trim(); // Remove from admin Admin admin = getAdmin(player); @@ -54,7 +56,7 @@ public class Command_doom extends FreedomCommand plugin.ptero.updateAccountStatus(admin); if (plugin.dc.enabled && ConfigEntry.DISCORD_ROLE_SYNC.getBoolean()) { - plugin.dc.syncRoles(admin, plugin.pl.getData(admin.getName()).getDiscordID()); + Discord.syncRoles(admin, plugin.pl.getData(admin.getName()).getDiscordID()); } } @@ -125,7 +127,6 @@ public class Command_doom extends FreedomCommand // generate explosion player.getWorld().createExplosion(player.getLocation(), 0F, false); - ; // kick player player.kickPlayer(ChatColor.RED + kickReason); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_eject.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_eject.java index aa67df4e..9c72b8ad 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_eject.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_eject.java @@ -19,7 +19,7 @@ public class Command_eject extends FreedomCommand public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { - List names = new ArrayList(); + List names = new ArrayList<>(); for (Entity entity : playerSender.getPassengers()) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_enchant.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_enchant.java index a88ce67a..b6d154b6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_enchant.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_enchant.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.ChatColor; @@ -19,6 +20,18 @@ import org.bukkit.inventory.ItemStack; public class Command_enchant extends FreedomCommand { + public static List stringNumberRange(int min, int max) + { + List range = new ArrayList<>(); + for (int i = min; i <= max; i++) + { + range.add(String.valueOf(i)); + } + + return range; + } + + @SuppressWarnings("deprecation") @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -27,9 +40,9 @@ public class Command_enchant extends FreedomCommand return false; } - ItemStack item = playerSender.getEquipment().getItemInMainHand(); + ItemStack item = Objects.requireNonNull(playerSender.getEquipment()).getItemInMainHand(); - if (item == null || item.getType() == Material.AIR) + if (item.getType() == Material.AIR) { msg("You have to hold an item to enchant it"); return true; @@ -99,7 +112,7 @@ public class Command_enchant extends FreedomCommand { ench = Enchantment.getByName(args[1].toUpperCase()); } - catch (Exception ex) + catch (Exception ignored) { } @@ -123,7 +136,7 @@ public class Command_enchant extends FreedomCommand { if (ConfigEntry.ALLOW_UNSAFE_ENCHANTMENTS.getBoolean()) { - level = Integer.valueOf(args[2]); + level = Integer.parseInt(args[2]); } else { @@ -158,9 +171,10 @@ public class Command_enchant extends FreedomCommand return true; } + @SuppressWarnings("deprecation") public List getAllEnchantments() { - List enchantments = new ArrayList(); + List enchantments = new ArrayList<>(); for (Enchantment enchantment : Enchantment.values()) { enchantments.add(enchantment.getName()); @@ -168,9 +182,10 @@ public class Command_enchant extends FreedomCommand return enchantments; } + @SuppressWarnings("deprecation") public List getAllEnchantments(ItemStack item) { - List enchantments = new ArrayList(); + List enchantments = new ArrayList<>(); for (Enchantment enchantment : Enchantment.values()) { if (enchantment.canEnchantItem(item)) @@ -181,9 +196,10 @@ public class Command_enchant extends FreedomCommand return enchantments; } + @SuppressWarnings("deprecation") public List getEnchantments(ItemStack item) { - List enchantments = new ArrayList(); + List enchantments = new ArrayList<>(); for (Enchantment enchantment : item.getEnchantments().keySet()) { enchantments.add(enchantment.getName()); @@ -191,17 +207,7 @@ public class Command_enchant extends FreedomCommand return enchantments; } - public static List stringNumberRange(int min, int max) - { - List range = new ArrayList(); - for (int i = min; i <= max; i++) - { - range.add(String.valueOf(i)); - } - - return range; - } - + @SuppressWarnings("deprecation") @Override public List getTabCompleteOptions(CommandSender sender, Command command, String alias, String[] args) { @@ -214,9 +220,9 @@ public class Command_enchant extends FreedomCommand { return Collections.emptyList(); } - ItemStack item = player.getEquipment().getItemInMainHand(); + ItemStack item = Objects.requireNonNull(player.getEquipment()).getItemInMainHand(); - if (item == null || item.getType() == Material.AIR) + if (item.getType() == Material.AIR) { return Collections.emptyList(); } @@ -258,7 +264,7 @@ public class Command_enchant extends FreedomCommand } else { - return Arrays.asList("[level]"); + return Collections.singletonList("[level]"); } } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_entitywipe.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_entitywipe.java index 5a80bf5f..ff2043b2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_entitywipe.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_entitywipe.java @@ -17,6 +17,29 @@ import org.bukkit.entity.Player; public class Command_entitywipe extends FreedomCommand { + public static List getAllEntities() + { + List entityTypes = new ArrayList<>(); + for (EntityType entityType : EntityType.values()) + { + if (!Groups.MOB_TYPES.contains(entityType)) + { + entityTypes.add(entityType); + } + } + return entityTypes; + } + + public static List getAllEntityNames() + { + List names = new ArrayList<>(); + for (EntityType entityType : getAllEntities()) + { + names.add(entityType.name()); + } + return names; + } + @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -75,29 +98,6 @@ public class Command_entitywipe extends FreedomCommand return true; } - public static List getAllEntities() - { - List entityTypes = new ArrayList<>(); - for (EntityType entityType : EntityType.values()) - { - if (!Groups.MOB_TYPES.contains(entityType)) - { - entityTypes.add(entityType); - } - } - return entityTypes; - } - - public static List getAllEntityNames() - { - List names = new ArrayList<>(); - for (EntityType entityType : getAllEntities()) - { - names.add(entityType.name()); - } - return names; - } - @Override public List getTabCompleteOptions(CommandSender sender, Command command, String alias, String[] args) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_expel.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_expel.java index 8e43600f..2f94d1af 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_expel.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_expel.java @@ -28,7 +28,7 @@ public class Command_expel extends FreedomCommand { radius = Math.max(1.0, Math.min(100.0, Double.parseDouble(args[0]))); } - catch (NumberFormatException ex) + catch (NumberFormatException ignored) { } } @@ -39,7 +39,7 @@ public class Command_expel extends FreedomCommand { strength = Math.max(0.0, Math.min(50.0, Double.parseDouble(args[1]))); } - catch (NumberFormatException ex) + catch (NumberFormatException ignored) { } } @@ -63,7 +63,7 @@ public class Command_expel extends FreedomCommand { inRange = targetPosVec.distanceSquared(senderPos) < (radius * radius); } - catch (IllegalArgumentException ex) + catch (IllegalArgumentException ignored) { } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_health.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_health.java index b85f6743..512acb11 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_health.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_health.java @@ -70,7 +70,7 @@ public class Command_health extends FreedomCommand return true; } - private class TFM_TickMeter + private static class TFM_TickMeter { private final AtomicInteger ticks = new AtomicInteger(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_hubworld.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_hubworld.java index 1ffc1bb1..f2742988 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_hubworld.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_hubworld.java @@ -19,11 +19,6 @@ import org.bukkit.entity.Player; public class Command_hubworld extends FreedomCommand { - private enum CommandMode - { - TELEPORT, TIME, WEATHER - } - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -66,7 +61,7 @@ public class Command_hubworld extends FreedomCommand { hubWorld = plugin.wm.hubworld.getWorld(); } - catch (Exception ex) + catch (Exception ignored) { } @@ -184,7 +179,12 @@ public class Command_hubworld extends FreedomCommand } } - private class PermissionDeniedException extends Exception + private enum CommandMode + { + TELEPORT, TIME, WEATHER + } + + private static class PermissionDeniedException extends Exception { private static final long serialVersionUID = 1L; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invis.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invis.java index 12bbff7b..01598b32 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invis.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invis.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -42,7 +41,7 @@ public class Command_invis extends FreedomCommand } } - List players = new ArrayList(); + List players = new ArrayList<>(); int clears = 0; for (Player player : server.getOnlinePlayers()) @@ -81,7 +80,7 @@ public class Command_invis extends FreedomCommand { if (args.length == 1 && plugin.al.isAdmin(sender)) { - return Arrays.asList("clear"); + return Collections.singletonList("clear"); } return Collections.emptyList(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invsee.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invsee.java index 150e8e24..5390d710 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invsee.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_invsee.java @@ -47,11 +47,6 @@ public class Command_invsee extends FreedomCommand if (args[1].equals("offhand")) { ItemStack offhand = player.getInventory().getItemInOffHand(); - if (offhand == null) - { - msg("That player has nothing in their offhand."); - return true; - } Inventory inventory = server.createInventory(null, 9, player.getName() + "'s offhand"); inventory.setItem(1, offhand); playerSender.openInventory(inventory); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_landmine.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_landmine.java index be00b73e..f51e7fb5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_landmine.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_landmine.java @@ -50,7 +50,7 @@ public class Command_landmine extends FreedomCommand { radius = Math.max(2.0, Math.min(6.0, Double.parseDouble(args[0]))); } - catch (NumberFormatException ex) + catch (NumberFormatException ignored) { } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_linkdiscord.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_linkdiscord.java index 642f34eb..40df6d93 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_linkdiscord.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_linkdiscord.java @@ -47,7 +47,7 @@ public class Command_linkdiscord extends FreedomCommand if (Discord.LINK_CODES.containsValue(data)) { - code = plugin.dc.getCode(data); + code = Discord.getCode(data); } else { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_list.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_list.java index 3c421870..fd6ef859 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_list.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_list.java @@ -2,11 +2,11 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; import java.util.List; +import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.admin.AdminList; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Displayable; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.AdminList; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import net.md_5.bungee.api.ChatColor; import org.apache.commons.lang.StringUtils; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_lockup.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_lockup.java index c6c4a992..6d31cf47 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_lockup.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_lockup.java @@ -17,7 +17,7 @@ public class Command_lockup extends FreedomCommand @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { - Boolean silent = (args[args.length - 1].equalsIgnoreCase("-q")); + boolean silent = (args[args.length - 1].equalsIgnoreCase("-q")); if (args.length == 1) { if (args[0].equalsIgnoreCase("all")) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_makeopregion.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_makeopregion.java index 32305e78..7cf2334f 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_makeopregion.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_makeopregion.java @@ -81,7 +81,7 @@ public class Command_makeopregion extends FreedomCommand region.setOwners(owners); region.setFlags(flags); - for (Flag flag : flags.keySet()) + for (Flag flag : flags.keySet()) { region.setFlag(flag.getRegionGroupFlag(), RegionGroup.MEMBERS); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_manageshop.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_manageshop.java index 64219716..5c53e3d2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_manageshop.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_manageshop.java @@ -56,7 +56,6 @@ public class Command_manageshop extends FreedomCommand { player.sendMessage(ChatColor.GREEN + sender.getName() + " gave you " + amount + " coins. Your new balance is " + playerData.getCoins()); } - return true; } else { @@ -68,8 +67,8 @@ public class Command_manageshop extends FreedomCommand player.sendMessage(ChatColor.GREEN + sender.getName() + " gave you " + amount + " coins. Your new balance is " + playerData.getCoins()); } msg("Successfully added " + amount + " coins to all online players.", ChatColor.GREEN); - return true; } + return true; } catch (NumberFormatException ex) { @@ -100,7 +99,6 @@ public class Command_manageshop extends FreedomCommand { player.sendMessage(ChatColor.RED + sender.getName() + " took " + amount + " coins from you. Your new balance is " + playerData.getCoins()); } - return true; } else { @@ -116,8 +114,8 @@ public class Command_manageshop extends FreedomCommand player.sendMessage(ChatColor.RED + sender.getName() + " took " + amount + " coins from you. Your new balance is " + playerData.getCoins()); } msg("Successfully took " + amount + " coins from all online players.", ChatColor.GREEN); - return true; } + return true; } catch (NumberFormatException ex) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_manuallyverify.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_manuallyverify.java index 27861817..f79473a2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_manuallyverify.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_manuallyverify.java @@ -1,8 +1,8 @@ package me.totalfreedom.totalfreedommod.command; +import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; -import me.totalfreedom.totalfreedommod.config.ConfigEntry; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_masterbuilderworld.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_masterbuilderworld.java index dd89780f..7542386e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_masterbuilderworld.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_masterbuilderworld.java @@ -19,11 +19,6 @@ import org.bukkit.entity.Player; public class Command_masterbuilderworld extends FreedomCommand { - private enum CommandMode - { - TELEPORT, TIME, WEATHER - } - @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -66,7 +61,7 @@ public class Command_masterbuilderworld extends FreedomCommand { masterBuilderWorld = plugin.wm.masterBuilderWorld.getWorld(); } - catch (Exception ex) + catch (Exception ignored) { } @@ -184,7 +179,12 @@ public class Command_masterbuilderworld extends FreedomCommand } } - private class PermissionDeniedException extends Exception + private enum CommandMode + { + TELEPORT, TIME, WEATHER + } + + private static class PermissionDeniedException extends Exception { private static final long serialVersionUID = 1L; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mbconfig.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mbconfig.java index f0d597cb..b1231416 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mbconfig.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mbconfig.java @@ -101,7 +101,7 @@ public class Command_mbconfig extends FreedomCommand return false; } - if (!plugin.pl.canManageMasterBuilders(sender.getName())) + if (plugin.pl.canManageMasterBuilders(sender.getName())) { return noPerms(); } @@ -157,7 +157,7 @@ public class Command_mbconfig extends FreedomCommand return false; } - if (!plugin.pl.canManageMasterBuilders(sender.getName())) + if (plugin.pl.canManageMasterBuilders(sender.getName())) { return noPerms(); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_moblimiter.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_moblimiter.java index 47fb93ee..d8884d69 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_moblimiter.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_moblimiter.java @@ -57,7 +57,7 @@ public class Command_moblimiter extends FreedomCommand { ConfigEntry.MOB_LIMITER_MAX.setInteger(Math.max(0, Math.min(2000, Integer.parseInt(args[1])))); } - catch (NumberFormatException nfex) + catch (NumberFormatException ignored) { } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mobpurge.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mobpurge.java index 26071f83..7d726cbd 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mobpurge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mobpurge.java @@ -17,6 +17,16 @@ import org.bukkit.entity.Player; public class Command_mobpurge extends FreedomCommand { + public static List getAllMobNames() + { + List names = new ArrayList<>(); + for (EntityType entityType : Groups.MOB_TYPES) + { + names.add(entityType.name()); + } + return names; + } + @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -52,16 +62,6 @@ public class Command_mobpurge extends FreedomCommand return true; } - public static List getAllMobNames() - { - List names = new ArrayList<>(); - for (EntityType entityType : Groups.MOB_TYPES) - { - names.add(entityType.name()); - } - return names; - } - @Override public List getTabCompleteOptions(CommandSender sender, Command command, String alias, String[] args) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_modifyitem.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_modifyitem.java index 6e2374bd..ed9273cf 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_modifyitem.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_modifyitem.java @@ -24,6 +24,7 @@ import org.bukkit.potion.PotionEffectType; public class Command_modifyitem extends FreedomCommand { + @SuppressWarnings("deprecation") @Override public boolean run(final CommandSender sender, final Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -52,6 +53,7 @@ public class Command_modifyitem extends FreedomCommand } ItemMeta meta = item.getItemMeta(); + assert meta != null; switch (args[0]) { case "name": @@ -188,6 +190,7 @@ public class Command_modifyitem extends FreedomCommand }); cmpnd.setString("Slot", "mainhand"); modifiers.add(cmpnd); + assert compound != null; compound.set("AttributeModifiers", modifiers); nmsStack.setTag(compound); item = CraftItemStack.asBukkitCopy(nmsStack); @@ -237,17 +240,6 @@ public class Command_modifyitem extends FreedomCommand this.attribute = attribute; } - public String getAttribute() - { - return attribute; - } - - @Override - public String toString() - { - return name; - } - public static Attribute getByName(String name) { for (Attribute attr : Attribute.values()) @@ -259,5 +251,16 @@ public class Command_modifyitem extends FreedomCommand } return null; } + + public String getAttribute() + { + return attribute; + } + + @Override + public String toString() + { + return name; + } } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mp44.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mp44.java index 6f34ab27..a5c003be 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mp44.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_mp44.java @@ -1,5 +1,6 @@ package me.totalfreedom.totalfreedommod.command; +import java.util.Objects; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -38,7 +39,7 @@ public class Command_mp44 extends FreedomCommand msg("mp44 is ARMED! Left click with gunpowder to start firing, left click again to quit.", ChatColor.GREEN); msg("Type /mp44 sling to disable. -by Madgeek1450", ChatColor.GREEN); - playerSender.getEquipment().setItemInMainHand(new ItemStack(Material.GUNPOWDER, 1)); + Objects.requireNonNull(playerSender.getEquipment()).setItemInMainHand(new ItemStack(Material.GUNPOWDER, 1)); } else { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_myadmin.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_myadmin.java index b8148bc9..9a8a0137 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_myadmin.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_myadmin.java @@ -4,11 +4,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.discord.Discord; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickclean.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickclean.java index e5fc24f7..1ba43927 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickclean.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickclean.java @@ -20,7 +20,7 @@ import org.bukkit.entity.Player; @CommandParameters(description = "Essentials Interface Command - Remove illegal chatcodes from nicknames of one or all players on server.", usage = "/ [player]", aliases = "nc") public class Command_nickclean extends FreedomCommand { - private Map colorCodes = new HashMap() + private final Map colorCodes = new HashMap() {{ put("&0", Color.BLACK); put("&1", Color.BLUE); @@ -81,7 +81,7 @@ public class Command_nickclean extends FreedomCommand for (String split : nickName.split("§x")) { List colors = new ArrayList<>(); - String hexColorSub = null; + String hexColorSub; if (split.length() >= 12 && split.contains("§")) { hexColorSub = split.substring(0, 12); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickfilter.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickfilter.java index 16d5375a..6a67581e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickfilter.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_nickfilter.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -20,6 +19,42 @@ import org.bukkit.entity.Player; public class Command_nickfilter extends FreedomCommand { + private static Player getPlayerByDisplayName(String needle) + { + needle = needle.toLowerCase().trim(); + + for (Player player : Bukkit.getOnlinePlayers()) + { + if (player.getDisplayName().toLowerCase().trim().contains(needle)) + { + return player; + } + } + + return null; + } + + private static Player getPlayerByDisplayNameAlt(String needle) + { + needle = needle.toLowerCase().trim(); + + Integer minEditDistance = null; + Player minEditMatch = null; + + for (Player player : Bukkit.getOnlinePlayers()) + { + String haystack = player.getDisplayName().toLowerCase().trim(); + int editDistance = StringUtils.getLevenshteinDistance(needle, haystack.toLowerCase()); + if (minEditDistance == null || minEditDistance > editDistance) + { + minEditDistance = editDistance; + minEditMatch = player; + } + } + + return minEditMatch; + } + @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -29,8 +64,7 @@ public class Command_nickfilter extends FreedomCommand if (args.length >= 1) { - final List argsList = Arrays.asList(args); - for (String arg : argsList) + for (String arg : args) { Player player = null; @@ -84,40 +118,4 @@ public class Command_nickfilter extends FreedomCommand return true; } - - private static Player getPlayerByDisplayName(String needle) - { - needle = needle.toLowerCase().trim(); - - for (Player player : Bukkit.getOnlinePlayers()) - { - if (player.getDisplayName().toLowerCase().trim().contains(needle)) - { - return player; - } - } - - return null; - } - - private static Player getPlayerByDisplayNameAlt(String needle) - { - needle = needle.toLowerCase().trim(); - - Integer minEditDistance = null; - Player minEditMatch = null; - - for (Player player : Bukkit.getOnlinePlayers()) - { - String haystack = player.getDisplayName().toLowerCase().trim(); - int editDistance = StringUtils.getLevenshteinDistance(needle, haystack.toLowerCase()); - if (minEditDistance == null || minEditDistance.intValue() > editDistance) - { - minEditDistance = editDistance; - minEditMatch = player; - } - } - - return minEditMatch; - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_notes.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_notes.java index fe01b6b0..8a4754b2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_notes.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_notes.java @@ -51,12 +51,12 @@ public class Command_notes extends FreedomCommand case "list": { final StringBuilder noteList = new StringBuilder(); - noteList.append(ChatColor.GREEN + "Player notes for " + playerData.getName() + ":"); + noteList.append(ChatColor.GREEN).append("Player notes for ").append(playerData.getName()).append(":"); int id = 1; for (String note : playerData.getNotes()) { String noteLine = id + ". " + note; - noteList.append("\n" + ChatColor.GOLD + noteLine); + noteList.append("\n").append(ChatColor.GOLD).append(noteLine); id++; } msg(noteList.toString()); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ops.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ops.java index 246d66b4..70686735 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ops.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ops.java @@ -1,5 +1,6 @@ package me.totalfreedom.totalfreedommod.command; +import java.util.Objects; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.OfflinePlayer; @@ -54,7 +55,7 @@ public class Command_ops extends FreedomCommand player.setOp(false); if (player.isOnline()) { - msg(player.getPlayer(), FreedomCommand.YOU_ARE_NOT_OP); + msg(Objects.requireNonNull(player.getPlayer()), FreedomCommand.YOU_ARE_NOT_OP); } } return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_panel.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_panel.java index 88042ec8..364d58ff 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_panel.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_panel.java @@ -4,9 +4,9 @@ import com.google.common.base.Strings; import java.util.Arrays; import java.util.Collections; import java.util.List; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.ChatColor; import org.bukkit.command.Command; @@ -98,27 +98,6 @@ public class Command_panel extends FreedomCommand msg("Successfully deleted your Pterodactyl account.", ChatColor.GREEN); return true; } - /*else if (args[0].equals("resetpassword")) - { - Admin admin = getAdmin(playerSender); - - if (admin.getAmpUsername() == null) - { - msg("You do not have a Pterodactyl account.", ChatColor.RED); - return true; - } - - msg("Resetting your password...", ChatColor.GREEN); - - String id = admin.getPteroID(); - String password = FUtil.randomString(30); - plugin.ptero.setPassword(id, password); - plugin.dc.sendPteroInfo(playerData, null, password); - - msg("Successfully reset your AMP account password. Check your DMs from " + plugin.dc.formatBotTag() + " on discord to get your credentials.", ChatColor.GREEN); - return true; - }*/ - return false; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_playerverification.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_playerverification.java index e649fd84..0bfe476a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_playerverification.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_playerverification.java @@ -22,8 +22,7 @@ public class Command_playerverification extends FreedomCommand { PlayerData target = plugin.pl.getData(playerSender); boolean verificationEnabled = ConfigEntry.DISCORD_VERIFICATION.getBoolean(); - List ips = new ArrayList<>(); - ips.addAll(target.getIps()); + List ips = new ArrayList<>(target.getIps()); if (verificationEnabled) { @@ -49,15 +48,7 @@ public class Command_playerverification extends FreedomCommand } else if (args[0].equalsIgnoreCase("clearip")) { - if (args.length < 2) - { - return false; - } - target.removeIp(args[1]); - msg("Removed" + args[1] + " from your list of IPs"); - plugin.pl.save(target); - plugin.pl.syncIps(target); - return true; + return false; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_playtime.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_playtime.java index fc8da0e6..c921275d 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_playtime.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_playtime.java @@ -3,8 +3,8 @@ package me.totalfreedom.totalfreedommod.command; import java.time.Instant; import java.util.Date; import java.util.List; -import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.admin.ActivityLogEntry; +import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -45,16 +45,32 @@ public class Command_playtime extends FreedomCommand long cminutes = duration / (60 * 1000) % 60; long chours = duration / (60 * 60 * 1000); StringBuilder sb = new StringBuilder() - .append("Playtime - " + sender.getName() + "\n") - .append("Current Session: " + chours + " hours, " + cminutes + " minutes, and " + cseconds + " seconds" + "\n") - .append("Overall: " + hours + " hours, " + minutes + " minutes, and " + seconds + " seconds" + "\n"); + .append("Playtime - ") + .append(sender.getName()) + .append("\n") + .append("Current Session: ") + .append(chours) + .append(" hours, ") + .append(cminutes) + .append(" minutes, and ") + .append(cseconds) + .append(" seconds") + .append("\n") + .append("Overall: ") + .append(hours) + .append(" hours, ") + .append(minutes) + .append(" minutes, and ") + .append(seconds) + .append(" seconds") + .append("\n"); List durations = entry.getDurations(); if (durations.size() >= 3) { sb.append("Recent Sessions:"); for (int i = 0; i < 3; i++) { - sb.append("\n" + " - " + durations.get((durations.size() - 1) - i)); + sb.append("\n" + " - ").append(durations.get((durations.size() - 1) - i)); } } msg(sb.toString()); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_plugincontrol.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_plugincontrol.java index b49f4b8c..b86ec80a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_plugincontrol.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_plugincontrol.java @@ -38,7 +38,7 @@ public class Command_plugincontrol extends FreedomCommand { final String version = serverPlugin.getDescription().getVersion(); msg(ChatColor.GRAY + "- " + (serverPlugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED) + serverPlugin.getName() - + ChatColor.GOLD + (version != null && !version.isEmpty() ? " v" + version : "") + " by " + + ChatColor.GOLD + (!version.isEmpty() ? " v" + version : "") + " by " + StringUtils.join(serverPlugin.getDescription().getAuthors(), ", ")); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potion.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potion.java index 999455a9..dd508c54 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potion.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potion.java @@ -22,6 +22,7 @@ import org.bukkit.potion.PotionEffectType; public class Command_potion extends FreedomCommand { + @SuppressWarnings("deprecation") @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -178,8 +179,7 @@ public class Command_potion extends FreedomCommand switch (args.length) { case 1: - List arguments = new ArrayList<>(); - arguments.addAll(Arrays.asList("list", "clear", "add")); + List arguments = new ArrayList<>(Arrays.asList("list", "clear", "add")); if (plugin.al.isAdmin(sender)) { arguments.add("clearall"); @@ -203,14 +203,14 @@ public class Command_potion extends FreedomCommand case 3: if (args[0].equals("add")) { - return Arrays.asList(""); + return Collections.singletonList(""); } break; case 4: if (args[0].equals("add")) { - return Arrays.asList(""); + return Collections.singletonList(""); } break; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potionspy.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potionspy.java index 0de7c639..277b6ac3 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potionspy.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_potionspy.java @@ -4,8 +4,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; -import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; import org.apache.commons.lang.math.NumberUtils; import org.bukkit.Bukkit; @@ -19,11 +19,6 @@ import org.bukkit.entity.ThrownPotion; @CommandParameters(description = "Allows admins to see potions that are thrown.", usage = "/ | history [player] ", aliases = "potspy") public class Command_potionspy extends FreedomCommand { - private String titleText = "&8&m------------------&r &ePotionSpy &8&m------------------&r"; - private String validPageText = "Please specify a valid page number between 1 and %s."; - private String noPlayerRecord = "That player has not thrown any potions yet."; - private String splashedText = "&r%s splashed a potion at &eX: %s Y: %s Z: %s&r\nin the world '&e%s&r' about &e%s &rago%s."; - private String bottomText = "&8&m--------------------&r &e%s / %s &8&m--------------------&r"; @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) @@ -37,6 +32,11 @@ public class Command_potionspy extends FreedomCommand } else { + String titleText = "&8&m------------------&r &ePotionSpy &8&m------------------&r"; + String validPageText = "Please specify a valid page number between 1 and %s."; + String noPlayerRecord = "That player has not thrown any potions yet."; + String splashedText = "&r%s splashed a potion at &eX: %s Y: %s Z: %s&r\nin the world '&e%s&r' about &e%s &rago%s."; + String bottomText = "&8&m--------------------&r &e%s / %s &8&m--------------------&r"; switch (args[0].toLowerCase()) { case "enable": @@ -59,8 +59,7 @@ public class Command_potionspy extends FreedomCommand return true; } - List> thrownPotions = new ArrayList<>(); - thrownPotions.addAll(plugin.mo.getPlayerThrownPotions(player)); // Make a copy of the list to avoid modifying the original. + List> thrownPotions = new ArrayList<>(plugin.mo.getPlayerThrownPotions(player)); // Make a copy of the list to avoid modifying the original. List potionThrowNotifications = new ArrayList<>(); int lastPage = (int)Math.ceil(thrownPotions.size() / 5.0); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_premium.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_premium.java index b883f3c3..4fdec9cf 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_premium.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_premium.java @@ -47,7 +47,7 @@ public class Command_premium extends FreedomCommand final URL getUrl = new URL("https://api.ashcon.app/mojang/v2/user/" + name); final HttpURLConnection urlConnection = (HttpURLConnection)getUrl.openConnection(); urlConnection.setRequestProperty("User-Agent", ""); - String message = ""; + String message; /*old code BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))) //message = (!"PREMIUM".equalsIgnoreCase(in.readLine()) ? ChatColor.RED + "No" : ChatColor.DARK_GREEN + "Yes"); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_releaseparrots.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_releaseparrots.java index 93a3414a..16a25106 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_releaseparrots.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_releaseparrots.java @@ -12,6 +12,7 @@ import org.bukkit.entity.Player; public class Command_releaseparrots extends FreedomCommand { + @SuppressWarnings("deprecation") @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ro.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ro.java index 9a8922c6..e51dc061 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ro.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_ro.java @@ -22,6 +22,46 @@ import org.bukkit.entity.Player; public class Command_ro extends FreedomCommand { + public static int replaceBlocks(Location center, Material fromMaterial, Material toMaterial, int radius) + { + int affected = 0; + + Block centerBlock = center.getBlock(); + for (int xOffset = -radius; xOffset <= radius; xOffset++) + { + for (int yOffset = -radius; yOffset <= radius; yOffset++) + { + for (int zOffset = -radius; zOffset <= radius; zOffset++) + { + Block block = centerBlock.getRelative(xOffset, yOffset, zOffset); + BlockData data = block.getBlockData(); + if (block.getLocation().distanceSquared(center) < (radius * radius)) + { + if (fromMaterial.equals(Material.WATER) && data instanceof Waterlogged) + { + Waterlogged waterloggedData = (Waterlogged)data; + if (waterloggedData.isWaterlogged()) + { + waterloggedData.setWaterlogged(false); + block.setBlockData(waterloggedData); + affected++; + continue; + } + block.setType(toMaterial); + affected++; + } + else if (block.getType().equals(fromMaterial)) + { + block.setType(toMaterial); + affected++; + } + } + } + } + } + return affected; + } + @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -97,7 +137,7 @@ public class Command_ro extends FreedomCommand { adminWorld = plugin.wm.adminworld.getWorld(); } - catch (Exception ex) + catch (Exception ignored) { } @@ -134,47 +174,4 @@ public class Command_ro extends FreedomCommand FUtil.adminAction(sender.getName(), "Remove complete! " + affected + " blocks removed.", false); return true; } - - public static int replaceBlocks(Location center, Material fromMaterial, Material toMaterial, int radius) - { - int affected = 0; - - Block centerBlock = center.getBlock(); - for (int xOffset = -radius; xOffset <= radius; xOffset++) - { - for (int yOffset = -radius; yOffset <= radius; yOffset++) - { - for (int zOffset = -radius; zOffset <= radius; zOffset++) - { - Block block = centerBlock.getRelative(xOffset, yOffset, zOffset); - BlockData data = block.getBlockData(); - if (block.getLocation().distanceSquared(center) < (radius * radius)) - { - if (fromMaterial.equals(Material.WATER) && data instanceof Waterlogged) - { - if (data instanceof Waterlogged) - { - Waterlogged waterloggedData = (Waterlogged)data; - if (waterloggedData.isWaterlogged()) - { - waterloggedData.setWaterlogged(false); - block.setBlockData(waterloggedData); - affected++; - continue; - } - } - block.setType(toMaterial); - affected++; - } - else if (block.getType().equals(fromMaterial)) - { - block.setType(toMaterial); - affected++; - } - } - } - } - } - return affected; - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_rock.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_rock.java index 5a151506..fed36ec4 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_rock.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_rock.java @@ -22,6 +22,7 @@ public class Command_rock extends FreedomCommand { final ItemStack heldItem = new ItemStack(Material.STONE); final ItemMeta heldItemMeta = heldItem.getItemMeta(); + assert heldItemMeta != null; heldItemMeta.setDisplayName(ChatColor.BLUE + "Rock"); heldItem.setItemMeta(heldItemMeta); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_saconfig.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_saconfig.java index 20d85c05..28517d51 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_saconfig.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_saconfig.java @@ -5,11 +5,11 @@ import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.discord.Discord; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; @@ -176,7 +176,7 @@ public class Command_saconfig extends FreedomCommand } // Find the old admin entry - String name = player != null ? player.getName() : args[1]; + String name = player.getName(); Admin admin = null; for (Admin loopAdmin : plugin.al.getAllAdmins()) { @@ -195,33 +195,24 @@ public class Command_saconfig extends FreedomCommand if (admin == null) // New admin { - if (player == null) - { - msg(FreedomCommand.PLAYER_NOT_FOUND); - return true; - } FUtil.adminAction(sender.getName(), "Adding " + player.getName() + " to the admin list", true); admin = new Admin(player); plugin.al.addAdmin(admin); plugin.rm.updateDisplay(player); - plugin.ptero.updateAccountStatus(admin); } else // Existing admin { FUtil.adminAction(sender.getName(), "Re-adding " + player.getName() + " to the admin list", true); - if (player != null) + String oldName = admin.getName(); + if (!oldName.equals(player.getName())) { - String oldName = admin.getName(); - if (oldName != player.getName()) - { - admin.setName(player.getName()); - plugin.sql.updateAdminName(oldName, admin.getName()); - } - admin.addIp(FUtil.getIp(player)); + admin.setName(player.getName()); + plugin.sql.updateAdminName(oldName, admin.getName()); } + admin.addIp(FUtil.getIp(player)); admin.setActive(true); admin.setLastLogin(new Date()); @@ -234,32 +225,26 @@ public class Command_saconfig extends FreedomCommand plugin.al.save(admin); plugin.al.updateTables(); - if (player != null) - { - plugin.rm.updateDisplay(player); - } + plugin.rm.updateDisplay(player); if (plugin.dc.enabled && ConfigEntry.DISCORD_ROLE_SYNC.getBoolean()) { - plugin.dc.syncRoles(admin, plugin.pl.getData(player).getDiscordID()); + Discord.syncRoles(admin, plugin.pl.getData(player).getDiscordID()); } - plugin.ptero.updateAccountStatus(admin); + } + plugin.ptero.updateAccountStatus(admin); + + final FPlayer fPlayer = plugin.pl.getPlayer(player); + if (fPlayer.getFreezeData().isFrozen()) + { + fPlayer.getFreezeData().setFrozen(false); + msg(player, "You have been unfrozen."); } - if (player != null) + if (!player.isOp()) { - final FPlayer fPlayer = plugin.pl.getPlayer(player); - if (fPlayer.getFreezeData().isFrozen()) - { - fPlayer.getFreezeData().setFrozen(false); - msg(player, "You have been unfrozen."); - } - - if (!player.isOp()) - { - player.setOp(true); - player.sendMessage(YOU_ARE_OP); - } + player.setOp(true); + player.sendMessage(YOU_ARE_OP); } return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setlever.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setlever.java index d32a2553..dfec52c8 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setlever.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setlever.java @@ -7,10 +7,11 @@ import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.type.Switch; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.bukkit.material.Lever; @CommandPermissions(level = Rank.NON_OP, source = SourceType.BOTH) @CommandParameters(description = "Set the on/off state of the lever at position x, y, z in world 'worldname'.", usage = "/ ") @@ -65,9 +66,11 @@ public class Command_setlever extends FreedomCommand if (targetBlock.getType() == Material.LEVER) { BlockState state = targetBlock.getState(); - Lever lever = (Lever)state.getData(); - lever.setPowered(leverOn); - state.setData(lever); + BlockData data = state.getBlockData(); + Switch caster = (Switch)data; + + caster.setPowered(leverOn); + state.setBlockData(data); state.update(); } else diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setplayerlimit.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setplayerlimit.java index bbc22bd0..f518bd86 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setplayerlimit.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_setplayerlimit.java @@ -59,6 +59,7 @@ public class Command_setplayerlimit extends FreedomCommand } if (success) { + assert player != null; FUtil.adminAction(sender.getName(), "Setting " + player.getName() + "'s WorldEdit block modification limit to " + amount + ".", true); } return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_smite.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_smite.java index 39726bbe..708d36bf 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_smite.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_smite.java @@ -19,51 +19,6 @@ import org.bukkit.entity.Player; public class Command_smite extends FreedomCommand { - @Override - public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) - { - if (args.length < 1) - { - return false; - } - - String reason = null; - boolean silent = false; - if (args.length >= 2) - { - if (args[args.length - 1].equalsIgnoreCase("-q")) - { - if (args[args.length - 1].equalsIgnoreCase("-q")) - { - silent = true; - } - - if (args.length >= 3) - { - reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length - 1), " "); - } - } - else - { - reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); - } - } - - final Player player = getPlayer(args[0]); - - if (player == null) - { - msg(FreedomCommand.PLAYER_NOT_FOUND); - return true; - } - - smite(sender, player, reason, silent); - - plugin.pul.logPunishment(new Punishment(player.getName(), FUtil.getIp(player), sender.getName(), PunishmentType.SMITE, reason)); - - return true; - } - public static void smite(CommandSender sender, Player player) { smite(sender, player, null, false); @@ -122,4 +77,49 @@ public class Command_smite extends FreedomCommand player.sendTitle(ChatColor.RED + "You've been smitten.", ChatColor.YELLOW + "Reason: " + reason, 20, 100, 60); } } + + @Override + public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) + { + if (args.length < 1) + { + return false; + } + + String reason = null; + boolean silent = false; + if (args.length >= 2) + { + if (args[args.length - 1].equalsIgnoreCase("-q")) + { + if (args[args.length - 1].equalsIgnoreCase("-q")) + { + silent = true; + } + + if (args.length >= 3) + { + reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length - 1), " "); + } + } + else + { + reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); + } + } + + final Player player = getPlayer(args[0]); + + if (player == null) + { + msg(FreedomCommand.PLAYER_NOT_FOUND); + return true; + } + + smite(sender, player, reason, silent); + + plugin.pul.logPunishment(new Punishment(player.getName(), FUtil.getIp(player), sender.getName(), PunishmentType.SMITE, reason)); + + return true; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_spawnmob.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_spawnmob.java index cf9f0866..5306ceda 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_spawnmob.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_spawnmob.java @@ -1,13 +1,11 @@ package me.totalfreedom.totalfreedommod.command; import java.util.List; -import java.util.Set; import me.totalfreedom.totalfreedommod.rank.Rank; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.EnumUtils; import org.bukkit.ChatColor; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tban.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tban.java index 62952366..c4c4c62f 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tban.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tban.java @@ -2,6 +2,7 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.banning.Ban; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.punishments.Punishment; @@ -40,12 +41,12 @@ public class Command_tban extends FreedomCommand } final String username; - final List ips = new ArrayList<>(); final Player player = getPlayer(args[0]); + final PlayerData entry; if (player == null) { - final PlayerData entry = plugin.pl.getData(args[0]); + entry = plugin.pl.getData(args[0]); if (entry == null) { @@ -54,14 +55,13 @@ public class Command_tban extends FreedomCommand } username = entry.getName(); - ips.addAll(entry.getIps()); } else { - final PlayerData entry = plugin.pl.getData(player); + entry = plugin.pl.getData(player); username = player.getName(); - ips.addAll(entry.getIps()); } + final List ips = new ArrayList<>(entry.getIps()); String reason = null; if (args.length > 1) @@ -84,7 +84,7 @@ public class Command_tban extends FreedomCommand for (int z = -1; z <= 1; z++) { final Location strike_pos = new Location(targetPos.getWorld(), targetPos.getBlockX() + x, targetPos.getBlockY(), targetPos.getBlockZ() + z); - targetPos.getWorld().strikeLightning(strike_pos); + Objects.requireNonNull(targetPos.getWorld()).strikeLightning(strike_pos); } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tempban.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tempban.java index 7ae87d6b..0462cdee 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tempban.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tempban.java @@ -4,6 +4,7 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.banning.Ban; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.punishments.Punishment; @@ -22,7 +23,7 @@ import org.bukkit.entity.Player; public class Command_tempban extends FreedomCommand { - private static final SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd \'at\' HH:mm:ss z"); + private static final SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) @@ -44,12 +45,12 @@ public class Command_tempban extends FreedomCommand } final String username; - final List ips = new ArrayList<>(); final Player player = getPlayer(args[0]); + final PlayerData entry; if (player == null) { - final PlayerData entry = plugin.pl.getData(args[0]); + entry = plugin.pl.getData(args[0]); if (entry == null) { @@ -58,15 +59,15 @@ public class Command_tempban extends FreedomCommand } username = entry.getName(); - ips.addAll(entry.getIps()); } else { - final PlayerData entry = plugin.pl.getData(player); + entry = plugin.pl.getData(player); username = player.getName(); - ips.addAll(entry.getIps()); } + final List ips = new ArrayList<>(entry.getIps()); + assert player != null; final StringBuilder message = new StringBuilder("Temporarily banned " + player.getName()); Date expires = FUtil.parseDateOffset("30m"); @@ -93,7 +94,7 @@ public class Command_tempban extends FreedomCommand for (int z = -1; z <= 1; z++) { final Location strike_pos = new Location(targetPos.getWorld(), targetPos.getBlockX() + x, targetPos.getBlockY(), targetPos.getBlockZ() + z); - targetPos.getWorld().strikeLightningEffect(strike_pos); + Objects.requireNonNull(targetPos.getWorld()).strikeLightningEffect(strike_pos); } } @@ -107,14 +108,7 @@ public class Command_tempban extends FreedomCommand Ban ban; - if (player != null) - { - ban = Ban.forPlayer(player, sender, null, reason); - } - else - { - ban = Ban.forPlayerName(username, sender, null, reason); - } + ban = Ban.forPlayer(player, sender, null, reason); for (String ip : ips) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_toggle.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_toggle.java index c29a14c0..2233ec62 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_toggle.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_toggle.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import me.totalfreedom.totalfreedommod.GameRuleHandler; +import me.totalfreedom.totalfreedommod.LoginProcess; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; @@ -109,8 +110,8 @@ public class Command_toggle extends FreedomCommand case "lockdown": { - boolean active = !plugin.lp.isLockdownEnabled(); - plugin.lp.setLockdownEnabled(active); + boolean active = !LoginProcess.isLockdownEnabled(); + LoginProcess.setLockdownEnabled(active); FUtil.adminAction(sender.getName(), (active ? "A" : "De-a") + "ctivating server lockdown", true); break; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tossmob.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tossmob.java index aea33cf8..28470eb6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tossmob.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_tossmob.java @@ -2,6 +2,7 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -21,6 +22,16 @@ import org.bukkit.inventory.ItemStack; public class Command_tossmob extends FreedomCommand { + public static List getAllMobNames() + { + List names = new ArrayList<>(); + for (EntityType entityType : Groups.MOB_TYPES) + { + names.add(entityType.name()); + } + return names; + } + @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -38,41 +49,38 @@ public class Command_tossmob extends FreedomCommand FPlayer playerData = plugin.pl.getPlayer(playerSender); EntityType type = null; - if (args.length >= 1) + if (args[0].equalsIgnoreCase("off")) { - if (args[0].equalsIgnoreCase("off")) - { - playerData.disableMobThrower(); - msg("Turned off.", ChatColor.GREEN); - return true; - } + playerData.disableMobThrower(); + msg("Turned off.", ChatColor.GREEN); + return true; + } - if (args[0].equalsIgnoreCase("list")) - { - msg("Supported mobs: " + getAllMobNames(), ChatColor.GREEN); - return true; - } + if (args[0].equalsIgnoreCase("list")) + { + msg("Supported mobs: " + getAllMobNames(), ChatColor.GREEN); + return true; + } - for (EntityType loop : EntityType.values()) + for (EntityType loop : EntityType.values()) + { + if (loop != null && loop.name().equalsIgnoreCase(args[0])) { - if (loop != null && loop.name().equalsIgnoreCase(args[0])) - { - type = loop; - break; - } + type = loop; + break; } + } - if (type == null) - { - msg("Unknown entity type: " + args[0], ChatColor.RED); - return true; - } + if (type == null) + { + msg("Unknown entity type: " + args[0], ChatColor.RED); + return true; + } - if (!Groups.MOB_TYPES.contains(type)) - { - msg(FUtil.formatName(type.name()) + " is an entity, however it is not a mob.", ChatColor.RED); - return true; - } + if (!Groups.MOB_TYPES.contains(type)) + { + msg(FUtil.formatName(type.name()) + " is an entity, however it is not a mob.", ChatColor.RED); + return true; } double speed = 1.0; @@ -103,17 +111,7 @@ public class Command_tossmob extends FreedomCommand msg("Right click while holding a " + Material.BONE.toString() + " to throw mobs!", ChatColor.GREEN); msg("Type '/tossmob off' to disable. -By Madgeek1450", ChatColor.GREEN); - playerSender.getEquipment().setItemInMainHand(new ItemStack(Material.BONE, 1)); + Objects.requireNonNull(playerSender.getEquipment()).setItemInMainHand(new ItemStack(Material.BONE, 1)); return true; } - - public static List getAllMobNames() - { - List names = new ArrayList<>(); - for (EntityType entityType : Groups.MOB_TYPES) - { - names.add(entityType.name()); - } - return names; - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_unban.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_unban.java index d1327381..b6ca9452 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_unban.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_unban.java @@ -22,7 +22,6 @@ public class Command_unban extends FreedomCommand if (args.length > 0) { String username; - final List ips = new ArrayList<>(); final PlayerData entry = plugin.pl.getData(args[0]); if (entry == null) @@ -32,7 +31,7 @@ public class Command_unban extends FreedomCommand } username = entry.getName(); - ips.addAll(entry.getIps()); + final List ips = new ArrayList<>(entry.getIps()); FUtil.adminAction(sender.getName(), "Unbanning " + username, true); msg(username + " has been unbanned along with the following IPs: " + StringUtils.join(ips, ", ")); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_unbanip.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_unbanip.java index 21122d84..03cbaef7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_unbanip.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_unbanip.java @@ -25,7 +25,7 @@ public class Command_unbanip extends FreedomCommand String ip = args[0]; - if (!FUtil.isValidIPv4(ip)) + if (FUtil.isValidIPv4(ip)) { msg(ip + " is not a valid IP address", ChatColor.RED); return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_vanish.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_vanish.java index b14b0b68..68ce1b41 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_vanish.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_vanish.java @@ -1,5 +1,6 @@ package me.totalfreedom.totalfreedommod.command; +import me.totalfreedom.totalfreedommod.admin.AdminList; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Displayable; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -66,7 +67,7 @@ public class Command_vanish extends FreedomCommand } plugin.esb.setVanished(playerSender.getName(), false); playerSender.setPlayerListName(StringUtils.substring(displayName, 0, 16)); - plugin.al.vanished.remove(playerSender.getName()); + AdminList.vanished.remove(playerSender.getName()); } else { @@ -105,7 +106,7 @@ public class Command_vanish extends FreedomCommand } plugin.esb.setVanished(playerSender.getName(), true); - plugin.al.vanished.add(playerSender.getName()); + AdminList.vanished.add(playerSender.getName()); } return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_verify.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_verify.java index e23a4ad5..fb33dca6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_verify.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_verify.java @@ -1,6 +1,7 @@ package me.totalfreedom.totalfreedommod.command; import me.totalfreedom.totalfreedommod.config.ConfigEntry; +import me.totalfreedom.totalfreedommod.discord.Discord; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -69,14 +70,14 @@ public class Command_verify extends FreedomCommand PlayerData mapPlayer = plugin.dc.getVerificationCodes().get(code); if (mapPlayer == null) { - if (!playerData.getBackupCodes().contains(plugin.dc.getMD5(code))) + if (!playerData.getBackupCodes().contains(Discord.getMD5(code))) { msg("You have entered an invalid verification code", ChatColor.RED); return true; } else { - backupCode = plugin.dc.getMD5(code); + backupCode = Discord.getMD5(code); } } else diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whitelist.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whitelist.java index 2ffc1b6b..b07356e7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whitelist.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whitelist.java @@ -169,8 +169,7 @@ public class Command_whitelist extends FreedomCommand { if (args.length == 1) { - List arguments = new ArrayList<>(); - arguments.addAll(Arrays.asList("list", "count")); + List arguments = new ArrayList<>(Arrays.asList("list", "count")); if (plugin.al.isAdmin(sender)) { arguments.addAll(Arrays.asList("on", "off", "add", "remove", "addall")); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whohas.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whohas.java index cdd2754b..ac819030 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whohas.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_whohas.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import me.totalfreedom.totalfreedommod.rank.Rank; @@ -17,6 +16,16 @@ import org.bukkit.entity.Player; public class Command_whohas extends FreedomCommand { + public static List getAllMaterials() + { + List names = new ArrayList<>(); + for (Material material : Material.values()) + { + names.add(material.name()); + } + return names; + } + @Override public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { @@ -69,16 +78,6 @@ public class Command_whohas extends FreedomCommand return true; } - public static List getAllMaterials() - { - List names = new ArrayList<>(); - for (Material material : Material.values()) - { - names.add(material.name()); - } - return names; - } - @Override public List getTabCompleteOptions(CommandSender sender, Command command, String alias, String[] args) { @@ -89,7 +88,7 @@ public class Command_whohas extends FreedomCommand if (args.length == 2 && plugin.al.isAdmin(sender)) { - return Arrays.asList("clear"); + return Collections.singletonList("clear"); } return Collections.emptyList(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_wipeuserdata.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_wipeuserdata.java index 5efcca19..9ee23578 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_wipeuserdata.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_wipeuserdata.java @@ -1,6 +1,7 @@ package me.totalfreedom.totalfreedommod.command; import java.io.File; +import java.util.Objects; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.Bukkit; @@ -32,11 +33,11 @@ public class Command_wipeuserdata extends FreedomCommand continue; } - FUtil.deleteFolder(new File(server.getPluginManager().getPlugin("Essentials").getDataFolder(), "userdata")); + FUtil.deleteFolder(new File(Objects.requireNonNull(server.getPluginManager().getPlugin("Essentials")).getDataFolder(), "userdata")); FUtil.deleteFolder(new File(Bukkit.getServer().getWorld(plugin.wm.flatlands.getName()).getWorldFolder().getName() + "playerdata")); FUtil.deleteFolder(new File(Bukkit.getServer().getWorld(plugin.wm.flatlands.getName()).getWorldFolder().getName() + "stats")); - FUtil.deleteFolder(new File(Bukkit.getServer().getWorld(w.getName()).getWorldFolder().getName() + "stats")); - FUtil.deleteFolder(new File(Bukkit.getServer().getWorld(w.getName()).getWorldFolder().getName() + "playerdata")); + FUtil.deleteFolder(new File(Objects.requireNonNull(Bukkit.getServer().getWorld(w.getName())).getWorldFolder().getName() + "stats")); + FUtil.deleteFolder(new File(Objects.requireNonNull(Bukkit.getServer().getWorld(w.getName())).getWorldFolder().getName() + "playerdata")); msg("Deleted all player data."); return true; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_wipewarps.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_wipewarps.java index ce7dcc36..b7003ea6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_wipewarps.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_wipewarps.java @@ -25,6 +25,7 @@ public class Command_wipewarps extends FreedomCommand File warps = new File(essentials.getDataFolder(), "warps"); FUtil.adminAction(sender.getName(), "Wiping Essentials warps", true); FUtil.deleteFolder(warps); + //noinspection ResultOfMethodCallIgnored warps.mkdir(); essentials.reload(); msg("All warps deleted."); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java b/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java index e9116d88..8ca4efec 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java @@ -8,11 +8,10 @@ import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; -import lombok.Getter; import me.totalfreedom.totalfreedommod.TotalFreedomMod; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; @@ -27,43 +26,33 @@ import org.bukkit.command.PluginCommand; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; -import org.spigotmc.SpigotConfig; +import org.jetbrains.annotations.NotNull; public abstract class FreedomCommand implements CommandExecutor, TabCompleter { public static final String COMMAND_PREFIX = "Command_"; - - @Getter - private static CommandMap commandMap; - @Getter - private final String name; - private final String description; - private final String usage; - @Getter - private final String aliases; - private final Rank level; - private final SourceType source; - private final boolean blockHostConsole; - private final int cooldown; - private final CommandParameters params; - @Getter - private final CommandPermissions perms; - - protected CommandSender sender; - - protected final TotalFreedomMod plugin = TotalFreedomMod.getPlugin(); - protected final Server server = plugin.getServer(); - - public static final String UNKNOWN_COMMAND = ChatColor.WHITE + SpigotConfig.unknownCommandMessage; public static final String YOU_ARE_OP = ChatColor.YELLOW + "You are now op!"; public static final String YOU_ARE_NOT_OP = ChatColor.YELLOW + "You are no longer op!"; public static final String PLAYER_NOT_FOUND = ChatColor.GRAY + "Player not found!"; public static final String ONLY_CONSOLE = ChatColor.RED + "Only console senders may execute this command!"; public static final String ONLY_IN_GAME = ChatColor.RED + "Only in-game players may execute this command!"; public static final String NO_PERMISSION = ChatColor.RED + "You do not have permission to execute this command."; - public static final Timer timer = new Timer(); public static final Map COOLDOWN_TIMERS = new HashMap<>(); + private static CommandMap commandMap; + protected final TotalFreedomMod plugin = TotalFreedomMod.getPlugin(); + protected final Server server = plugin.getServer(); + private final String name; + private final String description; + private final String usage; + private final String aliases; + private final Rank level; + private final SourceType source; + private final boolean blockHostConsole; + private final int cooldown; + private final CommandParameters params; + private final CommandPermissions perms; + protected CommandSender sender; FreedomCommand() { @@ -79,25 +68,6 @@ public abstract class FreedomCommand implements CommandExecutor, TabCompleter this.cooldown = perms.cooldown(); } - public void register() - { - FCommand cmd = new FCommand(this.name); - if (this.aliases != null) - { - cmd.setAliases(Arrays.asList(StringUtils.split(this.aliases, ","))); - } - if (this.description != null) - { - cmd.setDescription(this.description); - } - if (this.usage != null) - { - cmd.setUsage(this.usage); - } - getCommandMap().register("totalfreedommod", cmd); - cmd.setExecutor(this); - } - public static CommandMap getCommandMap() { if (commandMap == null) @@ -116,84 +86,42 @@ public abstract class FreedomCommand implements CommandExecutor, TabCompleter return commandMap; } - private final class FCommand extends Command + public static FreedomCommand getFrom(Command command) { - private FreedomCommand cmd = null; - - private FCommand(String command) + try { - super(command); + return (FreedomCommand)(((PluginCommand)command).getExecutor()); } - - public void setExecutor(FreedomCommand cmd) + catch (Exception ex) { - this.cmd = cmd; - } - - public boolean execute(CommandSender sender, String commandLabel, String[] args) - { - if (cmd != null) - { - cmd.sender = sender; - - if (COOLDOWN_TIMERS.containsKey(sender) && COOLDOWN_TIMERS.containsValue(cmd)) - { - msg(ChatColor.RED + "You are on cooldown for this command."); - return true; - } - - if (perms.blockHostConsole() && FUtil.isFromHostConsole(sender.getName()) && !FUtil.inDeveloperMode()) - { - msg(ChatColor.RED + "Host console is not allowed to use this command!"); - return true; - } - - if (!plugin.rm.getRank(sender).isAtLeast(perms.level())) - { - msg(NO_PERMISSION); - return true; - } - - if (perms.source() == SourceType.ONLY_CONSOLE && sender instanceof Player) - { - msg(ONLY_CONSOLE); - return true; - } - - if (perms.source() == SourceType.ONLY_IN_GAME && sender instanceof ConsoleCommandSender) - { - msg(ONLY_IN_GAME); - return true; - } - - if (perms.cooldown() != 0 && !isAdmin(sender)) - { - COOLDOWN_TIMERS.put(sender, cmd); - timer.schedule(new TimerTask() - { - @Override - public void run() - { - COOLDOWN_TIMERS.remove(sender); - } - }, perms.cooldown() * 1000); - } - return cmd.onCommand(sender, this, commandLabel, args); - } - return false; - } - - @Override - public List tabComplete(CommandSender sender, String alias, String[] args) - { - if (cmd != null) - { - return cmd.onTabComplete(sender, this, alias, args); - } return null; } } + public static String getCommandPrefix() + { + return COMMAND_PREFIX; + } + + public void register() + { + FCommand cmd = new FCommand(this.name); + if (this.aliases != null) + { + cmd.setAliases(Arrays.asList(StringUtils.split(this.aliases, ","))); + } + if (this.description != null) + { + cmd.setDescription(this.description); + } + if (this.usage != null) + { + cmd.setUsage(this.usage); + } + getCommandMap().register("totalfreedommod", cmd); + cmd.setExecutor(this); + } + protected void msg(CommandSender sender, String message) { sender.sendMessage(ChatColor.GRAY + message); @@ -258,15 +186,7 @@ public abstract class FreedomCommand implements CommandExecutor, TabCompleter } } - protected void checkNotHostConsole() - { - if (isConsole() && FUtil.isFromHostConsole(sender.getName())) - { - throw new CommandFailException("This command can not be used from the host console."); - } - } - - public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String commandLabel, @NotNull String[] args) { try { @@ -284,7 +204,7 @@ public abstract class FreedomCommand implements CommandExecutor, TabCompleter return false; } - public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { List options = getTabCompleteOptions(sender, command, alias, args); if (options == null) @@ -344,14 +264,130 @@ public abstract class FreedomCommand implements CommandExecutor, TabCompleter throw new CommandFailException(NO_PERMISSION); } - public static FreedomCommand getFrom(Command command) + public String getName() { - try + return name; + } + + public String getDescription() + { + return description; + } + + public String getUsage() + { + return usage; + } + + public String getAliases() + { + return aliases; + } + + public Rank getLevel() + { + return level; + } + + public SourceType getSource() + { + return source; + } + + public boolean isBlockHostConsole() + { + return blockHostConsole; + } + + public int getCooldown() + { + return cooldown; + } + + public CommandParameters getParams() + { + return params; + } + + public CommandPermissions getPerms() + { + return perms; + } + + private final class FCommand extends Command + { + private FreedomCommand cmd = null; + + private FCommand(String command) { - return (FreedomCommand)(((PluginCommand)command).getExecutor()); + super(command); } - catch (Exception ex) + + public void setExecutor(FreedomCommand cmd) { + this.cmd = cmd; + } + + public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, String[] args) + { + if (cmd != null) + { + cmd.sender = sender; + + if (COOLDOWN_TIMERS.containsKey(sender) && COOLDOWN_TIMERS.containsValue(cmd)) + { + msg(ChatColor.RED + "You are on cooldown for this command."); + return true; + } + + if (perms.blockHostConsole() && FUtil.isFromHostConsole(sender.getName()) && !FUtil.inDeveloperMode()) + { + msg(ChatColor.RED + "Host console is not allowed to use this command!"); + return true; + } + + if (!plugin.rm.getRank(sender).isAtLeast(perms.level())) + { + msg(NO_PERMISSION); + return true; + } + + if (perms.source() == SourceType.ONLY_CONSOLE && sender instanceof Player) + { + msg(ONLY_CONSOLE); + return true; + } + + if (perms.source() == SourceType.ONLY_IN_GAME && sender instanceof ConsoleCommandSender) + { + msg(ONLY_IN_GAME); + return true; + } + + if (perms.cooldown() != 0 && !isAdmin(sender)) + { + COOLDOWN_TIMERS.put(sender, cmd); + timer.schedule(new TimerTask() + { + @Override + public void run() + { + COOLDOWN_TIMERS.remove(sender); + } + }, perms.cooldown() * 1000L); + } + return cmd.onCommand(sender, this, commandLabel, args); + } + return false; + } + + @Override + public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, String[] args) + { + if (cmd != null) + { + return cmd.onTabComplete(sender, this, alias, args); + } return null; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/SourceType.java b/src/main/java/me/totalfreedom/totalfreedommod/command/SourceType.java index 0cd232f0..20dc8211 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/SourceType.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/SourceType.java @@ -2,6 +2,5 @@ package me.totalfreedom.totalfreedommod.command; public enum SourceType { - - ONLY_IN_GAME, ONLY_CONSOLE, BOTH; + ONLY_IN_GAME, ONLY_CONSOLE, BOTH } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java index 926aac8f..e49f52e7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java @@ -1,6 +1,7 @@ package me.totalfreedom.totalfreedommod.config; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; @@ -172,6 +173,19 @@ public enum ConfigEntry this.configName = configName; } + public static ConfigEntry findConfigEntry(String name) + { + name = name.toLowerCase().replace("_", ""); + for (ConfigEntry entry : values()) + { + if (entry.toString().toLowerCase().replace("_", "").equals(name)) + { + return entry; + } + } + return null; + } + public Class getType() { return type; @@ -187,21 +201,14 @@ public enum ConfigEntry return getConfig().getString(this); } - public String setString(String value) - { - getConfig().setString(this, value); - return value; - } - public Double getDouble() { return getConfig().getDouble(this); } - public Double setDouble(Double value) + public void setDouble(Double value) { getConfig().setDouble(this, value); - return value; } public Boolean getBoolean() @@ -220,10 +227,9 @@ public enum ConfigEntry return getConfig().getInteger(this); } - public Integer setInteger(Integer value) + public void setInteger(Integer value) { getConfig().setInteger(this, value); - return value; } public List getList() @@ -239,19 +245,6 @@ public enum ConfigEntry private MainConfig getConfig() { - return TotalFreedomMod.plugin().config; - } - - public static ConfigEntry findConfigEntry(String name) - { - name = name.toLowerCase().replace("_", ""); - for (ConfigEntry entry : values()) - { - if (entry.toString().toLowerCase().replace("_", "").equals(name)) - { - return entry; - } - } - return null; + return Objects.requireNonNull(TotalFreedomMod.plugin()).config; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/config/MainConfig.java b/src/main/java/me/totalfreedom/totalfreedommod/config/MainConfig.java index c6e7be31..e3569923 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/config/MainConfig.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/config/MainConfig.java @@ -22,18 +22,6 @@ public class MainConfig extends FreedomService private final ConfigDefaults defaults; public YamlConfiguration configuration; - @Override - public void onStart() - { - - } - - @Override - public void onStop() - { - - } - public MainConfig() { entries = new EnumMap<>(ConfigEntry.class); @@ -69,6 +57,18 @@ public class MainConfig extends FreedomService defaults = tempDefaults; } + @Override + public void onStart() + { + + } + + @Override + public void onStop() + { + + } + public void load() { try @@ -212,7 +212,7 @@ public class MainConfig extends FreedomService } } - public List getList(ConfigEntry entry) + public List getList(ConfigEntry entry) { try { @@ -297,11 +297,7 @@ public class MainConfig extends FreedomService defaults.load(isr); isr.close(); } - catch (IOException ex) - { - FLog.severe(ex); - } - catch (InvalidConfigurationException ex) + catch (IOException | InvalidConfigurationException ex) { FLog.severe(ex); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/config/YamlConfig.java b/src/main/java/me/totalfreedom/totalfreedommod/config/YamlConfig.java index bd4585b8..0ed4aa89 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/config/YamlConfig.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/config/YamlConfig.java @@ -6,15 +6,11 @@ import org.bukkit.configuration.file.YamlConfiguration; public class YamlConfig extends YamlConfiguration { - private final TotalFreedomMod plugin; private final File file; - private final boolean copyDefaults; public YamlConfig(TotalFreedomMod plugin, String name, boolean copyDefaults) { - this.plugin = plugin; this.file = new File(plugin.getDataFolder(), name); - this.copyDefaults = copyDefaults; if (copyDefaults) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java index bf62f31a..18dfc1a8 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java @@ -9,15 +9,16 @@ import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Objects; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import javax.security.auth.login.LoginException; import me.totalfreedom.totalfreedommod.FreedomService; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; import net.dv8tion.jda.api.EmbedBuilder; @@ -48,322 +49,23 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.jetbrains.annotations.NotNull; public class Discord extends FreedomService { public static HashMap LINK_CODES = new HashMap<>(); public static HashMap VERIFICATION_CODES = new HashMap<>(); + public static JDA bot = null; public ScheduledThreadPoolExecutor RATELIMIT_EXECUTOR; public List> sentMessages = new ArrayList<>(); - - public static JDA bot = null; public Boolean enabled = false; - public void startBot() - { - boolean verificationEnabled = ConfigEntry.DISCORD_VERIFICATION.getBoolean(); - if (!verificationEnabled) - { - FLog.info("Discord Verification has been manually disabled."); - } - - enabled = !Strings.isNullOrEmpty(ConfigEntry.DISCORD_TOKEN.getString()); - if (!enabled) - { - return; - } - - if (bot != null) - { - RATELIMIT_EXECUTOR = new ScheduledThreadPoolExecutor(5, new CountingThreadFactory(this::poolIdentifier, "RateLimit")); - RATELIMIT_EXECUTOR.setRemoveOnCancelPolicy(true); - for (Object object : bot.getRegisteredListeners()) - { - bot.removeEventListener(object); - } - } - - try - { - bot = JDABuilder.createDefault(ConfigEntry.DISCORD_TOKEN.getString()) - .addEventListeners(new PrivateMessageListener(), - new DiscordToMinecraftListener(), - new DiscordToAdminChatListener(), - new ListenerAdapter() - { - @Override - public void onReady(ReadyEvent event) - { - new StartEvent(event.getJDA()).start(); - } - }) - .setAutoReconnect(true) - .setRateLimitPool(RATELIMIT_EXECUTOR) - .setChunkingFilter(ChunkingFilter.ALL) - .setMemberCachePolicy(MemberCachePolicy.ALL) - .enableIntents(GatewayIntent.GUILD_MEMBERS) - .build(); - FLog.info("Discord verification bot has successfully enabled!"); - } - catch (LoginException e) - { - FLog.warning("An invalid token for the discord verification bot, the bot will not enable."); - } - catch (IllegalArgumentException e) - { - FLog.warning("Discord verification bot failed to start."); - } - catch (NoClassDefFoundError e) - { - FLog.warning("The JDA plugin is not installed, therefore the discord bot cannot start."); - FLog.warning("To resolve this error, please download the latest JDA from: https://github.com/TFPatches/Minecraft-JDA/releases"); - } - - } - - public String poolIdentifier() - { - return "JDA"; - } - - public void clearQueue() - { - for (CompletableFuture messages : sentMessages) - { - if (!messages.isDone()) - { - messages.cancel(true); - } - } - sentMessages.clear(); - messageChatChannel("**Message queue cleared**"); - } - - // Do no ask why this is here. I spent two hours trying to make a simple thing work - public class StartEvent - { - private final JDA api; - - public StartEvent(JDA api) - { - this.api = api; - } - - public void start() - { - messageChatChannel("**Server has started**"); - } - } - - public void sendPteroInfo(PlayerData playerData, String username, String password) - { - User user = getUser(playerData.getDiscordID()); - String message = "The following are your Pterodactyl details:\n\nUsername: " + username + "\nPassword: " + password + "\n\nYou can connect to the panel at " + plugin.ptero.URL; - PrivateChannel privateChannel = user.openPrivateChannel().complete(); - privateChannel.sendMessage(message).complete(); - } - - public User getUser(String id) - { - Guild guild = bot.getGuildById(ConfigEntry.DISCORD_SERVER_ID.getString()); - - if (guild == null) - { - FLog.severe("Either the bot is not in the Discord server or it doesn't exist. Check the server ID."); - return null; - } - - Member member = guild.getMemberById(id); - - if (member == null) - { - return null; - } - - return member.getUser(); - } - - public boolean sendBackupCodes(PlayerData playerData) - { - List codes = generateBackupCodes(); - List encryptedCodes = generateEncryptedBackupCodes(codes); - User user = getUser(playerData.getDiscordID()); - File file = generateBackupCodesFile(playerData.getName(), codes); - if (file == null) - { - return false; - } - PrivateChannel privateChannel = user.openPrivateChannel().complete(); - privateChannel.sendMessage("Do not share these codes with anyone as they can be used to impose as you.").addFile(file).complete(); - playerData.setBackupCodes(encryptedCodes); - plugin.pl.save(playerData); - file.delete(); - return true; - } - - public List generateBackupCodes() - { - List codes = new ArrayList<>(); - for (int i = 0; i < 10; i++) - { - codes.add(FUtil.randomAlphanumericString(10)); - } - return codes; - } - - public String generateCode(int size) - { - StringBuilder code = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < size; i++) - { - code.append(random.nextInt(10)); - } - return code.toString(); - } - - public List generateEncryptedBackupCodes(List codes) - { - List encryptedCodes = new ArrayList<>(); - for (String code : codes) - { - encryptedCodes.add(getMD5(code)); - } - return encryptedCodes; - } - - public File generateBackupCodesFile(String name, List codes) - { - StringBuilder text = new StringBuilder(); - text.append("Below are your backup codes for use on TotalFreedom in the event you lose access to your discord account.\n") - .append("Simply pick a code, and run /verify on the server. Each code is one use, so be sure to cross it off once you use it.\n") - .append("To generate new codes, simply run /generatebackupcodes\n\n"); - - for (String code : codes) - { - text.append(code).append("\n"); - } - - String fileUrl = plugin.getDataFolder().getAbsolutePath() + "/TF-Backup-Codes-" + name + ".txt"; - try - { - FileWriter fileWriter = new FileWriter(fileUrl); - fileWriter.write(text.toString()); - fileWriter.close(); - } - catch (IOException e) - { - FLog.severe("Failed to generate backup codes file: " + e.toString()); - return null; - } - return new File(fileUrl); - } - public static String getMD5(String string) { return DigestUtils.md5Hex(string); } - public void addVerificationCode(String code, PlayerData playerData) - { - VERIFICATION_CODES.put(code, playerData); - } - - public void removeVerificationCode(String code) - { - VERIFICATION_CODES.remove(code); - } - - public HashMap getVerificationCodes() - { - return VERIFICATION_CODES; - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerDeath(PlayerDeathEvent event) - { - if (!event.getEntity().getWorld().getGameRuleValue(GameRule.SHOW_DEATH_MESSAGES)) - { - return; - } - - if (event.getDeathMessage() != null) - { - messageChatChannel("**" + event.getDeathMessage() + "**"); - } - } - - @Override - public void onStart() - { - startBot(); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(PlayerJoinEvent event) - { - if (!plugin.al.isVanished(event.getPlayer().getName())) - { - messageChatChannel("**" + event.getPlayer().getName() + " joined the server" + "**"); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerLeave(PlayerQuitEvent event) - { - if (!plugin.al.isVanished(event.getPlayer().getName())) - { - messageChatChannel("**" + event.getPlayer().getName() + " left the server" + "**"); - } - } - - public void messageChatChannel(String message) - { - String chat_channel_id = ConfigEntry.DISCORD_CHAT_CHANNEL_ID.getString(); - if (message.contains("@everyone") || message.contains("@here")) - { - message = StringUtils.remove(message, "@"); - } - - if (message.toLowerCase().contains("discord.gg")) - { - return; - } - - if (enabled && !chat_channel_id.isEmpty()) - { - CompletableFuture sentMessage = bot.getTextChannelById(chat_channel_id).sendMessage(deformat(message)).submit(true); - sentMessages.add(sentMessage); - } - } - - public void messageAdminChatChannel(String message) - { - String chat_channel_id = ConfigEntry.DISCORD_ADMINCHAT_CHANNEL_ID.getString(); - if (message.contains("@everyone") || message.contains("@here")) - { - message = StringUtils.remove(message, "@"); - } - - if (message.toLowerCase().contains("discord.gg")) - { - return; - } - - if (enabled && !chat_channel_id.isEmpty()) - { - CompletableFuture sentMessage = bot.getTextChannelById(chat_channel_id).sendMessage(deformat(message)).submit(true); - sentMessages.add(sentMessage); - } - } - - public String formatBotTag() - { - SelfUser user = bot.getSelfUser(); - return user.getName() + "#" + user.getDiscriminator(); - } - public static String getCode(PlayerData playerData) { for (String code : LINK_CODES.keySet()) @@ -376,68 +78,6 @@ public class Discord extends FreedomService return null; } - @Override - public void onStop() - { - if (bot != null) - { - messageChatChannel("**Server has stopped**"); - } - - FLog.info("Discord verification bot has successfully shutdown."); - } - - public String deformat(String input) - { - return input.replace("_", "\\_"); - } - - public boolean sendReport(Player reporter, Player reported, String reason) - { - if (ConfigEntry.DISCORD_REPORT_CHANNEL_ID.getString().isEmpty()) - { - return false; - } - - if (ConfigEntry.DISCORD_SERVER_ID.getString().isEmpty()) - { - FLog.severe("No Discord server ID was specified in the config, but there is a report channel ID."); - return false; - } - - Guild server = bot.getGuildById(ConfigEntry.DISCORD_SERVER_ID.getString()); - if (server == null) - { - FLog.severe("The Discord server ID specified is invalid, or the bot is not on the server."); - return false; - } - - TextChannel channel = server.getTextChannelById(ConfigEntry.DISCORD_REPORT_CHANNEL_ID.getString()); - if (channel == null) - { - FLog.severe("The report channel ID specified in the config is invalid."); - return false; - } - - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle("Report for " + reported.getName()); - embedBuilder.setDescription(reason); - embedBuilder.setFooter("Reported by " + reporter.getName(), "https://minotar.net/helm/" + reporter.getName() + ".png"); - embedBuilder.setTimestamp(Instant.from(ZonedDateTime.now())); - String location = "World: " + reported.getLocation().getWorld().getName() + ", X: " + reported.getLocation().getBlockX() + ", Y: " + reported.getLocation().getBlockY() + ", Z: " + reported.getLocation().getBlockZ(); - embedBuilder.addField("Location", location, true); - embedBuilder.addField("Game Mode", WordUtils.capitalizeFully(reported.getGameMode().name()), true); - com.earth2me.essentials.User user = plugin.esb.getEssentialsUser(reported.getName()); - embedBuilder.addField("God Mode", WordUtils.capitalizeFully(String.valueOf(user.isGodModeEnabled())), true); - if (user.getNickname() != null) - { - embedBuilder.addField("Nickname", user.getNickname(), true); - } - MessageEmbed embed = embedBuilder.build(); - channel.sendMessage(embed).complete(); - return true; - } - public static boolean syncRoles(Admin admin, String discordID) { if (discordID == null) @@ -511,4 +151,365 @@ public class Discord extends FreedomService } return false; } + + public void startBot() + { + boolean verificationEnabled = ConfigEntry.DISCORD_VERIFICATION.getBoolean(); + if (!verificationEnabled) + { + FLog.info("Discord Verification has been manually disabled."); + } + + enabled = !Strings.isNullOrEmpty(ConfigEntry.DISCORD_TOKEN.getString()); + if (!enabled) + { + return; + } + + if (bot != null) + { + RATELIMIT_EXECUTOR = new ScheduledThreadPoolExecutor(5, new CountingThreadFactory(this::poolIdentifier, "RateLimit")); + RATELIMIT_EXECUTOR.setRemoveOnCancelPolicy(true); + for (Object object : bot.getRegisteredListeners()) + { + bot.removeEventListener(object); + } + } + + try + { + bot = JDABuilder.createDefault(ConfigEntry.DISCORD_TOKEN.getString()) + .addEventListeners(new PrivateMessageListener(), + new DiscordToMinecraftListener(), + new DiscordToAdminChatListener(), + new ListenerAdapter() + { + @Override + public void onReady(@NotNull ReadyEvent event) + { + new StartEvent(event.getJDA()).start(); + } + }) + .setAutoReconnect(true) + .setRateLimitPool(RATELIMIT_EXECUTOR) + .setChunkingFilter(ChunkingFilter.ALL) + .setMemberCachePolicy(MemberCachePolicy.ALL) + .enableIntents(GatewayIntent.GUILD_MEMBERS) + .build(); + FLog.info("Discord verification bot has successfully enabled!"); + } + catch (LoginException e) + { + FLog.warning("An invalid token for the discord verification bot, the bot will not enable."); + } + catch (IllegalArgumentException e) + { + FLog.warning("Discord verification bot failed to start."); + } + catch (NoClassDefFoundError e) + { + FLog.warning("The JDA plugin is not installed, therefore the discord bot cannot start."); + FLog.warning("To resolve this error, please download the latest JDA from: https://github.com/TFPatches/Minecraft-JDA/releases"); + } + + } + + public String poolIdentifier() + { + return "JDA"; + } + + public void clearQueue() + { + for (CompletableFuture messages : sentMessages) + { + if (!messages.isDone()) + { + messages.cancel(true); + } + } + sentMessages.clear(); + messageChatChannel("**Message queue cleared**"); + } + + public void sendPteroInfo(PlayerData playerData, String username, String password) + { + User user = getUser(playerData.getDiscordID()); + String message = "The following are your Pterodactyl details:\n\nUsername: " + username + "\nPassword: " + password + "\n\nYou can connect to the panel at " + plugin.ptero.URL; + PrivateChannel privateChannel = user.openPrivateChannel().complete(); + privateChannel.sendMessage(message).complete(); + } + + public User getUser(String id) + { + Guild guild = bot.getGuildById(ConfigEntry.DISCORD_SERVER_ID.getString()); + + if (guild == null) + { + FLog.severe("Either the bot is not in the Discord server or it doesn't exist. Check the server ID."); + return null; + } + + Member member = guild.getMemberById(id); + + if (member == null) + { + return null; + } + + return member.getUser(); + } + + public boolean sendBackupCodes(PlayerData playerData) + { + List codes = generateBackupCodes(); + List encryptedCodes = generateEncryptedBackupCodes(codes); + User user = getUser(playerData.getDiscordID()); + File file = generateBackupCodesFile(playerData.getName(), codes); + if (file == null) + { + return false; + } + PrivateChannel privateChannel = user.openPrivateChannel().complete(); + privateChannel.sendMessage("Do not share these codes with anyone as they can be used to impose as you.").addFile(file).complete(); + playerData.setBackupCodes(encryptedCodes); + plugin.pl.save(playerData); + //noinspection ResultOfMethodCallIgnored + file.delete(); + return true; + } + + public List generateBackupCodes() + { + List codes = new ArrayList<>(); + for (int i = 0; i < 10; i++) + { + codes.add(FUtil.randomAlphanumericString(10)); + } + return codes; + } + + public String generateCode(int size) + { + StringBuilder code = new StringBuilder(); + Random random = new Random(); + for (int i = 0; i < size; i++) + { + code.append(random.nextInt(10)); + } + return code.toString(); + } + + public List generateEncryptedBackupCodes(List codes) + { + List encryptedCodes = new ArrayList<>(); + for (String code : codes) + { + encryptedCodes.add(getMD5(code)); + } + return encryptedCodes; + } + + public File generateBackupCodesFile(String name, List codes) + { + StringBuilder text = new StringBuilder(); + text.append("Below are your backup codes for use on TotalFreedom in the event you lose access to your discord account.\n") + .append("Simply pick a code, and run /verify on the server. Each code is one use, so be sure to cross it off once you use it.\n") + .append("To generate new codes, simply run /generatebackupcodes\n\n"); + + for (String code : codes) + { + text.append(code).append("\n"); + } + + String fileUrl = plugin.getDataFolder().getAbsolutePath() + "/TF-Backup-Codes-" + name + ".txt"; + try + { + FileWriter fileWriter = new FileWriter(fileUrl); + fileWriter.write(text.toString()); + fileWriter.close(); + } + catch (IOException e) + { + FLog.severe("Failed to generate backup codes file: " + e.toString()); + return null; + } + return new File(fileUrl); + } + + public void addVerificationCode(String code, PlayerData playerData) + { + VERIFICATION_CODES.put(code, playerData); + } + + public void removeVerificationCode(String code) + { + VERIFICATION_CODES.remove(code); + } + + public HashMap getVerificationCodes() + { + return VERIFICATION_CODES; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerDeath(PlayerDeathEvent event) + { + //Avoiding NPE Unboxing Warnings + Boolean b = event.getEntity().getWorld().getGameRuleValue(GameRule.SHOW_DEATH_MESSAGES); + if (b == null || !b) + { + return; + } + + if (event.getDeathMessage() != null) + { + messageChatChannel("**" + event.getDeathMessage() + "**"); + } + } + + @Override + public void onStart() + { + startBot(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(PlayerJoinEvent event) + { + if (!plugin.al.isVanished(event.getPlayer().getName())) + { + messageChatChannel("**" + event.getPlayer().getName() + " joined the server" + "**"); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerLeave(PlayerQuitEvent event) + { + if (!plugin.al.isVanished(event.getPlayer().getName())) + { + messageChatChannel("**" + event.getPlayer().getName() + " left the server" + "**"); + } + } + + public void messageChatChannel(String message) + { + String chat_channel_id = ConfigEntry.DISCORD_CHAT_CHANNEL_ID.getString(); + if (message.contains("@everyone") || message.contains("@here")) + { + message = StringUtils.remove(message, "@"); + } + + if (message.toLowerCase().contains("discord.gg")) + { + return; + } + + if (enabled && !chat_channel_id.isEmpty()) + { + CompletableFuture sentMessage = Objects.requireNonNull(bot.getTextChannelById(chat_channel_id)).sendMessage(deformat(message)).submit(true); + sentMessages.add(sentMessage); + } + } + + public void messageAdminChatChannel(String message) + { + String chat_channel_id = ConfigEntry.DISCORD_ADMINCHAT_CHANNEL_ID.getString(); + if (message.contains("@everyone") || message.contains("@here")) + { + message = StringUtils.remove(message, "@"); + } + + if (message.toLowerCase().contains("discord.gg")) + { + return; + } + + if (enabled && !chat_channel_id.isEmpty()) + { + CompletableFuture sentMessage = Objects.requireNonNull(bot.getTextChannelById(chat_channel_id)).sendMessage(deformat(message)).submit(true); + sentMessages.add(sentMessage); + } + } + + public String formatBotTag() + { + SelfUser user = bot.getSelfUser(); + return user.getName() + "#" + user.getDiscriminator(); + } + + @Override + public void onStop() + { + if (bot != null) + { + messageChatChannel("**Server has stopped**"); + } + + FLog.info("Discord verification bot has successfully shutdown."); + } + + public String deformat(String input) + { + return input.replace("_", "\\_"); + } + + public boolean sendReport(Player reporter, Player reported, String reason) + { + if (ConfigEntry.DISCORD_REPORT_CHANNEL_ID.getString().isEmpty()) + { + return false; + } + + if (ConfigEntry.DISCORD_SERVER_ID.getString().isEmpty()) + { + FLog.severe("No Discord server ID was specified in the config, but there is a report channel ID."); + return false; + } + + Guild server = bot.getGuildById(ConfigEntry.DISCORD_SERVER_ID.getString()); + if (server == null) + { + FLog.severe("The Discord server ID specified is invalid, or the bot is not on the server."); + return false; + } + + TextChannel channel = server.getTextChannelById(ConfigEntry.DISCORD_REPORT_CHANNEL_ID.getString()); + if (channel == null) + { + FLog.severe("The report channel ID specified in the config is invalid."); + return false; + } + + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setTitle("Report for " + reported.getName()); + embedBuilder.setDescription(reason); + embedBuilder.setFooter("Reported by " + reporter.getName(), "https://minotar.net/helm/" + reporter.getName() + ".png"); + embedBuilder.setTimestamp(Instant.from(ZonedDateTime.now())); + String location = "World: " + Objects.requireNonNull(reported.getLocation().getWorld()).getName() + ", X: " + reported.getLocation().getBlockX() + ", Y: " + reported.getLocation().getBlockY() + ", Z: " + reported.getLocation().getBlockZ(); + embedBuilder.addField("Location", location, true); + embedBuilder.addField("Game Mode", WordUtils.capitalizeFully(reported.getGameMode().name()), true); + com.earth2me.essentials.User user = plugin.esb.getEssentialsUser(reported.getName()); + embedBuilder.addField("God Mode", WordUtils.capitalizeFully(String.valueOf(user.isGodModeEnabled())), true); + if (user.getNickname() != null) + { + embedBuilder.addField("Nickname", user.getNickname(), true); + } + MessageEmbed embed = embedBuilder.build(); + channel.sendMessage(embed).complete(); + return true; + } + + // Do no ask why this is here. I spent two hours trying to make a simple thing work + public class StartEvent + { + public StartEvent(JDA api) + { + } + + public void start() + { + messageChatChannel("**Server has started**"); + } + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToAdminChatListener.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToAdminChatListener.java index 169b9d43..832dbed6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToAdminChatListener.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToAdminChatListener.java @@ -33,7 +33,7 @@ public class DiscordToAdminChatListener extends ListenerAdapter { message.append(" ").append(tag); } - message.append(" " + ChatColor.RED).append(ChatColor.stripColor(member.getEffectiveName())).append(ChatColor.DARK_GRAY).append(":").append(ChatColor.RESET); + message.append(" ").append(ChatColor.RED).append(ChatColor.stripColor(member.getEffectiveName())).append(ChatColor.DARK_GRAY).append(":").append(ChatColor.RESET); ComponentBuilder builder = new ComponentBuilder(message.toString()); if (!msg.getContentDisplay().isEmpty()) { @@ -44,10 +44,7 @@ public class DiscordToAdminChatListener extends ListenerAdapter { for (Message.Attachment attachment : msg.getAttachments()) { - if (attachment.getUrl() == null) - { - continue; - } + attachment.getUrl(); builder.append(" "); TextComponent text = new TextComponent(ChatColor.YELLOW + "[Media]"); text.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, attachment.getUrl())); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToMinecraftListener.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToMinecraftListener.java index 083e66fa..85a58d64 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToMinecraftListener.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToMinecraftListener.java @@ -34,7 +34,7 @@ public class DiscordToMinecraftListener extends ListenerAdapter { message.append(" ").append(tag); } - message.append(" " + ChatColor.RED).append(ChatColor.stripColor(member.getEffectiveName())).append(ChatColor.DARK_GRAY).append(":").append(ChatColor.RESET); + message.append(" ").append(ChatColor.RED).append(ChatColor.stripColor(member.getEffectiveName())).append(ChatColor.DARK_GRAY).append(":").append(ChatColor.RESET); ComponentBuilder builder = new ComponentBuilder(message.toString()); if (!msg.getContentDisplay().isEmpty()) { @@ -45,10 +45,7 @@ public class DiscordToMinecraftListener extends ListenerAdapter { for (Message.Attachment attachment : msg.getAttachments()) { - if (attachment.getUrl() == null) - { - continue; - } + attachment.getUrl(); builder.append(" "); TextComponent text = new TextComponent(ChatColor.YELLOW + "[Media]"); text.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, attachment.getUrl())); @@ -72,6 +69,7 @@ public class DiscordToMinecraftListener extends ListenerAdapter { Guild server = Discord.bot.getGuildById(ConfigEntry.DISCORD_SERVER_ID.getString()); // Server Owner + assert server != null; if (member.getRoles().contains(server.getRoleById(ConfigEntry.DISCORD_SERVER_OWNER_ROLE_ID.getString()))) { return Title.OWNER.getColoredTag(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java index 9c82a81e..bdd9e90c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java @@ -1,8 +1,9 @@ package me.totalfreedom.totalfreedommod.discord; +import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; -import me.totalfreedom.totalfreedommod.player.PlayerData; import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.player.PlayerData; import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; @@ -24,12 +25,12 @@ public class PrivateMessageListener extends ListenerAdapter player.setDiscordID(event.getMessage().getAuthor().getId()); player.setVerification(true); - Admin admin = TotalFreedomMod.plugin().al.getEntryByName(name); + Admin admin = Objects.requireNonNull(TotalFreedomMod.plugin()).al.getEntryByName(name); if (admin != null) { Discord.syncRoles(admin, player.getDiscordID()); } - TotalFreedomMod.plugin().pl.save(player); + Objects.requireNonNull(TotalFreedomMod.plugin()).pl.save(player); Discord.LINK_CODES.remove(code); } else diff --git a/src/main/java/me/totalfreedom/totalfreedommod/freeze/FreezeData.java b/src/main/java/me/totalfreedom/totalfreedommod/freeze/FreezeData.java index f0f97136..bb03caaf 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/freeze/FreezeData.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/freeze/FreezeData.java @@ -1,6 +1,6 @@ package me.totalfreedom.totalfreedommod.freeze; -import lombok.Getter; +import java.util.Objects; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; @@ -17,7 +17,6 @@ public class FreezeData private final FPlayer fPlayer; // - @Getter private Location location = null; private BukkitTask unfreeze = null; @@ -36,7 +35,7 @@ public class FreezeData final Player player = fPlayer.getPlayer(); if (player == null) { - FLog.info("Could not freeze " + player.getName() + ". Player not online!"); + FLog.info("Could not freeze that player as they are not online!"); return; } @@ -62,13 +61,18 @@ public class FreezeData @Override public void run() { - if (!plugin().al.isAdminImpostor(player) && plugin().pl.isPlayerImpostor(player)) + if (!Objects.requireNonNull(plugin()).al.isAdminImpostor(player) && Objects.requireNonNull(plugin()).pl.isPlayerImpostor(player)) { FUtil.adminAction("TotalFreedom", "Unfreezing " + player.getName(), false); setFrozen(false); } } - }.runTaskLater(plugin(), AUTO_PURGE_TICKS); + }.runTaskLater(Objects.requireNonNull(plugin()), AUTO_PURGE_TICKS); + } + + public Location getLocation() + { + return location; } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/freeze/Freezer.java b/src/main/java/me/totalfreedom/totalfreedommod/freeze/Freezer.java index 6dfa2594..cb0a33f9 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/freeze/Freezer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/freeze/Freezer.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.freeze; -import lombok.Getter; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.Location; @@ -12,7 +11,6 @@ import org.bukkit.event.player.PlayerMoveEvent; public class Freezer extends FreedomService { - @Getter private boolean globalFreeze = false; @Override @@ -26,11 +24,6 @@ public class Freezer extends FreedomService { } - public void setGlobalFreeze(boolean frozen) - { - this.globalFreeze = frozen; - } - public void purge() { this.globalFreeze = false; @@ -60,11 +53,17 @@ public class Freezer extends FreedomService FUtil.setFlying(player, true); Location loc = player.getLocation(); - if (loc == null) - { - loc = event.getFrom(); - } event.setTo(loc); } + + public boolean isGlobalFreeze() + { + return globalFreeze; + } + + public void setGlobalFreeze(boolean frozen) + { + this.globalFreeze = frozen; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java index f1875723..30a83f57 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Random; import java.util.UUID; import me.totalfreedom.totalfreedommod.FreedomService; @@ -47,15 +48,11 @@ import org.bukkit.util.Vector; public class ItemFun extends FreedomService { - public List explosivePlayers = new ArrayList<>(); - private final Random random = new Random(); - private final Map> cooldownTracker = new HashMap<>(); - private final Map orientationTracker = new HashMap<>(); - private final List FIRE_BALL_UUIDS = new ArrayList<>(); + public List explosivePlayers = new ArrayList<>(); private void cooldown(Player player, ShopItem item, int seconds) { @@ -282,7 +279,7 @@ public class ItemFun extends FreedomService didHit = true; } } - catch (IllegalArgumentException ex) + catch (IllegalArgumentException ignored) { } } @@ -294,7 +291,7 @@ public class ItemFun extends FreedomService { if (sound.toString().contains("HIT")) { - playerLoc.getWorld().playSound(randomOffset(playerLoc, 5.0), sound, 20f, randomDoubleRange(0.5, 2.0).floatValue()); + Objects.requireNonNull(playerLoc.getWorld()).playSound(randomOffset(playerLoc), sound, 20f, randomDoubleRange(0.5, 2.0).floatValue()); } } cooldown(player, ShopItem.CLOWN_FISH, 30); @@ -329,9 +326,10 @@ public class ItemFun extends FreedomService } if (arrow != null && (arrow.getShooter() instanceof Player)) { - if (explosivePlayers.contains((Player)arrow.getShooter())) + //Redundant Player cast is required to avoid suspicious method calls. + if (explosivePlayers.contains(arrow.getShooter())) { - arrow.getLocation().getWorld().createExplosion(arrow.getLocation().getX(), arrow.getLocation().getY(), arrow.getLocation().getZ(), ConfigEntry.EXPLOSIVE_RADIUS.getDouble().floatValue(), false, ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()); + Objects.requireNonNull(arrow.getLocation().getWorld()).createExplosion(arrow.getLocation().getX(), arrow.getLocation().getY(), arrow.getLocation().getZ(), ConfigEntry.EXPLOSIVE_RADIUS.getDouble().floatValue(), false, ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()); arrow.remove(); } } @@ -355,9 +353,9 @@ public class ItemFun extends FreedomService } } - private Location randomOffset(Location a, double magnitude) + private Location randomOffset(Location a) { - return a.clone().add(randomDoubleRange(-1.0, 1.0) * magnitude, randomDoubleRange(-1.0, 1.0) * magnitude, randomDoubleRange(-1.0, 1.0) * magnitude); + return a.clone().add(randomDoubleRange(-1.0, 1.0) * 5.0, randomDoubleRange(-1.0, 1.0) * 5.0, randomDoubleRange(-1.0, 1.0) * 5.0); } private Double randomDoubleRange(double min, double max) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/Jumppads.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/Jumppads.java index 523f9540..b551ea4b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/Jumppads.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/Jumppads.java @@ -3,8 +3,7 @@ package me.totalfreedom.totalfreedommod.fun; import com.google.common.collect.Maps; import java.util.HashMap; import java.util.Map; -import lombok.Getter; -import lombok.Setter; +import java.util.Objects; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.util.Groups; import org.bukkit.block.Block; @@ -20,11 +19,14 @@ public class Jumppads extends FreedomService public static final double DAMPING_COEFFICIENT = 0.8; // private final Map pushMap = Maps.newHashMap(); - // - @Getter - @Setter - private double strength = 1 + 0.1F; public HashMap players = new HashMap<>(); + // + private final double strength = 1 + 0.1F; + + public static double getDampingCoefficient() + { + return DAMPING_COEFFICIENT; + } @Override public void onStart() @@ -56,7 +58,7 @@ public class Jumppads extends FreedomService } final Player player = event.getPlayer(); - final Block block = event.getTo().getBlock(); + final Block block = Objects.requireNonNull(event.getTo()).getBlock(); final Vector velocity = player.getVelocity().clone(); if (players.get(event.getPlayer()) == JumpPadMode.MADGEEK) @@ -118,7 +120,27 @@ public class Jumppads extends FreedomService } } - public static enum JumpPadMode + public Map getPushMap() + { + return pushMap; + } + + public double getStrength() + { + return strength; + } + + public HashMap getPlayers() + { + return players; + } + + public void setPlayers(HashMap players) + { + this.players = players; + } + + public enum JumpPadMode { OFF(false), NORMAL_AND_SIDEWAYS(true), MADGEEK(true); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/Landminer.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/Landminer.java index f3896d07..471a3dc0 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/Landminer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/Landminer.java @@ -18,8 +18,6 @@ import org.bukkit.util.Vector; public class Landminer extends FreedomService { - - @Getter private final List landmines = new ArrayList<>(); @Override @@ -43,6 +41,7 @@ public class Landminer extends FreedomService landmines.remove(landmine); } + @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.NORMAL) public void onPlayerMove(PlayerMoveEvent event) { @@ -95,6 +94,11 @@ public class Landminer extends FreedomService } } + public List getLandmines() + { + return landmines; + } + public static class Landmine { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java index f1de102d..a72abaa1 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java @@ -1,6 +1,7 @@ package me.totalfreedom.totalfreedommod.fun; import java.util.HashSet; +import java.util.Objects; import java.util.Random; import java.util.Set; import me.totalfreedom.totalfreedommod.FreedomService; @@ -53,7 +54,7 @@ public class Trailer extends FreedomService return; } - Block toBlock = event.getTo().getBlock(); + Block toBlock = Objects.requireNonNull(event.getTo()).getBlock(); if (fromBlock.equals(toBlock)) { return; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTMLGenerationTools.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTMLGenerationTools.java index 23bc066c..b682e8cc 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTMLGenerationTools.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTMLGenerationTools.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.httpd; import java.util.Collection; -import java.util.Iterator; import java.util.Map; import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4; @@ -23,10 +22,8 @@ public class HTMLGenerationTools output.append("
    \r\n"); - Iterator> it = map.entrySet().iterator(); - while (it.hasNext()) + for (Map.Entry entry : map.entrySet()) { - Map.Entry entry = it.next(); output.append("
  • ").append(escapeHtml4(entry.getKey().toString() + " = " + entry.getValue().toString())).append("
  • \r\n"); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java index b7fd4474..21b647b6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java @@ -12,6 +12,7 @@ import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Response; import me.totalfreedom.totalfreedommod.httpd.module.HTTPDModule; import me.totalfreedom.totalfreedommod.httpd.module.Module_activitylog; +import me.totalfreedom.totalfreedommod.httpd.module.Module_admins; import me.totalfreedom.totalfreedommod.httpd.module.Module_bans; import me.totalfreedom.totalfreedommod.httpd.module.Module_file; import me.totalfreedom.totalfreedommod.httpd.module.Module_help; @@ -23,7 +24,6 @@ import me.totalfreedom.totalfreedommod.httpd.module.Module_logs; import me.totalfreedom.totalfreedommod.httpd.module.Module_players; import me.totalfreedom.totalfreedommod.httpd.module.Module_punishments; import me.totalfreedom.totalfreedommod.httpd.module.Module_schematic; -import me.totalfreedom.totalfreedommod.httpd.module.Module_admins; import me.totalfreedom.totalfreedommod.util.FLog; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; @@ -32,12 +32,50 @@ import org.apache.commons.lang.exception.ExceptionUtils; public class HTTPDaemon extends FreedomService { + private static final Pattern EXT_REGEX = Pattern.compile("\\.([^.\\s]+)$"); public static String MIME_DEFAULT_BINARY = "application/octet-stream"; - private static final Pattern EXT_REGEX = Pattern.compile("\\.([^\\.\\s]+)$"); // public int port; - private HTTPD httpd; public Map modules = new HashMap<>(); + private HTTPD httpd; + + public static Response serveFileBasic(File file) + { + Response response = null; + + if (file != null && file.exists()) + { + try + { + String mimetype = null; + + Matcher matcher = EXT_REGEX.matcher(file.getCanonicalPath()); + if (matcher.find()) + { + mimetype = Module_file.MIME_TYPES.get(matcher.group(1)); + } + + if (mimetype == null || mimetype.trim().isEmpty()) + { + mimetype = MIME_DEFAULT_BINARY; + } + + // Some browsers like firefox download the file for text/yaml mime types + if (FilenameUtils.getExtension(file.getName()).equals("yml")) + { + mimetype = NanoHTTPD.MIME_PLAINTEXT; + } + + response = new Response(Response.Status.OK, mimetype, new FileInputStream(file)); + response.addHeader("Content-Length", "" + file.length()); + } + catch (IOException ex) + { + FLog.severe(ex); + } + } + return response; + } @Override public void onStart() @@ -141,42 +179,4 @@ public class HTTPDaemon extends FreedomService } } } - - public static Response serveFileBasic(File file) - { - Response response = null; - - if (file != null && file.exists()) - { - try - { - String mimetype = null; - - Matcher matcher = EXT_REGEX.matcher(file.getCanonicalPath()); - if (matcher.find()) - { - mimetype = Module_file.MIME_TYPES.get(matcher.group(1)); - } - - if (mimetype == null || mimetype.trim().isEmpty()) - { - mimetype = MIME_DEFAULT_BINARY; - } - - // Some browsers like firefox download the file for text/yaml mime types - if (FilenameUtils.getExtension(file.getName()).equals("yml")) - { - mimetype = NanoHTTPD.MIME_PLAINTEXT; - } - - response = new Response(Response.Status.OK, mimetype, new FileInputStream(file)); - response.addHeader("Content-Length", "" + file.length()); - } - catch (IOException ex) - { - FLog.severe(ex); - } - } - return response; - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java index c008afdd..14148644 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java @@ -1,7 +1,7 @@ package me.totalfreedom.totalfreedommod.httpd; import java.lang.reflect.Constructor; -import java.util.concurrent.Callable; +import java.util.Objects; import lombok.Getter; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.httpd.module.HTTPDModule; @@ -19,35 +19,6 @@ public abstract class ModuleExecutable this.async = async; } - public NanoHTTPD.Response execute(final NanoHTTPD.HTTPSession session) - { - try - { - if (async) - { - return getResponse(session); - } - - // Sync to server thread - return Bukkit.getScheduler().callSyncMethod(TotalFreedomMod.plugin(), new Callable() - { - @Override - public NanoHTTPD.Response call() throws Exception - { - return getResponse(session); - } - }).get(); - - } - catch (Exception ex) - { - FLog.severe(ex); - } - return null; - } - - public abstract NanoHTTPD.Response getResponse(NanoHTTPD.HTTPSession session); - public static ModuleExecutable forClass(final TotalFreedomMod plugin, Class clazz, boolean async) { final Constructor cons; @@ -78,4 +49,26 @@ public abstract class ModuleExecutable }; } + public NanoHTTPD.Response execute(final NanoHTTPD.HTTPSession session) + { + try + { + if (async) + { + return getResponse(session); + } + + // Sync to server thread + return Bukkit.getScheduler().callSyncMethod(Objects.requireNonNull(TotalFreedomMod.plugin()), () -> getResponse(session)).get(); + + } + catch (Exception ex) + { + FLog.severe(ex); + } + return null; + } + + public abstract NanoHTTPD.Response getResponse(NanoHTTPD.HTTPSession session); + } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java index fe784f09..702c20d6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java @@ -21,6 +21,7 @@ import java.net.SocketException; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; @@ -33,6 +34,7 @@ import java.util.Map; import java.util.StringTokenizer; import java.util.TimeZone; import me.totalfreedom.totalfreedommod.util.FLog; +import org.jetbrains.annotations.NotNull; /** * A simple, tiny, nicely embeddable HTTP server in Java @@ -133,7 +135,7 @@ public abstract class NanoHTTPD setAsyncRunner(new DefaultAsyncRunner()); } - private static final void safeClose(ServerSocket serverSocket) + private static void safeClose(ServerSocket serverSocket) { if (serverSocket != null) { @@ -141,13 +143,13 @@ public abstract class NanoHTTPD { serverSocket.close(); } - catch (IOException e) + catch (IOException ignored) { } } } - private static final void safeClose(Socket socket) + private static void safeClose(Socket socket) { if (socket != null) { @@ -155,13 +157,13 @@ public abstract class NanoHTTPD { socket.close(); } - catch (IOException e) + catch (IOException ignored) { } } } - private static final void safeClose(Closeable closeable) + private static void safeClose(Closeable closeable) { if (closeable != null) { @@ -169,7 +171,7 @@ public abstract class NanoHTTPD { closeable.close(); } - catch (IOException e) + catch (IOException ignored) { } } @@ -185,64 +187,56 @@ public abstract class NanoHTTPD myServerSocket = new ServerSocket(); myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); - myThread = new Thread(new Runnable() + myThread = new Thread(() -> { - @Override - public void run() + do { - do + try { - try + final Socket finalAccept = myServerSocket.accept(); + final InputStream inputStream = finalAccept.getInputStream(); + if (inputStream == null) { - final Socket finalAccept = myServerSocket.accept(); - final InputStream inputStream = finalAccept.getInputStream(); - if (inputStream == null) - { - safeClose(finalAccept); - } - else - { - asyncRunner.exec(new Runnable() - { - @Override - public void run() - { - OutputStream outputStream = null; - try - { - outputStream = finalAccept.getOutputStream(); - TempFileManager tempFileManager = tempFileManagerFactory.create(); - HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept); - while (!finalAccept.isClosed()) - { - session.execute(); - } - } - catch (Exception e) - { - // When the socket is closed by the client, we throw our own SocketException - // to break the "keep alive" loop above. - if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) - { - FLog.severe(e); - } - } - finally - { - safeClose(outputStream); - safeClose(inputStream); - safeClose(finalAccept); - } - } - }); - } + safeClose(finalAccept); } - catch (IOException e) + else { + asyncRunner.exec(() -> + { + OutputStream outputStream = null; + try + { + outputStream = finalAccept.getOutputStream(); + TempFileManager tempFileManager = tempFileManagerFactory.create(); + HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept); + while (!finalAccept.isClosed()) + { + session.execute(); + } + } + catch (Exception e) + { + // When the socket is closed by the client, we throw our own SocketException + // to break the "keep alive" loop above. + if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) + { + FLog.severe(e); + } + } + finally + { + safeClose(outputStream); + safeClose(inputStream); + safeClose(finalAccept); + } + }); } } - while (!myServerSocket.isClosed()); + catch (IOException ignored) + { + } } + while (!myServerSocket.isClosed()); }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); @@ -382,7 +376,7 @@ public abstract class NanoHTTPD String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); if (!parms.containsKey(propertyName)) { - parms.put(propertyName, new ArrayList()); + parms.put(propertyName, new ArrayList<>()); } String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null; if (propertyValue != null) @@ -573,8 +567,8 @@ public abstract class NanoHTTPD public static class DefaultTempFile implements TempFile { - private File file; - private OutputStream fstream; + private final File file; + private final OutputStream fstream; public DefaultTempFile(String tempdir) throws IOException { @@ -583,7 +577,7 @@ public abstract class NanoHTTPD } @Override - public OutputStream open() throws Exception + public OutputStream open() { return fstream; } @@ -608,6 +602,10 @@ public abstract class NanoHTTPD public static class Response { + /** + * Headers for the HTTP response. Use addHeader() to add lines. + */ + private final Map header = new HashMap<>(); /** * HTTP status code after processing, e.g. "200 OK", HTTP_OK */ @@ -620,10 +618,6 @@ public abstract class NanoHTTPD * Data of the response, may be null. */ private InputStream data; - /** - * Headers for the HTTP response. Use addHeader() to add lines. - */ - private Map header = new HashMap<>(); /** * The request method that spawned this response. */ @@ -658,14 +652,7 @@ public abstract class NanoHTTPD { this.status = status; this.mimeType = mimeType; - try - { - this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null; - } - catch (java.io.UnsupportedEncodingException uee) - { - FLog.severe(uee); - } + this.data = txt != null ? new ByteArrayInputStream(txt.getBytes(StandardCharsets.UTF_8)) : null; } /** @@ -699,18 +686,15 @@ public abstract class NanoHTTPD pw.print("Content-Type: " + mime + "\r\n"); } - if (header == null || header.get("Date") == null) + if (header.get("Date") == null) { pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n"); } - if (header != null) + for (String key : header.keySet()) { - for (String key : header.keySet()) - { - String value = header.get(key); - pw.print(key + ": " + value + "\r\n"); - } + String value = header.get(key); + pw.print(key + ": " + value + "\r\n"); } pw.print("Connection: keep-alive\r\n"); @@ -747,7 +731,7 @@ public abstract class NanoHTTPD outputStream.write(buff, 0, read); outputStream.write(CRLF); } - outputStream.write(String.format("0\r\n\r\n").getBytes()); + outputStream.write("0\r\n\r\n".getBytes()); } private void sendAsFixedLength(OutputStream outputStream, PrintWriter pw) throws IOException @@ -764,7 +748,7 @@ public abstract class NanoHTTPD byte[] buff = new byte[BUFFER_SIZE]; while (pending > 0) { - int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending)); + int read = data.read(buff, 0, (Math.min(pending, BUFFER_SIZE))); if (read <= 0) { break; @@ -876,10 +860,52 @@ public abstract class NanoHTTPD } } + public static class Cookie + { + + private final String n; + private final String v; + private final String e; + + public Cookie(String name, String value, String expires) + { + n = name; + v = value; + e = expires; + } + + public Cookie(String name, String value) + { + this(name, value, 30); + } + + public Cookie(String name, String value, int numDays) + { + n = name; + v = value; + e = getHTTPTime(numDays); + } + + public static String getHTTPTime(int days) + { + Calendar calendar = Calendar.getInstance(); + SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); + calendar.add(Calendar.DAY_OF_MONTH, days); + return dateFormat.format(calendar.getTime()); + } + + public String getHTTPHeader() + { + String fmt = "%s=%s; expires=%s"; + return String.format(fmt, n, v, e); + } + } + /** * Default strategy for creating and cleaning up temporary files. */ - private class DefaultTempFileManagerFactory implements TempFileManagerFactory + private static class DefaultTempFileManagerFactory implements TempFileManagerFactory { @Override @@ -889,6 +915,92 @@ public abstract class NanoHTTPD } } + /** + * Provides rudimentary support for cookies. Doesn't support 'path', 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported features. + * + * @author LordFokas + */ + public static class CookieHandler implements Iterable + { + + private final HashMap cookies = new HashMap<>(); + private final ArrayList queue = new ArrayList<>(); + + public CookieHandler(Map httpHeaders) + { + String raw = httpHeaders.get("cookie"); + if (raw != null) + { + String[] tokens = raw.split(";"); + for (String token : tokens) + { + String[] data = token.trim().split("="); + if (data.length == 2) + { + cookies.put(data[0], data[1]); + } + } + } + } + + @Override + public @NotNull Iterator iterator() + { + return cookies.keySet().iterator(); + } + + /** + * Read a cookie from the HTTP Headers. + * + * @param name The cookie's name. + * @return The cookie's value if it exists, null otherwise. + */ + public String read(String name) + { + return cookies.get(name); + } + + /** + * Sets a cookie. + * + * @param name The cookie's name. + * @param value The cookie's value. + * @param expires How many days until the cookie expires. + */ + public void set(String name, String value, int expires) + { + queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires))); + } + + public void set(Cookie cookie) + { + queue.add(cookie); + } + + /** + * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side. + * + * @param name The cookie name. + */ + public void delete(String name) + { + set(name, "-delete-", -30); + } + + /** + * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers. + * + * @param response The Response object to which headers the queued cookies will be added. + */ + public void unloadQueue(Response response) + { + for (Cookie cookie : queue) + { + response.addHeader("Set-Cookie", cookie.getHTTPHeader()); + } + } + } + /** * Handles one session, i.e. parses the HTTP request and returns the response. */ @@ -949,8 +1061,7 @@ public abstract class NanoHTTPD if (splitbyte < rlen) { ByteArrayInputStream splitInputStream = new ByteArrayInputStream(buf, splitbyte, rlen - splitbyte); - SequenceInputStream sequenceInputStream = new SequenceInputStream(splitInputStream, inputStream); - inputStream = sequenceInputStream; + inputStream = new SequenceInputStream(splitInputStream, inputStream); } parms = new HashMap<>(); @@ -1040,11 +1151,13 @@ public abstract class NanoHTTPD size -= rlen; if (rlen > 0) { + assert randomAccessFile != null; randomAccessFile.write(buf, 0, rlen); } } // Get the raw body as a byte [] + assert randomAccessFile != null; ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length()); randomAccessFile.seek(0); @@ -1079,7 +1192,7 @@ public abstract class NanoHTTPD String boundaryStartString = "boundary="; int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length(); - String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length()); + String boundary = contentTypeHeader.substring(boundaryContentStart); if (boundary.startsWith("\"") && boundary.endsWith("\"")) { boundary = boundary.substring(1, boundary.length() - 1); @@ -1090,16 +1203,16 @@ public abstract class NanoHTTPD else { // Handle application/x-www-form-urlencoded - String postLine = ""; - char pbuf[] = new char[512]; + StringBuilder postLine = new StringBuilder(); + char[] pbuf = new char[512]; int read = in.read(pbuf); - while (read >= 0 && !postLine.endsWith("\r\n")) + while (read >= 0 && !postLine.toString().endsWith("\r\n")) { - postLine += String.valueOf(pbuf, 0, read); + postLine.append(String.valueOf(pbuf, 0, read)); read = in.read(pbuf); } - postLine = postLine.trim(); - decodeParms(postLine, parms); + postLine = new StringBuilder(postLine.toString().trim()); + decodeParms(postLine.toString(), parms); } } else if (Method.PUT.equals(method)) @@ -1232,7 +1345,7 @@ public abstract class NanoHTTPD String pname = disposition.get("name"); pname = pname.substring(1, pname.length() - 1); - String value = ""; + StringBuilder value = new StringBuilder(); if (item.get("content-type") == null) { while (mpline != null && !mpline.contains(boundary)) @@ -1243,11 +1356,11 @@ public abstract class NanoHTTPD int d = mpline.indexOf(boundary); if (d == -1) { - value += mpline; + value.append(mpline); } else { - value += mpline.substring(0, d - 2); + value.append(mpline, 0, d - 2); } } } @@ -1261,15 +1374,15 @@ public abstract class NanoHTTPD int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]); String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4); files.put(pname, path); - value = disposition.get("filename"); - value = value.substring(1, value.length() - 1); + value = new StringBuilder(disposition.get("filename")); + value = new StringBuilder(value.substring(1, value.length() - 1)); do { mpline = in.readLine(); } while (mpline != null && !mpline.contains(boundary)); } - parms.put(pname, value); + parms.put(pname, value.toString()); } } } @@ -1462,130 +1575,4 @@ public abstract class NanoHTTPD } } - public static class Cookie - { - - private String n, v, e; - - public Cookie(String name, String value, String expires) - { - n = name; - v = value; - e = expires; - } - - public Cookie(String name, String value) - { - this(name, value, 30); - } - - public Cookie(String name, String value, int numDays) - { - n = name; - v = value; - e = getHTTPTime(numDays); - } - - public String getHTTPHeader() - { - String fmt = "%s=%s; expires=%s"; - return String.format(fmt, n, v, e); - } - - public static String getHTTPTime(int days) - { - Calendar calendar = Calendar.getInstance(); - SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); - dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - calendar.add(Calendar.DAY_OF_MONTH, days); - return dateFormat.format(calendar.getTime()); - } - } - - /** - * Provides rudimentary support for cookies. Doesn't support 'path', 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported features. - * - * @author LordFokas - */ - public class CookieHandler implements Iterable - { - - private HashMap cookies = new HashMap<>(); - private ArrayList queue = new ArrayList<>(); - - public CookieHandler(Map httpHeaders) - { - String raw = httpHeaders.get("cookie"); - if (raw != null) - { - String[] tokens = raw.split(";"); - for (String token : tokens) - { - String[] data = token.trim().split("="); - if (data.length == 2) - { - cookies.put(data[0], data[1]); - } - } - } - } - - @Override - public Iterator iterator() - { - return cookies.keySet().iterator(); - } - - /** - * Read a cookie from the HTTP Headers. - * - * @param name The cookie's name. - * @return The cookie's value if it exists, null otherwise. - */ - public String read(String name) - { - return cookies.get(name); - } - - /** - * Sets a cookie. - * - * @param name The cookie's name. - * @param value The cookie's value. - * @param expires How many days until the cookie expires. - */ - public void set(String name, String value, int expires) - { - queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires))); - } - - public void set(Cookie cookie) - { - queue.add(cookie); - } - - /** - * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side. - * - * @param name The cookie name. - */ - public void delete(String name) - { - set(name, "-delete-", -30); - } - - /** - * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers. - * - * @param response The Response object to which headers the queued cookies will be added. - */ - public void unloadQueue(Response response) - { - for (Cookie cookie : queue) - { - response.addHeader("Set-Cookie", cookie.getHTTPHeader()); - } - } - } - } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/HTTPDModule.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/HTTPDModule.java index 74b3b2da..4ea99cef 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/HTTPDModule.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/HTTPDModule.java @@ -4,7 +4,6 @@ import java.net.Socket; import java.util.HashMap; import java.util.Map; import me.totalfreedom.totalfreedommod.FreedomService; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.httpd.HTTPDPageBuilder; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.HTTPSession; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Method; @@ -21,7 +20,7 @@ public abstract class HTTPDModule extends FreedomService protected final Socket socket; protected final HTTPSession session; - public HTTPDModule(TotalFreedomMod plugin, HTTPSession session) + public HTTPDModule(HTTPSession session) { this.uri = session.getUri(); this.method = session.getMethod(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_activitylog.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_activitylog.java index 4a308179..be224bb7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_activitylog.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_activitylog.java @@ -1,18 +1,17 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.io.File; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; -import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon; -import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; import me.totalfreedom.totalfreedommod.admin.ActivityLog; import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon; +import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; public class Module_activitylog extends HTTPDModule { - public Module_activitylog(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_activitylog(NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_admins.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_admins.java index 1377d21d..f03da6bc 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_admins.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_admins.java @@ -1,15 +1,14 @@ package me.totalfreedom.totalfreedommod.httpd.module; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; -import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; public class Module_admins extends HTTPDModule { - public Module_admins(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_admins(NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_bans.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_bans.java index b1141830..182fb5a7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_bans.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_bans.java @@ -1,15 +1,14 @@ package me.totalfreedom.totalfreedommod.httpd.module; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; -import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; import me.totalfreedom.totalfreedommod.admin.Admin; +import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; public class Module_bans extends HTTPDModule { - public Module_bans(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_bans(NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_file.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_file.java index c8f09c15..da43ca2c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_file.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_file.java @@ -2,7 +2,6 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.io.File; import java.io.FileInputStream; -import java.io.FilenameFilter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @@ -12,7 +11,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; @@ -25,7 +23,6 @@ import org.apache.commons.lang3.StringUtils; public class Module_file extends HTTPDModule { - private final File rootDir = new File(ConfigEntry.HTTPD_PUBLIC_FOLDER.getString()); public static final Map MIME_TYPES = new HashMap<>(); static @@ -58,9 +55,11 @@ public class Module_file extends HTTPDModule MIME_TYPES.put("class", "application/octet-stream"); } - public Module_file(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + private final File rootDir = new File(ConfigEntry.HTTPD_PUBLIC_FOLDER.getString()); + + public Module_file(NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } private File getRootDir() @@ -70,31 +69,31 @@ public class Module_file extends HTTPDModule private String encodeUri(String uri) { - String newUri = ""; + StringBuilder newUri = new StringBuilder(); StringTokenizer st = new StringTokenizer(uri, "/ ", true); while (st.hasMoreTokens()) { String tok = st.nextToken(); if (tok.equals("/")) { - newUri += "/"; + newUri.append("/"); } else if (tok.equals(" ")) { - newUri += "%20"; + newUri.append("%20"); } else { try { - newUri += URLEncoder.encode(tok, "UTF-8"); + newUri.append(URLEncoder.encode(tok, "UTF-8")); } catch (UnsupportedEncodingException ignored) { } } } - return newUri; + return newUri.toString(); } public Response serveFile(String uri, Map params, File homeDir) @@ -237,7 +236,6 @@ public class Module_file extends HTTPDModule { res = new Response(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, ""); res.addHeader("Content-Range", "bytes 0-0/" + fileLen); - res.addHeader("ETag", etag); } else { @@ -255,25 +253,25 @@ public class Module_file extends HTTPDModule FileInputStream fis = new FileInputStream(f) { @Override - public int available() throws IOException + public int available() { return (int)dataLen; } }; + //noinspection ResultOfMethodCallIgnored fis.skip(startFrom); res = new Response(Response.Status.PARTIAL_CONTENT, mime, fis); res.addHeader("Content-Length", "" + dataLen); res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen); - res.addHeader("ETag", etag); } } else { res = new Response(Response.Status.OK, mime, new FileInputStream(f)); res.addHeader("Content-Length", "" + fileLen); - res.addHeader("ETag", etag); } + res.addHeader("ETag", etag); } } catch (IOException ioe) @@ -288,12 +286,12 @@ public class Module_file extends HTTPDModule private String listDirectory(String uri, File f) { String heading = "Directory " + uri; - String msg = "" + heading + "" - + "

    " + heading + "

    "; + + "

    " + heading + "

    "); String up = null; if (uri.length() > 1) @@ -306,72 +304,56 @@ public class Module_file extends HTTPDModule } } - List files = Arrays.asList(f.list(new FilenameFilter() - { - @Override - public boolean accept(File dir, String name) - { - return new File(dir, name).isFile(); - } - })); + List files = Arrays.asList(f.list((dir, name) -> new File(dir, name).isFile())); Collections.sort(files); - List directories = Arrays.asList(f.list(new FilenameFilter() - { - @Override - public boolean accept(File dir, String name) - { - return new File(dir, name).isDirectory(); - } - })); + List directories = Arrays.asList(f.list((dir, name) -> new File(dir, name).isDirectory())); Collections.sort(directories); if (up != null || directories.size() + files.size() > 0) { - msg += "
      "; + msg.append("
        "); if (up != null || directories.size() > 0) { - msg += "
        "; + msg.append("
        "); if (up != null) { - msg += "
      • ..
      • "; + msg.append("
      • ..
      • "); } - for (int i = 0; i < directories.size(); i++) + for (String directory : directories) { - String dir = directories.get(i) + "/"; - msg += "
      • " + dir + "
      • "; + String dir = directory + "/"; + msg.append("
      • ").append(dir).append("
      • "); } - msg += "
        "; + msg.append("
        "); } if (files.size() > 0) { - msg += "
        "; - for (int i = 0; i < files.size(); i++) + msg.append("
        "); + for (String file : files) { - String file = files.get(i); - - msg += "
      • " + file + ""; + msg.append("
      • ").append(file).append(""); File curFile = new File(f, file); long len = curFile.length(); - msg += " ("; + msg.append(" ("); if (len < 1024) { - msg += len + " bytes"; + msg.append(len).append(" bytes"); } else if (len < 1024 * 1024) { - msg += len / 1024 + "." + (len % 1024 / 10 % 100) + " KB"; + msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB"); } else { - msg += len / (1024 * 1024) + "." + len % (1024 * 1024) / 10 % 100 + " MB"; + msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10 % 100).append(" MB"); } - msg += ")
      • "; + msg.append(")"); } - msg += "
        "; + msg.append("
        "); } - msg += "
      "; + msg.append("
    "); } - msg += ""; - return msg; + msg.append(""); + return msg.toString(); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_help.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_help.java index 19afdd68..d19849be 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_help.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_help.java @@ -2,12 +2,11 @@ package me.totalfreedom.totalfreedommod.httpd.module; import com.google.common.collect.Lists; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.command.FreedomCommand; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; @@ -24,16 +23,39 @@ import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4; public class Module_help extends HTTPDModule { - public Module_help(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_help(NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); + } + + private static String buildDescription(Command command) + { + StringBuilder sb = new StringBuilder(); + + sb.append( + "
  • {$CMD_NAME} - Usage: {$CMD_USAGE}" + .replace("{$CMD_NAME}", escapeHtml4(command.getName().trim())) + .replace("{$CMD_USAGE}", escapeHtml4(command.getUsage().trim()))); + + if (!command.getAliases().isEmpty()) + { + sb.append( + " - Aliases: {$CMD_ALIASES}" + .replace("{$CMD_ALIASES}", escapeHtml4(StringUtils.join(command.getAliases(), ", ")))); + } + + sb.append( + "
    {$CMD_DESC}
  • \r\n" + .replace("{$CMD_DESC}", escapeHtml4(command.getDescription().trim()))); + + return sb.toString(); } @Override public String getBody() { final CommandMap map = FreedomCommand.getCommandMap(); - if (map == null || !(map instanceof SimpleCommandMap)) + if (!(map instanceof SimpleCommandMap)) { return paragraph("Error loading commands."); } @@ -60,14 +82,12 @@ public class Module_help extends HTTPDModule pluginCommands.add(command); } - final Iterator>> it = commandsByPlugin.entrySet().iterator(); - while (it.hasNext()) + for (Map.Entry> entry : commandsByPlugin.entrySet()) { - final Map.Entry> entry = it.next(); final String pluginName = entry.getKey(); final List commands = entry.getValue(); - Collections.sort(commands, new CommandComparator()); + commands.sort(new CommandComparator()); responseBody.append(heading(pluginName, 2)).append("
      \r\n"); @@ -80,7 +100,7 @@ public class Module_help extends HTTPDModule continue; } - Displayable tfmCommandLevel = FreedomCommand.getFrom(command).getPerms().level(); + Displayable tfmCommandLevel = Objects.requireNonNull(FreedomCommand.getFrom(command)).getPerms().level(); if (lastTfmCommandLevel == null || lastTfmCommandLevel != tfmCommandLevel) { responseBody.append("
    \r\n").append(heading(tfmCommandLevel.getName(), 3)).append("
      \r\n"); @@ -95,29 +115,6 @@ public class Module_help extends HTTPDModule return responseBody.toString(); } - private static String buildDescription(Command command) - { - StringBuilder sb = new StringBuilder(); - - sb.append( - "
    • {$CMD_NAME} - Usage: {$CMD_USAGE}" - .replace("{$CMD_NAME}", escapeHtml4(command.getName().trim())) - .replace("{$CMD_USAGE}", escapeHtml4(command.getUsage().trim()))); - - if (!command.getAliases().isEmpty()) - { - sb.append( - " - Aliases: {$CMD_ALIASES}" - .replace("{$CMD_ALIASES}", escapeHtml4(StringUtils.join(command.getAliases(), ", ")))); - } - - sb.append( - "
      {$CMD_DESC}
    • \r\n" - .replace("{$CMD_DESC}", escapeHtml4(command.getDescription().trim()))); - - return sb.toString(); - } - @Override public String getTitle() { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_indefbans.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_indefbans.java index 6940d628..6cb89393 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_indefbans.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_indefbans.java @@ -1,18 +1,17 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.io.File; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.banning.IndefiniteBanList; import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; -import me.totalfreedom.totalfreedommod.admin.Admin; public class Module_indefbans extends HTTPDModule { - public Module_indefbans(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_indefbans(NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_index.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_index.java index 8b3fb66b..7c7beabd 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_index.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_index.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.util.Set; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.HTMLGenerationTools; import me.totalfreedom.totalfreedommod.httpd.HTTPDPageBuilder; @@ -11,9 +10,9 @@ import org.reflections.Reflections; public class Module_index extends HTTPDModule { - public Module_index(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_index(NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override @@ -32,7 +31,7 @@ public class Module_index extends HTTPDModule Set> moduleClasses = r.getSubTypesOf(HTTPDModule.class); - for (Class c : moduleClasses) + for (Class c : moduleClasses) { String name = c.getSimpleName().replace("Module_", ""); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_list.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_list.java index fd44b4d6..95101727 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_list.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_list.java @@ -2,9 +2,9 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.util.Collection; import me.totalfreedom.totalfreedommod.TotalFreedomMod; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -16,7 +16,7 @@ public class Module_list extends HTTPDModule public Module_list(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logfile.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logfile.java index 8c964833..7015be7e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logfile.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logfile.java @@ -7,13 +7,13 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; import me.totalfreedom.totalfreedommod.TotalFreedomMod; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.HTMLGenerationTools; import me.totalfreedom.totalfreedommod.httpd.HTTPDPageBuilder; import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Response; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FLog; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringEscapeUtils; @@ -31,7 +31,13 @@ public class Module_logfile extends HTTPDModule public Module_logfile(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); + } + + private static String getArg(String[] args, int index) + { + String out = (args.length == index + 1 ? args[index] : null); + return (out == null ? null : (out.trim().isEmpty() ? null : out.trim())); } @Override @@ -169,6 +175,40 @@ public class Module_logfile extends HTTPDModule return entry != null && entry.isActive(); } + private enum ModuleMode + { + + LIST("list"), + DOWNLOAD("download"), + INVALID(null); + // + private final String modeName; + + ModuleMode(String modeName) + { + this.modeName = modeName; + } + + public static ModuleMode getMode(String needle) + { + for (ModuleMode mode : values()) + { + final String haystack = mode.toString(); + if (haystack != null && haystack.equalsIgnoreCase(needle)) + { + return mode; + } + } + return INVALID; + } + + @Override + public String toString() + { + return this.modeName; + } + } + private static class LogFileTransferException extends Exception { @@ -197,44 +237,4 @@ public class Module_logfile extends HTTPDModule return response; } } - - private static String getArg(String[] args, int index) - { - String out = (args.length == index + 1 ? args[index] : null); - return (out == null ? null : (out.trim().isEmpty() ? null : out.trim())); - } - - private static enum ModuleMode - { - - LIST("list"), - DOWNLOAD("download"), - INVALID(null); - // - private final String modeName; - - private ModuleMode(String modeName) - { - this.modeName = modeName; - } - - @Override - public String toString() - { - return this.modeName; - } - - public static ModuleMode getMode(String needle) - { - for (ModuleMode mode : values()) - { - final String haystack = mode.toString(); - if (haystack != null && haystack.equalsIgnoreCase(needle)) - { - return mode; - } - } - return INVALID; - } - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java index de2a0c4d..fce7c782 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java @@ -1,9 +1,9 @@ package me.totalfreedom.totalfreedommod.httpd.module; import me.totalfreedom.totalfreedommod.TotalFreedomMod; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -15,7 +15,7 @@ public class Module_players extends HTTPDModule public Module_players(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java index 88e192d9..4ce57158 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java @@ -2,17 +2,17 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.io.File; import me.totalfreedom.totalfreedommod.TotalFreedomMod; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; import me.totalfreedom.totalfreedommod.punishments.PunishmentList; -import me.totalfreedom.totalfreedommod.admin.Admin; public class Module_punishments extends HTTPDModule { public Module_punishments(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java index 0c42ae66..9a251b88 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java @@ -14,6 +14,7 @@ import java.util.List; import java.util.Map; import java.util.regex.Pattern; import me.totalfreedom.totalfreedommod.TotalFreedomMod; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.HTMLGenerationTools; import me.totalfreedom.totalfreedommod.httpd.HTTPDPageBuilder; @@ -22,7 +23,6 @@ import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Method; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Response; import me.totalfreedom.totalfreedommod.player.PlayerData; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FLog; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringEscapeUtils; @@ -48,7 +48,13 @@ public class Module_schematic extends HTTPDModule public Module_schematic(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); + } + + private static String getArg(String[] args, int index) + { + String out = (args.length == index + 1 ? args[index] : null); + return (out == null ? null : (out.trim().isEmpty() ? null : out.trim())); } @Override @@ -285,6 +291,41 @@ public class Module_schematic extends HTTPDModule return ((adminEntry != null && adminEntry.isActive()) || data != null && data.isMasterBuilder()); } + private enum ModuleMode + { + + LIST("list"), + UPLOAD("upload"), + DOWNLOAD("download"), + INVALID(null); + // + private final String modeName; + + ModuleMode(String modeName) + { + this.modeName = modeName; + } + + public static ModuleMode getMode(String needle) + { + for (ModuleMode mode : values()) + { + final String haystack = mode.toString(); + if (haystack != null && haystack.equalsIgnoreCase(needle)) + { + return mode; + } + } + return INVALID; + } + + @Override + public String toString() + { + return this.modeName; + } + } + private static class SchematicTransferException extends Exception { @@ -313,45 +354,4 @@ public class Module_schematic extends HTTPDModule return response; } } - - private static String getArg(String[] args, int index) - { - String out = (args.length == index + 1 ? args[index] : null); - return (out == null ? null : (out.trim().isEmpty() ? null : out.trim())); - } - - private static enum ModuleMode - { - - LIST("list"), - UPLOAD("upload"), - DOWNLOAD("download"), - INVALID(null); - // - private final String modeName; - - ModuleMode(String modeName) - { - this.modeName = modeName; - } - - @Override - public String toString() - { - return this.modeName; - } - - public static ModuleMode getMode(String needle) - { - for (ModuleMode mode : values()) - { - final String haystack = mode.toString(); - if (haystack != null && haystack.equalsIgnoreCase(needle)) - { - return mode; - } - } - return INVALID; - } - } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionConfig.java b/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionConfig.java index 77ea542b..bfc3d3c4 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionConfig.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionConfig.java @@ -7,7 +7,6 @@ import java.io.InputStreamReader; import java.util.EnumMap; import java.util.List; import me.totalfreedom.totalfreedommod.FreedomService; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.util.FLog; import org.apache.commons.io.FileUtils; import org.bukkit.configuration.InvalidConfigurationException; @@ -18,10 +17,9 @@ public class PermissionConfig extends FreedomService public static final String PERMISSIONS_FILENAME = "permissions.yml"; // private final EnumMap entries; - private final PermissionDefaults defaults; public YamlConfiguration configuration; - public PermissionConfig(TotalFreedomMod plugin) + public PermissionConfig() { entries = new EnumMap<>(PermissionEntry.class); @@ -53,7 +51,7 @@ public class PermissionConfig extends FreedomService FLog.severe(ex); } - defaults = tempDefaults; + PermissionDefaults defaults = tempDefaults; } @Override @@ -104,7 +102,7 @@ public class PermissionConfig extends FreedomService return new File(plugin.getDataFolder(), PERMISSIONS_FILENAME); } - public List getList(PermissionEntry entry) + public List getList(PermissionEntry entry) { try { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionEntry.java b/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionEntry.java index eaedc006..fc7a3b98 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionEntry.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionEntry.java @@ -1,6 +1,7 @@ package me.totalfreedom.totalfreedommod.permissions; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; public enum PermissionEntry @@ -36,6 +37,6 @@ public enum PermissionEntry private PermissionConfig getConfig() { - return TotalFreedomMod.plugin().permissions; + return Objects.requireNonNull(TotalFreedomMod.plugin()).permissions; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/player/FPlayer.java b/src/main/java/me/totalfreedom/totalfreedommod/player/FPlayer.java index 17a6c13f..5b7bca92 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/player/FPlayer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/player/FPlayer.java @@ -2,8 +2,6 @@ package me.totalfreedom.totalfreedommod.player; import java.util.ArrayList; import java.util.List; -import lombok.Getter; -import lombok.Setter; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.caging.CageData; import me.totalfreedom.totalfreedommod.config.ConfigEntry; @@ -20,37 +18,32 @@ import org.bukkit.scheduler.BukkitTask; public class FPlayer { - public static final long AUTO_PURGE_TICKS = 5L * 60L * 20L; - @Getter + private final TotalFreedomMod plugin; - @Getter + private final String name; - @Getter + private final String ip; // - @Setter + private final FreezeData freezeData = new FreezeData(this); + private final CageData cageData = new CageData(this); + private final List mobThrowerQueue = new ArrayList<>(); private Player player; // private BukkitTask unmuteTask; - @Getter - private final FreezeData freezeData = new FreezeData(this); - @Getter private double fuckoffRadius = 0; private int messageCount = 0; private int totalBlockDestroy = 0; private int totalBlockPlace = 0; private int freecamDestroyCount = 0; private int freecamPlaceCount = 0; - @Getter - private final CageData cageData = new CageData(this); private boolean isOrbiting = false; private double orbitStrength = 10.0; private boolean mobThrowerEnabled = false; private EntityType mobThrowerEntity = EntityType.PIG; private double mobThrowerSpeed = 4.0; - private final List mobThrowerQueue = new ArrayList<>(); private BukkitTask mp44ScheduleTask = null; private boolean mp44Armed = false; private boolean mp44Firing = false; @@ -59,21 +52,21 @@ public class FPlayer private String lastMessage = ""; private boolean inAdminchat = false; private boolean allCommandsBlocked = false; - @Getter - @Setter + + private boolean superadminIdVerified = false; private String lastCommand = ""; private boolean cmdspyEnabled = false; private String tag = null; private int warningCount = 0; - @Getter - @Setter + + private boolean editBlocked = false; - @Getter - @Setter + + private boolean pvpBlocked = false; - @Getter - @Setter + + private boolean invSee = false; public FPlayer(TotalFreedomMod plugin, Player player) @@ -88,6 +81,11 @@ public class FPlayer this.ip = ip; } + public static long getAutoPurgeTicks() + { + return AUTO_PURGE_TICKS; + } + public Player getPlayer() { if (player != null && !player.isOnline()) @@ -110,11 +108,21 @@ public class FPlayer return player; } + public void setPlayer(Player player) + { + this.player = player; + } + public boolean isOrbiting() { return isOrbiting; } + public void setOrbiting(boolean orbiting) + { + isOrbiting = orbiting; + } + public void startOrbiting(double strength) { this.isOrbiting = true; @@ -299,6 +307,7 @@ public class FPlayer plugin.mu.MUTED_PLAYERS.add(getPlayer().getName()); + // TODO: Simplify this into a Consumer lambda? unmuteTask = new BukkitRunnable() { @Override @@ -338,16 +347,16 @@ public class FPlayer this.lockedUp = lockedUp; } - public void setLastMessage(String message) - { - this.lastMessage = message; - } - public String getLastMessage() { return lastMessage; } + public void setLastMessage(String message) + { + this.lastMessage = message; + } + public void setAdminChat(boolean inAdminchat) { this.inAdminchat = inAdminchat; @@ -388,6 +397,11 @@ public class FPlayer return cmdspyEnabled; } + public String getTag() + { + return this.tag; + } + public void setTag(String tag) { if (tag == null) @@ -400,16 +414,16 @@ public class FPlayer } } - public String getTag() - { - return this.tag; - } - public int getWarningCount() { return this.warningCount; } + public void setWarningCount(int warningCount) + { + this.warningCount = warningCount; + } + public void incrementWarnings() { this.warningCount++; @@ -422,7 +436,257 @@ public class FPlayer } } - private class ArrowShooter extends BukkitRunnable + public TotalFreedomMod getPlugin() + { + return plugin; + } + + public String getName() + { + return name; + } + + public String getIp() + { + return ip; + } + + public BukkitTask getUnmuteTask() + { + return unmuteTask; + } + + public void setUnmuteTask(BukkitTask unmuteTask) + { + this.unmuteTask = unmuteTask; + } + + public FreezeData getFreezeData() + { + return freezeData; + } + + public double getFuckoffRadius() + { + return fuckoffRadius; + } + + public void setFuckoffRadius(double fuckoffRadius) + { + this.fuckoffRadius = fuckoffRadius; + } + + public int getMessageCount() + { + return messageCount; + } + + public void setMessageCount(int messageCount) + { + this.messageCount = messageCount; + } + + public int getTotalBlockDestroy() + { + return totalBlockDestroy; + } + + public void setTotalBlockDestroy(int totalBlockDestroy) + { + this.totalBlockDestroy = totalBlockDestroy; + } + + public int getTotalBlockPlace() + { + return totalBlockPlace; + } + + public void setTotalBlockPlace(int totalBlockPlace) + { + this.totalBlockPlace = totalBlockPlace; + } + + public int getFreecamDestroyCount() + { + return freecamDestroyCount; + } + + public void setFreecamDestroyCount(int freecamDestroyCount) + { + this.freecamDestroyCount = freecamDestroyCount; + } + + public int getFreecamPlaceCount() + { + return freecamPlaceCount; + } + + public void setFreecamPlaceCount(int freecamPlaceCount) + { + this.freecamPlaceCount = freecamPlaceCount; + } + + public CageData getCageData() + { + return cageData; + } + + public double getOrbitStrength() + { + return orbitStrength; + } + + public void setOrbitStrength(double orbitStrength) + { + this.orbitStrength = orbitStrength; + } + + public boolean isMobThrowerEnabled() + { + return mobThrowerEnabled; + } + + public void setMobThrowerEnabled(boolean mobThrowerEnabled) + { + this.mobThrowerEnabled = mobThrowerEnabled; + } + + public EntityType getMobThrowerEntity() + { + return mobThrowerEntity; + } + + public void setMobThrowerEntity(EntityType mobThrowerEntity) + { + this.mobThrowerEntity = mobThrowerEntity; + } + + public double getMobThrowerSpeed() + { + return mobThrowerSpeed; + } + + public void setMobThrowerSpeed(double mobThrowerSpeed) + { + this.mobThrowerSpeed = mobThrowerSpeed; + } + + public List getMobThrowerQueue() + { + return mobThrowerQueue; + } + + public BukkitTask getMp44ScheduleTask() + { + return mp44ScheduleTask; + } + + public void setMp44ScheduleTask(BukkitTask mp44ScheduleTask) + { + this.mp44ScheduleTask = mp44ScheduleTask; + } + + public boolean isMp44Armed() + { + return mp44Armed; + } + + public void setMp44Armed(boolean mp44Armed) + { + this.mp44Armed = mp44Armed; + } + + public boolean isMp44Firing() + { + return mp44Firing; + } + + public void setMp44Firing(boolean mp44Firing) + { + this.mp44Firing = mp44Firing; + } + + public BukkitTask getLockupScheduleTask() + { + return lockupScheduleTask; + } + + public void setLockupScheduleTask(BukkitTask lockupScheduleTask) + { + this.lockupScheduleTask = lockupScheduleTask; + } + + public boolean isInAdminchat() + { + return inAdminchat; + } + + public void setInAdminchat(boolean inAdminchat) + { + this.inAdminchat = inAdminchat; + } + + public boolean isAllCommandsBlocked() + { + return allCommandsBlocked; + } + + public void setAllCommandsBlocked(boolean allCommandsBlocked) + { + this.allCommandsBlocked = allCommandsBlocked; + } + + public boolean isSuperadminIdVerified() + { + return superadminIdVerified; + } + + public void setSuperadminIdVerified(boolean superadminIdVerified) + { + this.superadminIdVerified = superadminIdVerified; + } + + public boolean isCmdspyEnabled() + { + return cmdspyEnabled; + } + + public void setCmdspyEnabled(boolean cmdspyEnabled) + { + this.cmdspyEnabled = cmdspyEnabled; + } + + public boolean isEditBlocked() + { + return editBlocked; + } + + public void setEditBlocked(boolean editBlocked) + { + this.editBlocked = editBlocked; + } + + public boolean isPvpBlocked() + { + return pvpBlocked; + } + + public void setPvpBlocked(boolean pvpBlocked) + { + this.pvpBlocked = pvpBlocked; + } + + public boolean isInvSee() + { + return invSee; + } + + public void setInvSee(boolean invSee) + { + this.invSee = invSee; + } + + private static class ArrowShooter extends BukkitRunnable { private final Player player; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java b/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java index f780d7ac..6fedb107 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java @@ -7,8 +7,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import lombok.Getter; -import lombok.Setter; +import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.shop.ShopItem; import me.totalfreedom.totalfreedommod.util.FLog; @@ -19,38 +18,31 @@ import org.bukkit.entity.Player; public class PlayerData { - @Getter - @Setter - private String name; private final List ips = Lists.newArrayList(); private final List notes = Lists.newArrayList(); - @Getter - @Setter - private String tag = null; - @Getter - @Setter - private String discordID = null; private final List backupCodes = Lists.newArrayList(); - @Setter + private String name; + private String tag = null; + private String discordID = null; private Boolean masterBuilder = false; - @Setter + private Boolean verification = false; - @Getter - @Setter + + private String rideMode = "ask"; - @Getter - @Setter + + private int coins; private List items = Lists.newArrayList(); - @Getter - @Setter + + private int totalVotes; - @Setter + private boolean displayDiscord = true; - @Getter - @Setter + + private String loginMessage; - @Setter + private Boolean inspect = false; public PlayerData(ResultSet resultSet) @@ -86,41 +78,38 @@ public class PlayerData if (masterBuilder && !verification) { verification = true; - TotalFreedomMod.plugin().pl.save(this); + Objects.requireNonNull(TotalFreedomMod.plugin()).pl.save(this); } else if (!masterBuilder && discordID == null && verification) { this.verification = false; - TotalFreedomMod.plugin().pl.save(this); + Objects.requireNonNull(TotalFreedomMod.plugin()).pl.save(this); } } - @Override - public String toString() - { - final StringBuilder output = new StringBuilder(); - - output.append("Player: ").append(name).append("\n") - .append("- IPs: ").append(StringUtils.join(ips, ", ")).append("\n") - .append("- Discord ID: ").append(discordID).append("\n") - .append("- Master Builder: ").append(masterBuilder).append("\n") - .append("- Has Verification: ").append(verification).append("\n") - .append("- Coins: ").append(coins).append("\n") - .append("- Total Votes: ").append(totalVotes).append("\n") - .append("- Display Discord: ").append(displayDiscord).append("\n") - .append("- Tag: ").append(FUtil.colorize(tag)).append(ChatColor.GRAY).append("\n") - .append("- Ride Mode: ").append(rideMode).append("\n") - .append("- Backup Codes: ").append(backupCodes.size()).append("/10").append("\n") - .append("- Login Message: ").append(loginMessage); - - return output.toString(); - } - public PlayerData(Player player) { this.name = player.getName(); } + @Override + public String toString() + { + + return "Player: " + name + "\n" + + "- IPs: " + StringUtils.join(ips, ", ") + "\n" + + "- Discord ID: " + discordID + "\n" + + "- Master Builder: " + masterBuilder + "\n" + + "- Has Verification: " + verification + "\n" + + "- Coins: " + coins + "\n" + + "- Total Votes: " + totalVotes + "\n" + + "- Display Discord: " + displayDiscord + "\n" + + "- Tag: " + FUtil.colorize(tag) + ChatColor.GRAY + "\n" + + "- Ride Mode: " + rideMode + "\n" + + "- Backup Codes: " + backupCodes.size() + "/10" + "\n" + + "- Login Message: " + loginMessage; + } + public List getIps() { return Collections.unmodifiableList(ips); @@ -133,7 +122,12 @@ public class PlayerData public boolean addIp(String ip) { - return !ips.contains(ip) && ips.add(ip); + if (ips.contains(ip)) + { + return false; + } + ips.add(ip); + return true; } public void removeIp(String ip) @@ -148,7 +142,7 @@ public class PlayerData public void addIps(List ips) { - ips.addAll(ips); + this.ips.addAll(ips); } public List getNotes() @@ -205,13 +199,14 @@ public class PlayerData return Collections.unmodifiableList(items); } + public void setItems(List items) + { + this.items = items; + } + public boolean hasItem(ShopItem item) { - if (items.contains(item.getDataName())) - { - return true; - } - return false; + return items.contains(item.getDataName()); } public void removeItem(ShopItem item) @@ -236,7 +231,7 @@ public class PlayerData public Map toSQLStorable() { - Map map = new HashMap() + return new HashMap() {{ put("username", name); put("ips", FUtil.listToString(ips)); @@ -254,11 +249,120 @@ public class PlayerData put("login_message", loginMessage); put("inspect", inspect); }}; - return map; } public boolean doesDisplayDiscord() { return displayDiscord; } + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public String getTag() + { + return tag; + } + + public void setTag(String tag) + { + this.tag = tag; + } + + public String getDiscordID() + { + return discordID; + } + + public void setDiscordID(String discordID) + { + this.discordID = discordID; + } + + public Boolean getMasterBuilder() + { + return masterBuilder; + } + + public void setMasterBuilder(Boolean masterBuilder) + { + this.masterBuilder = masterBuilder; + } + + public Boolean getVerification() + { + return verification; + } + + public void setVerification(Boolean verification) + { + this.verification = verification; + } + + public String getRideMode() + { + return rideMode; + } + + public void setRideMode(String rideMode) + { + this.rideMode = rideMode; + } + + public int getCoins() + { + return coins; + } + + public void setCoins(int coins) + { + this.coins = coins; + } + + public int getTotalVotes() + { + return totalVotes; + } + + public void setTotalVotes(int totalVotes) + { + this.totalVotes = totalVotes; + } + + public boolean isDisplayDiscord() + { + return displayDiscord; + } + + public void setDisplayDiscord(boolean displayDiscord) + { + this.displayDiscord = displayDiscord; + } + + public String getLoginMessage() + { + return loginMessage; + } + + public void setLoginMessage(String loginMessage) + { + this.loginMessage = loginMessage; + } + + public Boolean getInspect() + { + return inspect; + } + + public void setInspect(Boolean inspect) + { + this.inspect = inspect; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerList.java b/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerList.java index bc17fa03..7bdc0f31 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerList.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerList.java @@ -7,11 +7,12 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Objects; import lombok.Getter; import me.totalfreedom.totalfreedommod.FreedomService; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.rank.Rank; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; import org.bukkit.OfflinePlayer; @@ -73,7 +74,7 @@ public class PlayerList extends FreedomService { if (player.isOnline()) { - return FUtil.getIp(player.getPlayer()); + return FUtil.getIp(Objects.requireNonNull(player.getPlayer())); } final PlayerData entry = getData(player.getName()); @@ -98,25 +99,16 @@ public class PlayerList extends FreedomService { PlayerData data = getData(name); - if ((!ConfigEntry.HOST_SENDER_NAMES.getStringList().contains(name.toLowerCase()) && data != null && !ConfigEntry.SERVER_OWNERS.getStringList().contains(data.getName())) + return (!ConfigEntry.HOST_SENDER_NAMES.getStringList().contains(name.toLowerCase()) && data != null && !ConfigEntry.SERVER_OWNERS.getStringList().contains(data.getName())) && !ConfigEntry.SERVER_EXECUTIVES.getStringList().contains(data.getName()) && !isTelnetMasterBuilder(data) - && !ConfigEntry.HOST_SENDER_NAMES.getStringList().contains(name.toLowerCase())) - { - return false; - } - return true; + && !ConfigEntry.HOST_SENDER_NAMES.getStringList().contains(name.toLowerCase()); } public boolean isTelnetMasterBuilder(PlayerData playerData) { Admin admin = plugin.al.getEntryByName(playerData.getName()); - if (admin != null && admin.getRank().isAtLeast(Rank.ADMIN) && playerData.isMasterBuilder()) - { - return true; - } - - return false; + return admin != null && admin.getRank().isAtLeast(Rank.ADMIN) && playerData.isMasterBuilder(); } // May not return null @@ -262,23 +254,19 @@ public class PlayerList extends FreedomService } // Create new data if nonexistent - if (playerData == null) - { - FLog.info("Creating new player verification entry for " + player.getName()); + FLog.info("Creating new player verification entry for " + player.getName()); - // Create new player - playerData = new PlayerData(player); - playerData.addIp(FUtil.getIp(player)); + // Create new player + playerData = new PlayerData(player); + playerData.addIp(FUtil.getIp(player)); - // Store player - dataMap.put(player.getName(), playerData); + // Store player + dataMap.put(player.getName(), playerData); - // Save player - plugin.sql.addPlayer(playerData); - return playerData; - } + // Save player + plugin.sql.addPlayer(playerData); + return playerData; - return null; } public PlayerData getData(String username) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/punishments/Punishment.java b/src/main/java/me/totalfreedom/totalfreedommod/punishments/Punishment.java index f315f30f..51c90da8 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/punishments/Punishment.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/punishments/Punishment.java @@ -3,32 +3,30 @@ package me.totalfreedom.totalfreedommod.punishments; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -import lombok.Getter; -import lombok.Setter; +import java.util.Objects; import me.totalfreedom.totalfreedommod.config.IConfig; import org.bukkit.configuration.ConfigurationSection; public class Punishment implements IConfig { - public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd \'at\' HH:mm:ss z"); + public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); + - @Getter - @Setter private String username = null; - @Getter + private String ip = null; - @Getter - @Setter + + private String by = null; - @Getter - @Setter + + private PunishmentType type = null; - @Getter - @Setter + + private String reason = null; - @Getter - @Setter + + private Date issued_on = null; public Punishment() @@ -45,13 +43,18 @@ public class Punishment implements IConfig this.issued_on = new Date(); } + public static SimpleDateFormat getDateFormat() + { + return DATE_FORMAT; + } + @Override public void loadFrom(ConfigurationSection cs) { this.username = cs.getString("username", null); this.ip = cs.getString("ip", null); this.by = cs.getString("by", null); - this.type = PunishmentType.valueOf(cs.getString("type", null).toUpperCase()); + this.type = PunishmentType.valueOf(Objects.requireNonNull(cs.getString("type", null)).toUpperCase()); this.reason = cs.getString("reason", null); try { @@ -63,7 +66,6 @@ public class Punishment implements IConfig } } - @Override public void saveTo(ConfigurationSection cs) { @@ -80,4 +82,64 @@ public class Punishment implements IConfig { return username != null || ip != null; } + + public String getUsername() + { + return username; + } + + public void setUsername(String username) + { + this.username = username; + } + + public String getIp() + { + return ip; + } + + public void setIp(String ip) + { + this.ip = ip; + } + + public String getBy() + { + return by; + } + + public void setBy(String by) + { + this.by = by; + } + + public PunishmentType getType() + { + return type; + } + + public void setType(PunishmentType type) + { + this.type = type; + } + + public String getReason() + { + return reason; + } + + public void setReason(String reason) + { + this.reason = reason; + } + + public Date getIssued_on() + { + return issued_on; + } + + public void setIssued_on(Date issued_on) + { + this.issued_on = issued_on; + } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/punishments/PunishmentList.java b/src/main/java/me/totalfreedom/totalfreedommod/punishments/PunishmentList.java index dd6938c0..b18952cb 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/punishments/PunishmentList.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/punishments/PunishmentList.java @@ -3,6 +3,7 @@ package me.totalfreedom.totalfreedommod.punishments; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Set; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.YamlConfig; @@ -11,9 +12,8 @@ import me.totalfreedom.totalfreedommod.util.FLog; public class PunishmentList extends FreedomService { - private final Set punishments = Sets.newHashSet(); public static final String CONFIG_FILENAME = "punishments.yml"; - + private final Set punishments = Sets.newHashSet(); // private final YamlConfig config; @@ -37,7 +37,7 @@ public class PunishmentList extends FreedomService } Punishment punishment = new Punishment(); - punishment.loadFrom(config.getConfigurationSection(id)); + punishment.loadFrom(Objects.requireNonNull(config.getConfigurationSection(id))); if (!punishment.isValid()) { @@ -55,7 +55,7 @@ public class PunishmentList extends FreedomService public void onStop() { saveAll(); - logger.info("Saved " + punishments.size() + " player bans"); + FLog.info("Saved " + punishments.size() + " player bans"); } public void saveAll() @@ -113,15 +113,13 @@ public class PunishmentList extends FreedomService return size; } - public boolean logPunishment(Punishment punishment) + public void logPunishment(Punishment punishment) { if (punishments.add(punishment)) { saveAll(); - return true; } - return false; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/rank/Rank.java b/src/main/java/me/totalfreedom/totalfreedommod/rank/Rank.java index 06c9cbaa..b7ebb707 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/rank/Rank.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/rank/Rank.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.rank; -import lombok.Getter; import net.md_5.bungee.api.ChatColor; public enum Rank implements Displayable @@ -12,25 +11,25 @@ public enum Rank implements Displayable SENIOR_ADMIN("a", "Senior Admin", Type.ADMIN, "SrA", ChatColor.GOLD, org.bukkit.ChatColor.GOLD, true, true), ADMIN_CONSOLE("the", "Console", Type.ADMIN_CONSOLE, "Console", ChatColor.DARK_PURPLE, null, false, false), SENIOR_CONSOLE("the", "Console", Type.ADMIN_CONSOLE, "Console", ChatColor.DARK_PURPLE, null, false, false); - @Getter + private final Type type; - @Getter + private final String name; - @Getter + private final String abbr; - @Getter + private final String article; - @Getter + private final String tag; - @Getter + private final String coloredTag; - @Getter + private final ChatColor color; - @Getter + private final org.bukkit.ChatColor teamColor; - @Getter + private final boolean hasTeam; - @Getter + private final boolean hasDefaultLoginMessage; Rank(String article, String name, Type type, String abbr, ChatColor color, org.bukkit.ChatColor teamColor, Boolean hasTeam, Boolean hasDefaultLoginMessage) @@ -47,6 +46,19 @@ public enum Rank implements Displayable this.hasDefaultLoginMessage = hasDefaultLoginMessage; } + public static Rank findRank(String string) + { + try + { + return Rank.valueOf(string.toUpperCase()); + } + catch (Exception ignored) + { + } + + return Rank.NON_OP; + } + @Override public String getColoredName() { @@ -99,6 +111,8 @@ public enum Rank implements Displayable return true; } + assert getConsoleVariant() != null; + assert rank.getConsoleVariant() != null; return getConsoleVariant().getLevel() >= rank.getConsoleVariant().getLevel(); } @@ -127,17 +141,55 @@ public enum Rank implements Displayable } } - public static Rank findRank(String string) + public Type getType() { - try - { - return Rank.valueOf(string.toUpperCase()); - } - catch (Exception ignored) - { - } + return type; + } - return Rank.NON_OP; + @Override + public String getName() + { + return name; + } + + @Override + public String getArticle() + { + return article; + } + + @Override + public String getTag() + { + return tag; + } + + @Override + public String getColoredTag() + { + return coloredTag; + } + + @Override + public ChatColor getColor() + { + return color; + } + + @Override + public org.bukkit.ChatColor getTeamColor() + { + return teamColor; + } + + public boolean isHasTeam() + { + return hasTeam; + } + + public boolean isHasDefaultLoginMessage() + { + return hasDefaultLoginMessage; } public enum Type diff --git a/src/main/java/me/totalfreedom/totalfreedommod/rank/RankManager.java b/src/main/java/me/totalfreedom/totalfreedommod/rank/RankManager.java index 1cc1c2af..15ebe5e4 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/rank/RankManager.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/rank/RankManager.java @@ -1,10 +1,11 @@ package me.totalfreedom.totalfreedommod.rank; +import java.util.Objects; import me.totalfreedom.totalfreedommod.FreedomService; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.FPlayer; import me.totalfreedom.totalfreedommod.player.PlayerData; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FUtil; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; @@ -276,21 +277,21 @@ public class RankManager extends FreedomService } if (message != null) { - String loginMessage = FUtil.colorize(ChatColor.AQUA + (message.contains("%name%") ? "" : player.getName() + " is ") + return FUtil.colorize(ChatColor.AQUA + (message.contains("%name%") ? "" : player.getName() + " is ") + FUtil.colorize(message).replace("%name%", player.getName()) .replace("%rank%", display.getName()) .replace("%coloredrank%", display.getColoredName()) .replace("%art%", display.getArticle())); - return loginMessage; } return null; } + @SuppressWarnings("deprecation") public void updatePlayerTeam(Player player) { Displayable display = getDisplay(player); - Scoreboard scoreboard = server.getScoreboardManager().getMainScoreboard(); + Scoreboard scoreboard = Objects.requireNonNull(server.getScoreboardManager()).getMainScoreboard(); Team team = scoreboard.getPlayerTeam(player); if (!display.hasTeam()) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/rank/Title.java b/src/main/java/me/totalfreedom/totalfreedommod/rank/Title.java index dd110111..ab2eb684 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/rank/Title.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/rank/Title.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.rank; -import lombok.Getter; import net.md_5.bungee.api.ChatColor; public enum Title implements Displayable @@ -12,21 +11,21 @@ public enum Title implements Displayable DEVELOPER("a", "Developer", ChatColor.DARK_PURPLE, org.bukkit.ChatColor.DARK_PURPLE, "Dev", true, true), OWNER("the", "Owner", ChatColor.of("#ff0000"), org.bukkit.ChatColor.DARK_RED, "Owner", true, true); - @Getter + private final String article; - @Getter + private final String name; - @Getter + private final String abbr; - @Getter + private final String tag; - @Getter + private final String coloredTag; - @Getter + private final ChatColor color; - @Getter + private final org.bukkit.ChatColor teamColor; - @Getter + private final boolean hasTeam; private final boolean hasDefaultLoginMessage; @@ -66,4 +65,46 @@ public enum Title implements Displayable { return article + " " + color + name; } + + @Override + public String getArticle() + { + return article; + } + + @Override + public String getName() + { + return name; + } + + @Override + public String getAbbr() + { + return abbr; + } + + @Override + public String getTag() + { + return tag; + } + + @Override + public String getColoredTag() + { + return coloredTag; + } + + @Override + public ChatColor getColor() + { + return color; + } + + @Override + public org.bukkit.ChatColor getTeamColor() + { + return teamColor; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/shop/Shop.java b/src/main/java/me/totalfreedom/totalfreedommod/shop/Shop.java index 2e92cd63..d08497c5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/shop/Shop.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/shop/Shop.java @@ -2,8 +2,10 @@ package me.totalfreedom.totalfreedommod.shop; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.Objects; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.player.PlayerData; @@ -28,14 +30,14 @@ import org.bukkit.scheduler.BukkitTask; public class Shop extends FreedomService { - private BukkitTask reactions; - public String reactionString = ""; - public Date reactionStartTime; public final int coinsPerReactionWin = ConfigEntry.SHOP_REACTIONS_COINS_PER_WIN.getInteger(); public final String prefix = ChatColor.DARK_GRAY + "[" + ChatColor.YELLOW + "Reaction" + ChatColor.DARK_GRAY + "] "; - public BukkitTask countdownTask; - private BossBar countdownBar = null; private final String LOGIN_MESSAGE_GUI_TITLE = ChatColor.DARK_GREEN + ChatColor.BOLD.toString() + "Login Messages"; + public String reactionString = ""; + public Date reactionStartTime; + public BukkitTask countdownTask; + private BukkitTask reactions; + private BossBar countdownBar = null; @Override public void onStart() @@ -90,7 +92,7 @@ public class Shop extends FreedomService countdownTask = new BukkitRunnable() { double seconds = 30; - double max = seconds; + final double max = seconds; @Override public void run() @@ -157,6 +159,7 @@ public class Shop extends FreedomService { ItemStack blank = new ItemStack(Material.WHITE_STAINED_GLASS_PANE); ItemMeta meta = blank.getItemMeta(); + assert meta != null; meta.setDisplayName(" "); blank.setItemMeta(meta); gui.setItem(slot, blank); @@ -169,6 +172,7 @@ public class Shop extends FreedomService // Coins ItemStack coins = new ItemStack(Material.GOLD_NUGGET); ItemMeta meta = coins.getItemMeta(); + assert meta != null; meta.setDisplayName(FUtil.colorize("&c&lYou have &e&l" + playerData.getCoins() + "&c&l coins")); coins.setItemMeta(meta); gui.setItem(35, coins); @@ -183,6 +187,7 @@ public class Shop extends FreedomService { ItemStack icon = new ItemStack(Material.NAME_TAG); ItemMeta meta = icon.getItemMeta(); + assert meta != null; meta.setDisplayName(FUtil.colorize(plugin.rm.craftLoginMessage(player, loginMessage))); icon.setItemMeta(meta); gui.setItem(slot, icon); @@ -190,6 +195,7 @@ public class Shop extends FreedomService } ItemStack clear = new ItemStack(Material.BARRIER); ItemMeta meta = clear.getItemMeta(); + assert meta != null; meta.setDisplayName(ChatColor.RED + "Clear login message"); clear.setItemMeta(meta); gui.setItem(35, clear); @@ -198,12 +204,7 @@ public class Shop extends FreedomService public boolean isRealItem(PlayerData data, ShopItem shopItem, PlayerInventory inventory, ItemStack realItem) { - if (isRealItem(data, shopItem, inventory.getItemInMainHand(), realItem) || isRealItem(data, shopItem, inventory.getItemInOffHand(), realItem)) - { - return true; - } - - return false; + return isRealItem(data, shopItem, inventory.getItemInMainHand(), realItem) || isRealItem(data, shopItem, inventory.getItemInOffHand(), realItem); } public boolean isRealItem(PlayerData data, ShopItem shopItem, ItemStack givenItem, ItemStack realItem) @@ -216,18 +217,16 @@ public class Shop extends FreedomService ItemMeta givenMeta = givenItem.getItemMeta(); ItemMeta realMeta = realItem.getItemMeta(); - if (givenMeta.getDisplayName().equals(realMeta.getDisplayName()) && givenMeta.getLore().equals(realMeta.getLore())) - { - return true; - } - - return false; + assert givenMeta != null; + assert realMeta != null; + return givenMeta.getDisplayName().equals(realMeta.getDisplayName()) && Objects.equals(givenMeta.getLore(), realMeta.getLore()); } public ItemStack getLightningRod() { ItemStack itemStack = new ItemStack(Material.BLAZE_ROD); ItemMeta itemMeta = itemStack.getItemMeta(); + assert itemMeta != null; itemMeta.setDisplayName(FUtil.colorize("&bL&3i&bg&3h&bt&3i&bn&3g &b&bR&3o&bd")); itemMeta.setLore(Arrays.asList(ChatColor.AQUA + "Strike others down with the power of lightning.", ChatColor.RED + ChatColor.ITALIC.toString() + "The classic way to exterminate annoyances.")); itemMeta.addEnchant(Enchantment.CHANNELING, 1, false); @@ -239,8 +238,9 @@ public class Shop extends FreedomService { ItemStack itemStack = new ItemStack(Material.FISHING_ROD); ItemMeta itemMeta = itemStack.getItemMeta(); + assert itemMeta != null; itemMeta.setDisplayName(ChatColor.YELLOW + "Grappling Hook"); - itemMeta.setLore(Arrays.asList(ChatColor.GREEN + "be spider-man but ghetto")); + itemMeta.setLore(Collections.singletonList(ChatColor.GREEN + "be spider-man but ghetto")); itemStack.setItemMeta(itemMeta); return itemStack; } @@ -249,8 +249,9 @@ public class Shop extends FreedomService { ItemStack itemStack = new ItemStack(Material.FIRE_CHARGE); ItemMeta itemMeta = itemStack.getItemMeta(); + assert itemMeta != null; itemMeta.setDisplayName(ChatColor.RED + "Fire Ball"); - itemMeta.setLore(Arrays.asList(ChatColor.GOLD + "Yeet this at people")); + itemMeta.setLore(Collections.singletonList(ChatColor.GOLD + "Yeet this at people")); itemStack.setItemMeta(itemMeta); return itemStack; } @@ -259,6 +260,7 @@ public class Shop extends FreedomService { ItemStack itemStack = new ItemStack(Material.ENDER_PEARL); ItemMeta itemMeta = itemStack.getItemMeta(); + assert itemMeta != null; itemMeta.setDisplayName(ChatColor.DARK_PURPLE + "Rideable Ender Pearl"); itemMeta.setLore(Arrays.asList(ChatColor.LIGHT_PURPLE + "What the title says.", "", ChatColor.WHITE + ChatColor.ITALIC.toString() + "TotalFreedom is not responsible for any injuries", ChatColor.WHITE + ChatColor.ITALIC.toString() + "sustained while using this item.")); itemMeta.addEnchant(Enchantment.BINDING_CURSE, 1, false); @@ -270,8 +272,9 @@ public class Shop extends FreedomService { ItemStack itemStack = new ItemStack(Material.POTATO); ItemMeta itemMeta = itemStack.getItemMeta(); + assert itemMeta != null; itemMeta.setDisplayName(ChatColor.YELLOW + "Stacking Potato"); - itemMeta.setLore(Arrays.asList(ChatColor.GREEN + "Left click to ride a mob, right click to put a mob on your head.")); + itemMeta.setLore(Collections.singletonList(ChatColor.GREEN + "Left click to ride a mob, right click to put a mob on your head.")); itemStack.setItemMeta(itemMeta); return itemStack; } @@ -280,19 +283,16 @@ public class Shop extends FreedomService { ItemStack itemStack = new ItemStack(Material.TROPICAL_FISH); ItemMeta itemMeta = itemStack.getItemMeta(); + assert itemMeta != null; itemMeta.setDisplayName(ChatColor.GOLD + "Clown Fish"); - itemMeta.setLore(Arrays.asList(ChatColor.AQUA + ":clown:")); + itemMeta.setLore(Collections.singletonList(ChatColor.AQUA + ":clown:")); itemStack.setItemMeta(itemMeta); return itemStack; } public boolean canAfford(int price, int coins) { - if (coins >= price) - { - return true; - } - return false; + return coins >= price; } public int amountNeeded(int price, int coins) @@ -304,11 +304,12 @@ public class Shop extends FreedomService { ItemStack itemStack = new ItemStack(item.getIcon()); ItemMeta itemMeta = itemStack.getItemMeta(); + assert itemMeta != null; itemMeta.setDisplayName(item.getColoredName()); int price = item.getCost(); int coins = data.getCoins(); - Boolean canAfford = canAfford(price, coins); - List lore = new ArrayList(); + boolean canAfford = canAfford(price, coins); + List lore = new ArrayList<>(); if (!data.hasItem(item)) { lore.add(ChatColor.GOLD + "Price: " + (canAfford ? ChatColor.DARK_GREEN : ChatColor.RED) + price); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/shop/ShopItem.java b/src/main/java/me/totalfreedom/totalfreedommod/shop/ShopItem.java index f7aadccd..4ce94dd5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/shop/ShopItem.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/shop/ShopItem.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.shop; -import lombok.Getter; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -27,18 +26,18 @@ public enum ShopItem --------$ */ - @Getter + private final String name; - @Getter + private final Material icon; - @Getter + private final int slot; private final ConfigEntry cost; - @Getter + private final ChatColor color; - @Getter + private final String dataName; - @Getter + private final String command; ShopItem(String name, Material icon, int slot, ConfigEntry cost, ChatColor color, String dataName, String command) @@ -52,16 +51,6 @@ public enum ShopItem this.command = command; } - public String getColoredName() - { - return color + name; - } - - public int getCost() - { - return cost.getInteger(); - } - public static ShopItem findItem(String string) { try @@ -74,4 +63,44 @@ public enum ShopItem return null; } + + public String getColoredName() + { + return color + name; + } + + public int getCost() + { + return cost.getInteger(); + } + + public String getName() + { + return name; + } + + public Material getIcon() + { + return icon; + } + + public int getSlot() + { + return slot; + } + + public ChatColor getColor() + { + return color; + } + + public String getDataName() + { + return dataName; + } + + public String getCommand() + { + return command; + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/sql/SQLite.java b/src/main/java/me/totalfreedom/totalfreedommod/sql/SQLite.java index 786d8b84..3a0643c0 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/sql/SQLite.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/sql/SQLite.java @@ -8,9 +8,9 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.text.MessageFormat; import me.totalfreedom.totalfreedommod.FreedomService; +import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.banning.Ban; import me.totalfreedom.totalfreedommod.player.PlayerData; -import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FUtil; @@ -66,7 +66,7 @@ public class SQLite extends FreedomService try { DatabaseMetaData meta = connection.getMetaData(); - if (!tableExists(meta, "bans")) + if (tableExists(meta, "bans")) { try { @@ -78,7 +78,7 @@ public class SQLite extends FreedomService } } - if (!tableExists(meta, "admins")) + if (tableExists(meta, "admins")) { try { @@ -89,7 +89,7 @@ public class SQLite extends FreedomService FLog.severe("Failed to create the admins table: " + e.getMessage()); } } - if (!tableExists(meta, "players")) + if (tableExists(meta, "players")) { try { @@ -423,6 +423,6 @@ public class SQLite extends FreedomService public boolean tableExists(DatabaseMetaData meta, String name) throws SQLException { - return meta.getTables(null, null, name, null).next(); + return !meta.getTables(null, null, name, null).next(); } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/FLog.java b/src/main/java/me/totalfreedom/totalfreedommod/util/FLog.java index b8529720..5bab9a8f 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/FLog.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/FLog.java @@ -78,16 +78,6 @@ public class FLog getLogger(false).log(level, null, throwable); } - public static void setServerLogger(Logger logger) - { - serverLogger = logger; - } - - public static void setPluginLogger(Logger logger) - { - pluginLogger = logger; - } - private static Logger getLogger(boolean raw) { if (raw || pluginLogger == null) @@ -105,8 +95,18 @@ public class FLog return (pluginLogger != null ? pluginLogger : FALLBACK_LOGGER); } + public static void setPluginLogger(Logger logger) + { + pluginLogger = logger; + } + public static Logger getServerLogger() { return (serverLogger != null ? serverLogger : FALLBACK_LOGGER); } + + public static void setServerLogger(Logger logger) + { + serverLogger = logger; + } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/FSync.java b/src/main/java/me/totalfreedom/totalfreedommod/util/FSync.java index d1e39cad..91e51578 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/FSync.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/FSync.java @@ -12,6 +12,7 @@ public class FSync public static void playerMsg(final Player player, final String message) { final TotalFreedomMod plugin = TotalFreedomMod.plugin(); + assert plugin != null; new BukkitRunnable() { @@ -27,6 +28,7 @@ public class FSync public static void playerMsg(final CommandSender sender, final String message) { final TotalFreedomMod plugin = TotalFreedomMod.plugin(); + assert plugin != null; new BukkitRunnable() { @@ -42,6 +44,7 @@ public class FSync public static void playerKick(final Player player, final String reason) { final TotalFreedomMod plugin = TotalFreedomMod.plugin(); + assert plugin != null; new BukkitRunnable() { @@ -57,6 +60,7 @@ public class FSync public static void adminChatMessage(final CommandSender sender, final String message) { final TotalFreedomMod plugin = TotalFreedomMod.plugin(); + assert plugin != null; new BukkitRunnable() { @@ -72,6 +76,7 @@ public class FSync public static void autoEject(final Player player, final String kickMessage) { final TotalFreedomMod plugin = TotalFreedomMod.plugin(); + assert plugin != null; new BukkitRunnable() { @@ -87,6 +92,7 @@ public class FSync public static void bcastMsg(final String message, final ChatColor color) { final TotalFreedomMod plugin = TotalFreedomMod.plugin(); + assert plugin != null; new BukkitRunnable() { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java b/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java index ac30c3a9..6c982263 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java @@ -3,7 +3,6 @@ package me.totalfreedom.totalfreedommod.util; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; -import java.io.FileFilter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; @@ -21,6 +20,7 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.TimeZone; @@ -52,7 +52,6 @@ import static org.bukkit.Bukkit.getServer; public class FUtil { - private static final Random RANDOM = new Random(); public static final String SAVED_FLAGS_FILENAME = "savedflags.dat"; /* See https://github.com/TotalFreedom/License - None of the listed names may be removed. Leaving this list here for anyone running TFM on a cracked server: @@ -72,7 +71,6 @@ public class FUtil "c8e5af82-6aba-4dd7-83e8-474381380cc9" // Paldiu ); public static final List DEVELOPER_NAMES = Arrays.asList("Madgeek1450", "Prozza", "WickedGamingUK", "Wild1145", "aggelosQQ", "scripthead", "CoolJWB", "elmon_", "speednt", "SupItsDillon", "Paldiu"); - public static String DATE_STORAGE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; public static final Map CHAT_COLOR_NAMES = new HashMap<>(); public static final List CHAT_COLOR_POOL = Arrays.asList( ChatColor.DARK_RED, @@ -87,9 +85,10 @@ public class FUtil ChatColor.DARK_BLUE, ChatColor.DARK_PURPLE, ChatColor.LIGHT_PURPLE); - private static Iterator CHAT_COLOR_ITERATOR; - private static String CHARACTER_STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - private static Map TIMEZONE_LOOKUP = new HashMap<>(); + private static final Random RANDOM = new Random(); + private static final String CHARACTER_STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + private static final Map TIMEZONE_LOOKUP = new HashMap<>(); + public static String DATE_STORAGE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; static { @@ -128,7 +127,7 @@ public class FUtil { task.cancel(); } - catch (Exception ex) + catch (Exception ignored) { } } @@ -163,7 +162,7 @@ public class FUtil List names = new ArrayList<>(); for (Player player : Bukkit.getOnlinePlayers()) { - if (!TotalFreedomMod.plugin().al.isVanished(player.getName())) + if (!Objects.requireNonNull(TotalFreedomMod.plugin()).al.isVanished(player.getName())) { names.add(player.getName()); } @@ -232,6 +231,7 @@ public class FUtil return names; } + @SuppressWarnings("unchecked") public static UUID nameToUUID(String name) { try @@ -288,7 +288,7 @@ public class FUtil BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; - StringBuffer response = new StringBuffer(); + StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { @@ -354,7 +354,7 @@ public class FUtil public static String formatLocation(Location location) { return String.format("%s: (%d, %d, %d)", - location.getWorld().getName(), + Objects.requireNonNull(location.getWorld()).getName(), Math.round(location.getX()), Math.round(location.getY()), Math.round(location.getZ())); @@ -371,14 +371,7 @@ public class FUtil public static void deleteCoreDumps() { - final File[] coreDumps = new File(".").listFiles(new FileFilter() - { - @Override - public boolean accept(File file) - { - return file.getName().startsWith("java.core"); - } - }); + final File[] coreDumps = new File(".").listFiles(file -> file.getName().startsWith("java.core")); for (File dump : coreDumps) { @@ -545,7 +538,7 @@ public class FUtil octets = 1; } - for (int i = 0; i < octets && i < 4; i++) + for (int i = 0; i < octets; i++) { if (aParts[i].equals("*") || bParts[i].equals("*")) { @@ -587,7 +580,7 @@ public class FUtil return (T)field.get(from); } - catch (NoSuchFieldException | IllegalAccessException ex) + catch (NoSuchFieldException | IllegalAccessException ignored) { } } @@ -604,7 +597,7 @@ public class FUtil public static String rainbowify(String string) { - CHAT_COLOR_ITERATOR = CHAT_COLOR_POOL.iterator(); + Iterator CHAT_COLOR_ITERATOR = CHAT_COLOR_POOL.iterator(); StringBuilder newString = new StringBuilder(); char[] chars = string.toCharArray(); @@ -666,37 +659,36 @@ public class FUtil public static int randomInteger(int min, int max) { int range = max - min + 1; - int value = (int)(Math.random() * range) + min; - return value; + return (int)(Math.random() * range) + min; } public static String randomString(int length) { String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789-_=+[]{};:,.<>~"; - String randomString = ""; + StringBuilder randomString = new StringBuilder(); for (int i = 0; i < length; i++) { int selectedCharacter = randomInteger(1, characters.length()) - 1; - randomString += characters.charAt(selectedCharacter); + randomString.append(characters.charAt(selectedCharacter)); } - return randomString; + return randomString.toString(); } public static String randomAlphanumericString(int length) { String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789"; - String randomString = ""; + StringBuilder randomString = new StringBuilder(); for (int i = 0; i < length; i++) { int selectedCharacter = randomInteger(1, characters.length()) - 1; - randomString += characters.charAt(selectedCharacter); + randomString.append(characters.charAt(selectedCharacter)); } - return randomString; + return randomString.toString(); } @@ -736,6 +728,7 @@ public class FUtil { ItemStack stack = new ItemStack(material, amount); ItemMeta meta = stack.getItemMeta(); + assert meta != null; meta.setDisplayName(FUtil.colorize(coloredName)); List loreList = new ArrayList<>(); for (String entry : lore) @@ -788,7 +781,7 @@ public class FUtil public static String getIp(Player player) { - return player.getAddress().getAddress().getHostAddress().trim(); + return Objects.requireNonNull(player.getAddress()).getAddress().getHostAddress().trim(); } public static String getIp(PlayerLoginEvent event) @@ -809,12 +802,8 @@ public class FUtil public static boolean isValidIPv4(String ip) { - if (ip.matches("^([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$") - || ip.matches("^([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([*])\\.([*])$")) - { - return true; - } - return false; + return !ip.matches("^([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$") + && !ip.matches("^([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\\.([*])\\.([*])$"); } public static List createColorGradient(Color c1, Color c2, int steps) @@ -868,7 +857,7 @@ public class FUtil @Override public void run() { - location.getWorld().createExplosion(location, power); + Objects.requireNonNull(location.getWorld()).createExplosion(location, power); } }.runTaskLater(TotalFreedomMod.getPlugin(), delay); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/History.java b/src/main/java/me/totalfreedom/totalfreedommod/util/History.java index 42b1a4aa..e82a29dd 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/History.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/History.java @@ -10,6 +10,7 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; +import java.util.Objects; import java.util.UUID; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import org.bukkit.ChatColor; @@ -64,7 +65,7 @@ public class History FSync.playerMsg(sender, ChatColor.RED + "Player not found!"); } } - }.runTaskAsynchronously(TotalFreedomMod.plugin()); + }.runTaskAsynchronously(Objects.requireNonNull(TotalFreedomMod.plugin())); } private static void printHistory(CommandSender sender, FName[] oldNames) @@ -85,9 +86,15 @@ public class History private static class FName implements Comparable { + private final String name; + private final long changedToAt; - private String name; - private long changedToAt; + //Added constructor because otherwise there's no way name or changedToAt would have been anything other than null. + public FName(String name, long changedToAt) + { + this.name = name; + this.changedToAt = changedToAt; + } @Override public int compareTo(FName other) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/Response.java b/src/main/java/me/totalfreedom/totalfreedommod/util/Response.java index fc3de35c..867b3f7f 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/Response.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/Response.java @@ -1,16 +1,13 @@ package me.totalfreedom.totalfreedommod.util; -import lombok.Getter; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class Response { - @Getter - private int code; - @Getter - private String message; + private final int code; + private final String message; public Response(int code, String message) { @@ -20,6 +17,16 @@ public class Response public JSONObject getJSONMessage() throws ParseException { - return (JSONObject) new JSONParser().parse(message); + return (JSONObject)new JSONParser().parse(message); + } + + public int getCode() + { + return code; + } + + public String getMessage() + { + return message; } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/UUIDFetcher.java b/src/main/java/me/totalfreedom/totalfreedommod/util/UUIDFetcher.java index 05f8b534..93f49e91 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/UUIDFetcher.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/UUIDFetcher.java @@ -55,7 +55,7 @@ public class UUIDFetcher return null; } - private class FetchedUuid + private static class FetchedUuid { private String id; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/AdminWorld.java b/src/main/java/me/totalfreedom/totalfreedommod/world/AdminWorld.java index 275fc39a..2a230017 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/AdminWorld.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/AdminWorld.java @@ -2,6 +2,7 @@ package me.totalfreedom.totalfreedommod.world; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.util.FLog; import org.bukkit.Bukkit; @@ -38,6 +39,7 @@ public final class AdminWorld extends CustomWorld super.sendToWorld(player); } + @SuppressWarnings("deprecation") @Override protected World generateWorld() { @@ -49,6 +51,7 @@ public final class AdminWorld extends CustomWorld final World world = Bukkit.getServer().createWorld(worldCreator); + assert world != null; world.setSpawnFlags(false, false); world.setSpawnLocation(0, 50, 0); @@ -81,7 +84,7 @@ public final class AdminWorld extends CustomWorld return true; } - if (world == null || !event.getTo().getWorld().equals(world)) + if (world == null || !Objects.equals(Objects.requireNonNull(event.getTo()).getWorld(), world)) { return true; } @@ -113,7 +116,7 @@ public final class AdminWorld extends CustomWorld { weatherMode.setWorldToWeather(getWorld()); } - catch (Exception ex) + catch (Exception ignored) { } } @@ -131,7 +134,7 @@ public final class AdminWorld extends CustomWorld { timeOfDay.setWorldToTime(getWorld()); } - catch (Exception ex) + catch (Exception ignored) { } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java b/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java index b3e7db55..8d0b9bd6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java @@ -25,11 +25,12 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.generator.ChunkGenerator; +import org.jetbrains.annotations.NotNull; import static java.lang.System.arraycopy; public class CleanroomChunkGenerator extends ChunkGenerator { - private Logger log = Logger.getLogger("Minecraft"); + private final Logger log = Logger.getLogger("Minecraft"); private Material[] materials; @@ -51,7 +52,7 @@ public class CleanroomChunkGenerator extends ChunkGenerator if (id.length() > 0) { - String tokens[] = id.split("[,]"); + String[] tokens = id.split("[,]"); if ((tokens.length % 2) != 0) { @@ -67,7 +68,7 @@ public class CleanroomChunkGenerator extends ChunkGenerator height = 64; } - String materialTokens[] = tokens[i + 1].split("[:]", 2); + String[] materialTokens = tokens[i + 1].split("[:]", 2); if (materialTokens.length == 2) { @@ -127,7 +128,7 @@ public class CleanroomChunkGenerator extends ChunkGenerator } @Override - public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome) + public @NotNull ChunkData generateChunkData(World world, @NotNull Random random, int x, int z, @NotNull BiomeGrid biome) { int maxHeight = world.getMaxHeight(); if (materials.length > maxHeight) @@ -149,7 +150,7 @@ public class CleanroomChunkGenerator extends ChunkGenerator } @Override - public Location getFixedSpawnLocation(World world, Random random) + public Location getFixedSpawnLocation(World world, @NotNull Random random) { if (!world.isChunkLoaded(0, 0)) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/CustomWorld.java b/src/main/java/me/totalfreedom/totalfreedommod/world/CustomWorld.java index e70c619c..9ef3392a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/CustomWorld.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/CustomWorld.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.world; import io.papermc.lib.PaperLib; -import lombok.Getter; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.util.FLog; import org.bukkit.Bukkit; @@ -10,8 +9,6 @@ import org.bukkit.entity.Player; public abstract class CustomWorld extends FreedomService { - - @Getter private final String name; // private World world; @@ -59,4 +56,9 @@ public abstract class CustomWorld extends FreedomService } protected abstract World generateWorld(); + + public String getName() + { + return name; + } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/Flatlands.java b/src/main/java/me/totalfreedom/totalfreedommod/world/Flatlands.java index 937f54d1..32033da5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/Flatlands.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/Flatlands.java @@ -23,6 +23,7 @@ public class Flatlands extends CustomWorld super("flatlands"); } + @SuppressWarnings("deprecation") @Override protected World generateWorld() { @@ -41,6 +42,7 @@ public class Flatlands extends CustomWorld final World world = Bukkit.getServer().createWorld(worldCreator); + assert world != null; world.setSpawnFlags(false, false); world.setSpawnLocation(0, 50, 0); @@ -70,7 +72,7 @@ public class Flatlands extends CustomWorld { doFlatlandsWipe = plugin.sf.getSavedFlag("do_wipe_flatlands"); } - catch (Exception ex) + catch (Exception ignored) { } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/HubWorld.java b/src/main/java/me/totalfreedom/totalfreedommod/world/HubWorld.java index 5cbafddc..241c6d81 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/HubWorld.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/HubWorld.java @@ -29,6 +29,8 @@ public final class HubWorld extends CustomWorld super.sendToWorld(player); } + // TODO: Replace instances of org.bukkit.Sign with a non deprecated version. This might include more boilerplate. + @SuppressWarnings("deprecation") @Override protected World generateWorld() { @@ -40,6 +42,7 @@ public final class HubWorld extends CustomWorld final World world = server.createWorld(worldCreator); + assert world != null; world.setSpawnFlags(false, false); world.setSpawnLocation(0, 50, 0); @@ -73,7 +76,7 @@ public final class HubWorld extends CustomWorld { weatherMode.setWorldToWeather(getWorld()); } - catch (Exception ex) + catch (Exception ignored) { } } @@ -91,7 +94,7 @@ public final class HubWorld extends CustomWorld { timeOfDay.setWorldToTime(getWorld()); } - catch (Exception ex) + catch (Exception ignored) { } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/MasterBuilderWorld.java b/src/main/java/me/totalfreedom/totalfreedommod/world/MasterBuilderWorld.java index 65e34cc6..2d35349f 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/MasterBuilderWorld.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/MasterBuilderWorld.java @@ -29,6 +29,8 @@ public final class MasterBuilderWorld extends CustomWorld super.sendToWorld(player); } + // TODO: Replace org.bukkit.Sign with a non deprecated version. This may require extra boilerplate. + @SuppressWarnings("deprecation") @Override protected World generateWorld() { @@ -40,6 +42,7 @@ public final class MasterBuilderWorld extends CustomWorld final World world = server.createWorld(worldCreator); + assert world != null; world.setSpawnFlags(false, false); world.setSpawnLocation(0, 50, 0); @@ -73,7 +76,7 @@ public final class MasterBuilderWorld extends CustomWorld { weatherMode.setWorldToWeather(getWorld()); } - catch (Exception ex) + catch (Exception ignored) { } } @@ -91,7 +94,7 @@ public final class MasterBuilderWorld extends CustomWorld { timeOfDay.setWorldToTime(getWorld()); } - catch (Exception ex) + catch (Exception ignored) { } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldManager.java b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldManager.java index 18aeffcd..a88dec0a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldManager.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldManager.java @@ -78,7 +78,7 @@ public class WorldManager extends FreedomService return; } } - catch (Exception ex) + catch (Exception ignored) { } @@ -106,7 +106,7 @@ public class WorldManager extends FreedomService return; } } - catch (Exception ex) + catch (Exception ignored) { } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldRestrictions.java b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldRestrictions.java index 0eefd78f..4b34835b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldRestrictions.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldRestrictions.java @@ -53,7 +53,7 @@ public class WorldRestrictions extends FreedomService public boolean doRestrict(Player player) { - if (!plugin.pl.getData(player).isMasterBuilder() && !plugin.pl.canManageMasterBuilders(player.getName())) + if (!plugin.pl.getData(player).isMasterBuilder() && plugin.pl.canManageMasterBuilders(player.getName())) { if (player.getWorld().equals(plugin.wm.masterBuilderWorld.getWorld()) || player.getWorld().equals(plugin.wm.hubworld.getWorld())) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldTime.java b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldTime.java index 501fba4d..0b5fd5e7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldTime.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldTime.java @@ -29,18 +29,6 @@ public enum WorldTime this.aliases = Arrays.asList(StringUtils.split(aliases, ",")); } - public int getTimeTicks() - { - return timeTicks; - } - - public void setWorldToTime(World world) - { - long time = world.getTime(); - time -= time % 24000; - world.setTime(time + 24000 + getTimeTicks()); - } - public static WorldTime getByAlias(String needle) { needle = needle.toLowerCase(); @@ -53,4 +41,16 @@ public enum WorldTime } return null; } + + public int getTimeTicks() + { + return timeTicks; + } + + public void setWorldToTime(World world) + { + long time = world.getTime(); + time -= time % 24000; + world.setTime(time + 24000 + getTimeTicks()); + } } \ No newline at end of file diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldWeather.java b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldWeather.java index 3debcedd..ef5cf5cb 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldWeather.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldWeather.java @@ -19,15 +19,6 @@ public enum WorldWeather this.aliases = Arrays.asList(StringUtils.split(aliases, ",")); } - public void setWorldToWeather(World world) - { - world.setStorm(this == RAIN || this == STORM); - world.setWeatherDuration(this == RAIN || this == STORM ? 20 * 60 * 5 : 0); - - world.setThundering(this == STORM); - world.setThunderDuration(this == STORM ? 20 * 60 * 5 : 0); - } - public static WorldWeather getByAlias(String needle) { needle = needle.toLowerCase(); @@ -40,4 +31,13 @@ public enum WorldWeather } return null; } + + public void setWorldToWeather(World world) + { + world.setStorm(this == RAIN || this == STORM); + world.setWeatherDuration(this == RAIN || this == STORM ? 20 * 60 * 5 : 0); + + world.setThundering(this == STORM); + world.setThunderDuration(this == STORM ? 20 * 60 * 5 : 0); + } } From 361aa4ee04d4b99c59cb7fb8bd75595ef4178779 Mon Sep 17 00:00:00 2001 From: Paldiu Date: Fri, 25 Dec 2020 15:20:34 -0500 Subject: [PATCH 02/15] Bugfix on Commit #5c0f77c A mismatched argument count during constructor initialization in Module_logs.class was fixed in this patch. --- .../totalfreedom/totalfreedommod/httpd/module/Module_logs.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java index cd065fec..a66737a5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java @@ -11,7 +11,7 @@ public class Module_logs extends Module_file public Module_logs(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) { - super(plugin, session); + super(session); } @Override From 97edce0a6714ce88099062d8fb9986941530fb4a Mon Sep 17 00:00:00 2001 From: Paldiu Date: Fri, 25 Dec 2020 15:35:33 -0500 Subject: [PATCH 03/15] Fixes for Codacy; These fixes are designed to satisfy codacy. However, codacy reports a NPath Complexity of 649, whereas the current, recommended, and standardized threshold is 200. This is caused by FreedomCommand#execute(CommandSender, String, String[]); --- .../totalfreedom/totalfreedommod/Pterodactyl.java | 8 ++++---- .../totalfreedommod/blocking/EventBlocker.java | 10 ++++------ .../totalfreedommod/caging/CageData.java | 6 +++--- .../totalfreedommod/discord/Discord.java | 4 ++-- .../totalfreedom/totalfreedommod/fun/ItemFun.java | 13 ++++++------- .../permissions/PermissionConfig.java | 4 +--- .../totalfreedommod/punishments/Punishment.java | 4 ++-- 7 files changed, 22 insertions(+), 27 deletions(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java b/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java index 22566205..12c0cefd 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/Pterodactyl.java @@ -182,22 +182,22 @@ public class Pterodactyl extends FreedomService return URL; } - public String getSERVER_KEY() + public String getServerKey() { return SERVER_KEY; } - public String getADMIN_KEY() + public String getAdminKey() { return ADMIN_KEY; } - public List getSERVER_HEADERS() + public List getServerHeaders() { return SERVER_HEADERS; } - public List getADMIN_HEADERS() + public List getAdminHeaders() { return ADMIN_HEADERS; } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java index 73e7bc7a..f9e97dfe 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/EventBlocker.java @@ -134,13 +134,11 @@ public class EventBlocker extends FreedomService @EventHandler(priority = EventPriority.HIGH) public void onEntityDamage(EntityDamageEvent event) { - if (event.getCause() == EntityDamageEvent.DamageCause.LAVA) + if ((event.getCause() == EntityDamageEvent.DamageCause.LAVA) + && !ConfigEntry.ALLOW_LAVA_DAMAGE.getBoolean()) { - if (!ConfigEntry.ALLOW_LAVA_DAMAGE.getBoolean()) - { - event.setCancelled(true); - return; - } + event.setCancelled(true); + return; } if (ConfigEntry.ENABLE_PET_PROTECT.getBoolean()) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/caging/CageData.java b/src/main/java/me/totalfreedom/totalfreedommod/caging/CageData.java index 16408f09..aab5299c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/caging/CageData.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/caging/CageData.java @@ -126,7 +126,7 @@ public class CageData this.innerMaterial = inner; input = null; - buildHistory(location, fPlayer); + buildHistory(location); regenerate(); } @@ -143,7 +143,7 @@ public class CageData this.innerMaterial = inner; CageData.input = input; - buildHistory(location, fPlayer); + buildHistory(location); regenerate(); } @@ -197,7 +197,7 @@ public class CageData } } - private void buildHistory(Location location, FPlayer playerdata) + private void buildHistory(Location location) { final Block center = location.getBlock(); for (int xOffset = -2; xOffset <= 2; xOffset++) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java index 18dfc1a8..1b345999 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java @@ -187,7 +187,7 @@ public class Discord extends FreedomService @Override public void onReady(@NotNull ReadyEvent event) { - new StartEvent(event.getJDA()).start(); + new StartEvent().start(); } }) .setAutoReconnect(true) @@ -503,7 +503,7 @@ public class Discord extends FreedomService // Do no ask why this is here. I spent two hours trying to make a simple thing work public class StartEvent { - public StartEvent(JDA api) + public StartEvent() { } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java index 30a83f57..e51fb163 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java @@ -324,14 +324,13 @@ public class ItemFun extends FreedomService { arrow = (Arrow)entity; } - if (arrow != null && (arrow.getShooter() instanceof Player)) + //Redundant Player cast is required to avoid suspicious method calls. + if (arrow != null + && (arrow.getShooter() instanceof Player) + && explosivePlayers.contains((Player)arrow.getShooter())) { - //Redundant Player cast is required to avoid suspicious method calls. - if (explosivePlayers.contains(arrow.getShooter())) - { - Objects.requireNonNull(arrow.getLocation().getWorld()).createExplosion(arrow.getLocation().getX(), arrow.getLocation().getY(), arrow.getLocation().getZ(), ConfigEntry.EXPLOSIVE_RADIUS.getDouble().floatValue(), false, ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()); - arrow.remove(); - } + Objects.requireNonNull(arrow.getLocation().getWorld()).createExplosion(arrow.getLocation().getX(), arrow.getLocation().getY(), arrow.getLocation().getZ(), ConfigEntry.EXPLOSIVE_RADIUS.getDouble().floatValue(), false, ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()); + arrow.remove(); } if (entity instanceof Fireball) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionConfig.java b/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionConfig.java index bfc3d3c4..c49faa66 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionConfig.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionConfig.java @@ -23,7 +23,7 @@ public class PermissionConfig extends FreedomService { entries = new EnumMap<>(PermissionEntry.class); - PermissionDefaults tempDefaults = null; + PermissionDefaults tempDefaults; try { try @@ -50,8 +50,6 @@ public class PermissionConfig extends FreedomService { FLog.severe(ex); } - - PermissionDefaults defaults = tempDefaults; } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/punishments/Punishment.java b/src/main/java/me/totalfreedom/totalfreedommod/punishments/Punishment.java index 51c90da8..3e532872 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/punishments/Punishment.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/punishments/Punishment.java @@ -133,12 +133,12 @@ public class Punishment implements IConfig this.reason = reason; } - public Date getIssued_on() + public Date getIssuedOn() { return issued_on; } - public void setIssued_on(Date issued_on) + public void setIssuedOn(Date issued_on) { this.issued_on = issued_on; } From dec35f76e4fc495385078e87f4c4f3fa6ffc3c46 Mon Sep 17 00:00:00 2001 From: Paldiu Date: Fri, 25 Dec 2020 15:51:17 -0500 Subject: [PATCH 04/15] Minor fix Switched from a lengthy if else to a ternary. --- .../totalfreedommod/bridge/EssentialsBridge.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java b/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java index 83670976..d58f8761 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/bridge/EssentialsBridge.java @@ -115,14 +115,7 @@ public class EssentialsBridge extends FreedomService if (user != null) { Long l = FUtil.getField(user, "lastActivity"); - if (l != null) - { - return l; - } - else - { - return 0L; - } + return (l != null) ? l : 0L; } } catch (Exception ex) From eb9759f2d8c6bd91f84544e884264c8c8dc4fd7a Mon Sep 17 00:00:00 2001 From: Paldiu Date: Fri, 25 Dec 2020 15:57:10 -0500 Subject: [PATCH 05/15] Replaced All Instances of Random With SplittableRandom SplittableRandom is faster (negligable) than Random and is also able to recursively return new instances of itself for an even more complex pseudo random generator compared to the default Random supplied by Java. --- .../totalfreedom/totalfreedommod/command/Command_bird.java | 4 ++-- .../totalfreedommod/command/Command_deafen.java | 4 ++-- .../totalfreedommod/command/Command_modifyitem.java | 4 ++-- .../me/totalfreedom/totalfreedommod/discord/Discord.java | 4 ++-- .../java/me/totalfreedom/totalfreedommod/fun/ItemFun.java | 4 ++-- .../java/me/totalfreedom/totalfreedommod/fun/Trailer.java | 4 ++-- .../java/me/totalfreedom/totalfreedommod/util/FUtil.java | 6 +++--- .../totalfreedommod/world/CleanroomChunkGenerator.java | 6 +++--- 8 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_bird.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_bird.java index 4eb70a01..87291599 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_bird.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_bird.java @@ -2,7 +2,7 @@ package me.totalfreedom.totalfreedommod.command; import java.util.Arrays; import java.util.List; -import java.util.Random; +import java.util.SplittableRandom; import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.Location; import org.bukkit.command.Command; @@ -27,7 +27,7 @@ public class Command_bird extends FreedomCommand public EntityType getRandomFish() { List fishTypes = Arrays.asList(EntityType.COD, EntityType.SALMON, EntityType.PUFFERFISH, EntityType.TROPICAL_FISH); - Random random = new Random(); + SplittableRandom random = new SplittableRandom(); return fishTypes.get(random.nextInt(fishTypes.size())); } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deafen.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deafen.java index eb15c609..d3358487 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deafen.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_deafen.java @@ -1,6 +1,6 @@ package me.totalfreedom.totalfreedommod.command; -import java.util.Random; +import java.util.SplittableRandom; import me.totalfreedom.totalfreedommod.rank.Rank; import org.bukkit.Location; import org.bukkit.Sound; @@ -15,7 +15,7 @@ public class Command_deafen extends FreedomCommand { public static final double STEPS = 10.0; - private static final Random random = new Random(); + private static final SplittableRandom random = new SplittableRandom(); private static Location randomOffset(Location a) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_modifyitem.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_modifyitem.java index ed9273cf..bb7d6ec7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_modifyitem.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_modifyitem.java @@ -2,7 +2,7 @@ package me.totalfreedom.totalfreedommod.command; import java.util.ArrayList; import java.util.List; -import java.util.Random; +import java.util.SplittableRandom; import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.util.FUtil; import net.minecraft.server.v1_16_R3.NBTTagCompound; @@ -180,7 +180,7 @@ public class Command_modifyitem extends FreedomCommand } cmpnd.setDouble("Amount", amount); cmpnd.setInt("Operation", 0); - Random random = new Random(); + SplittableRandom random = new SplittableRandom(); cmpnd.setIntArray("UUID", new int[] { random.nextInt(), diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java index 1b345999..06011b44 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/Discord.java @@ -10,7 +10,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Objects; -import java.util.Random; +import java.util.SplittableRandom; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import javax.security.auth.login.LoginException; @@ -292,7 +292,7 @@ public class Discord extends FreedomService public String generateCode(int size) { StringBuilder code = new StringBuilder(); - Random random = new Random(); + SplittableRandom random = new SplittableRandom(); for (int i = 0; i < size; i++) { code.append(random.nextInt(10)); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java index e51fb163..c42a10b3 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java @@ -5,7 +5,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Random; +import java.util.SplittableRandom; import java.util.UUID; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.config.ConfigEntry; @@ -48,7 +48,7 @@ import org.bukkit.util.Vector; public class ItemFun extends FreedomService { - private final Random random = new Random(); + private final SplittableRandom random = new SplittableRandom(); private final Map> cooldownTracker = new HashMap<>(); private final Map orientationTracker = new HashMap<>(); private final List FIRE_BALL_UUIDS = new ArrayList<>(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java index a72abaa1..77f2c9fe 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java @@ -2,7 +2,7 @@ package me.totalfreedom.totalfreedommod.fun; import java.util.HashSet; import java.util.Objects; -import java.util.Random; +import java.util.SplittableRandom; import java.util.Set; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.util.Groups; @@ -17,7 +17,7 @@ import org.bukkit.event.player.PlayerMoveEvent; public class Trailer extends FreedomService { - private final Random random = new Random(); + private final SplittableRandom random = new SplittableRandom(); private final Set trailPlayers = new HashSet<>(); // player name @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java b/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java index 6c982263..6f52ad8a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java @@ -21,7 +21,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; -import java.util.Random; +import java.util.SplittableRandom; import java.util.Set; import java.util.TimeZone; import java.util.UUID; @@ -85,7 +85,7 @@ public class FUtil ChatColor.DARK_BLUE, ChatColor.DARK_PURPLE, ChatColor.LIGHT_PURPLE); - private static final Random RANDOM = new Random(); + private static final SplittableRandom RANDOM = new SplittableRandom(); private static final String CHARACTER_STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final Map TIMEZONE_LOOKUP = new HashMap<>(); public static String DATE_STORAGE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; @@ -721,7 +721,7 @@ public class FUtil public static char getRandomCharacter() { - return CHARACTER_STRING.charAt(new Random().nextInt(CHARACTER_STRING.length())); + return CHARACTER_STRING.charAt(new SplittableRandom().nextInt(CHARACTER_STRING.length())); } public static void give(Player player, Material material, String coloredName, int amount, String... lore) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java b/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java index 8d0b9bd6..dc88905c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java @@ -19,7 +19,7 @@ package me.totalfreedom.totalfreedommod.world; import java.util.Arrays; -import java.util.Random; +import java.util.SplittableRandom; import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.Material; @@ -128,7 +128,7 @@ public class CleanroomChunkGenerator extends ChunkGenerator } @Override - public @NotNull ChunkData generateChunkData(World world, @NotNull Random random, int x, int z, @NotNull BiomeGrid biome) + public @NotNull ChunkData generateChunkData(World world, @NotNull SplittableRandom random, int x, int z, @NotNull BiomeGrid biome) { int maxHeight = world.getMaxHeight(); if (materials.length > maxHeight) @@ -150,7 +150,7 @@ public class CleanroomChunkGenerator extends ChunkGenerator } @Override - public Location getFixedSpawnLocation(World world, @NotNull Random random) + public Location getFixedSpawnLocation(World world, @NotNull SplittableRandom random) { if (!world.isChunkLoaded(0, 0)) { From d71f5452ad113212e71686f67e81feffe04f9456 Mon Sep 17 00:00:00 2001 From: Paldiu Date: Sat, 26 Dec 2020 10:30:30 -0500 Subject: [PATCH 06/15] Changed instance of SplittableRandom back to Random Overridable methods required Random instead of SplittableRandom and caused a build failure in the previous commit. This should fix the build failure. --- .../totalfreedommod/world/CleanroomChunkGenerator.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java b/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java index dc88905c..d60a2e71 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java @@ -19,6 +19,7 @@ package me.totalfreedom.totalfreedommod.world; import java.util.Arrays; +import java.util.Random; import java.util.SplittableRandom; import java.util.logging.Logger; import org.bukkit.Location; @@ -128,7 +129,7 @@ public class CleanroomChunkGenerator extends ChunkGenerator } @Override - public @NotNull ChunkData generateChunkData(World world, @NotNull SplittableRandom random, int x, int z, @NotNull BiomeGrid biome) + public @NotNull ChunkData generateChunkData(World world, @NotNull Random random, int x, int z, @NotNull BiomeGrid biome) { int maxHeight = world.getMaxHeight(); if (materials.length > maxHeight) @@ -150,7 +151,7 @@ public class CleanroomChunkGenerator extends ChunkGenerator } @Override - public Location getFixedSpawnLocation(World world, @NotNull SplittableRandom random) + public Location getFixedSpawnLocation(World world, @NotNull Random random) { if (!world.isChunkLoaded(0, 0)) { From 9352a486500c8e61ceab4980b6cb9c8a609cca2a Mon Sep 17 00:00:00 2001 From: Paldiu Date: Tue, 29 Dec 2020 21:37:50 -0600 Subject: [PATCH 07/15] Finalized lombok removal Finally removed all lomboks, also reduced npath complexity for FreedomCommand.FCommand#execute and removed empty constructor from Discord --- .idea/codeStyles/Project.xml | 18 ---- .../command/CommandLoader.java | 7 +- .../command/FreedomCommand.java | 99 ++++++++++++------- .../totalfreedommod/discord/Discord.java | 4 - .../totalfreedommod/fun/Landminer.java | 20 +++- .../httpd/ModuleExecutable.java | 7 +- .../totalfreedommod/player/PlayerList.java | 14 ++- 7 files changed, 95 insertions(+), 74 deletions(-) diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 86bb373f..9898a0e5 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -9,24 +9,6 @@ - - - -
    \r\n"); - final NanoHTTPD.Response response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_HTML, body.toString()); - - return response; + return new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_HTML, body.toString()); } } @@ -138,7 +135,7 @@ public class Module_list extends HTTPDModule public boolean hasSpecialTitle(Player player) { - return FUtil.DEVELOPERS.contains(player.getUniqueId().toString()) || ConfigEntry.SERVER_EXECUTIVES.getList().contains(player.getName()) || ConfigEntry.SERVER_OWNERS.getList().contains(player.getName()); + return !FUtil.DEVELOPERS.contains(player.getUniqueId().toString()) && !ConfigEntry.SERVER_EXECUTIVES.getList().contains(player.getName()) && !ConfigEntry.SERVER_OWNERS.getList().contains(player.getName()); } @Override diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logfile.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logfile.java index 7015be7e..e0a88031 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logfile.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logfile.java @@ -3,10 +3,8 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.io.File; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.List; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.HTMLGenerationTools; @@ -29,14 +27,14 @@ public class Module_logfile extends HTTPDModule "gz" }; - public Module_logfile(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_logfile(NanoHTTPD.HTTPSession session) { super(session); } - private static String getArg(String[] args, int index) + private static String getArg(String[] args) { - String out = (args.length == index + 1 ? args[index] : null); + String out = (args.length == 1 + 1 ? args[1] : null); return (out == null ? null : (out.trim().isEmpty() ? null : out.trim())); } @@ -69,13 +67,13 @@ public class Module_logfile extends HTTPDModule final StringBuilder out = new StringBuilder(); final String remoteAddress = socket.getInetAddress().getHostAddress(); final String[] args = StringUtils.split(uri, "/"); - final ModuleMode mode = ModuleMode.getMode(getArg(args, 1)); + final ModuleMode mode = ModuleMode.getMode(getArg(args)); switch (mode) { case LIST: { - if (!isAuthorized(remoteAddress)) + if (isAuthorized(remoteAddress)) { out.append(HTMLGenerationTools.paragraph("Log files access denied: Your IP, " + remoteAddress + ", is not registered to an admin on this server.")); @@ -94,14 +92,7 @@ public class Module_logfile extends HTTPDModule } - Collections.sort(LogFilesFormatted, new Comparator() - { - @Override - public int compare(String a, String b) - { - return a.toLowerCase().compareTo(b.toLowerCase()); - } - }); + LogFilesFormatted.sort(Comparator.comparing(String::toLowerCase)); out .append(HTMLGenerationTools.heading("Logfiles:", 1)) @@ -113,7 +104,7 @@ public class Module_logfile extends HTTPDModule } case DOWNLOAD: { - if (!isAuthorized(remoteAddress)) + if (isAuthorized(remoteAddress)) { out.append(HTMLGenerationTools.paragraph("Log files access denied: Your IP, " + remoteAddress + ", is not registered to an admin on this server.")); FLog.info("An unregistered IP (" + remoteAddress + ") has tried to download a log file"); @@ -172,7 +163,7 @@ public class Module_logfile extends HTTPDModule private boolean isAuthorized(String remoteAddress) { Admin entry = plugin.al.getEntryByIp(remoteAddress); - return entry != null && entry.isActive(); + return entry == null || !entry.isActive(); } private enum ModuleMode @@ -211,11 +202,6 @@ public class Module_logfile extends HTTPDModule private static class LogFileTransferException extends Exception { - - public LogFileTransferException() - { - } - public LogFileTransferException(String string) { super(string); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java index a66737a5..e40d191e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java @@ -9,7 +9,7 @@ import me.totalfreedom.totalfreedommod.util.FLog; public class Module_logs extends Module_file { - public Module_logs(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_logs(NanoHTTPD.HTTPSession session) { super(session); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java index fce7c782..64217059 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java @@ -13,7 +13,7 @@ import org.json.simple.JSONObject; public class Module_players extends HTTPDModule { - public Module_players(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_players(NanoHTTPD.HTTPSession session) { super(session); } @@ -25,7 +25,7 @@ public class Module_players extends HTTPDModule final JSONObject responseObject = new JSONObject(); final JSONArray players = new JSONArray(); - final JSONArray onlineadmins = new JSONArray(); + final JSONArray onlineadmins = new JSONArray(); // updated, never queried. final JSONArray masterbuilders = new JSONArray(); final JSONArray admins = new JSONArray(); final JSONArray senioradmins = new JSONArray(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java index 4ce57158..88ecd9eb 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java @@ -10,7 +10,7 @@ import me.totalfreedom.totalfreedommod.punishments.PunishmentList; public class Module_punishments extends HTTPDModule { - public Module_punishments(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_punishments(NanoHTTPD.HTTPSession session) { super(session); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java index 9a251b88..d9614745 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java @@ -8,12 +8,10 @@ import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.HTMLGenerationTools; @@ -46,14 +44,14 @@ public class Module_schematic extends HTTPDModule + "\n" + ""; - public Module_schematic(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session) + public Module_schematic(NanoHTTPD.HTTPSession session) { super(session); } - private static String getArg(String[] args, int index) + private static String getArg(String[] args) { - String out = (args.length == index + 1 ? args[index] : null); + String out = (args.length == 1 + 1 ? args[1] : null); return (out == null ? null : (out.trim().isEmpty() ? null : out.trim())); } @@ -85,7 +83,7 @@ public class Module_schematic extends HTTPDModule final StringBuilder out = new StringBuilder(); final String[] args = StringUtils.split(uri, "/"); - final ModuleMode mode = ModuleMode.getMode(getArg(args, 1)); + final ModuleMode mode = ModuleMode.getMode(getArg(args)); switch (mode) { @@ -112,14 +110,7 @@ public class Module_schematic extends HTTPDModule } } - Collections.sort(schematicsFormatted, new Comparator() - { - @Override - public int compare(String a, String b) - { - return a.toLowerCase().compareTo(b.toLowerCase()); - } - }); + schematicsFormatted.sort(Comparator.comparing(String::toLowerCase)); out.append(HTMLGenerationTools.heading("Schematics:", 1)) .append("
      ") @@ -190,7 +181,7 @@ public class Module_schematic extends HTTPDModule return out.toString(); } - private boolean uploadSchematic(String remoteAddress) throws SchematicTransferException + private void uploadSchematic(String remoteAddress) throws SchematicTransferException { Map files = getFiles(); @@ -244,7 +235,7 @@ public class Module_schematic extends HTTPDModule } try { - ClipboardReader reader = format.getReader(new FileInputStream(targetFile)); + format.getReader(new FileInputStream(targetFile)); } catch (IOException e) { @@ -261,7 +252,6 @@ public class Module_schematic extends HTTPDModule throw new SchematicTransferException(); } - return true; } private Response downloadSchematic(String schematicName) throws SchematicTransferException diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java b/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java index d60a2e71..8d0b9bd6 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/CleanroomChunkGenerator.java @@ -20,7 +20,6 @@ package me.totalfreedom.totalfreedommod.world; import java.util.Arrays; import java.util.Random; -import java.util.SplittableRandom; import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.Material; From a4e23dc03f5b804485ebddc9240fa007c327e649 Mon Sep 17 00:00:00 2001 From: Paldiu Date: Tue, 29 Dec 2020 22:14:57 -0600 Subject: [PATCH 09/15] Codacy Complacency Part 2 --- .../totalfreedommod/TotalFreedomMod.java | 22 +++++++++------ .../httpd/module/Module_logs.java | 1 - .../httpd/module/Module_players.java | 1 - .../httpd/module/Module_punishments.java | 1 - .../httpd/module/Module_schematic.java | 27 +++++++++++++------ 5 files changed, 33 insertions(+), 19 deletions(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java b/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java index d60bcff4..d60be15a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/TotalFreedomMod.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod; -import com.sun.org.apache.xml.internal.security.Init; import java.io.File; import java.io.InputStream; import java.util.Properties; @@ -288,8 +287,10 @@ public class TotalFreedomMod extends JavaPlugin /** * This class is provided to please Codacy. */ - private final class Initializer { - public Initializer() { + private final class Initializer + { + public Initializer() + { initServices(); initAdminUtils(); initBridges(); @@ -297,7 +298,8 @@ public class TotalFreedomMod extends JavaPlugin initHTTPD(); } - private void initServices() { + private void initServices() + { // Start services si = new ServerInterface(); sf = new SavedFlags(); @@ -335,7 +337,8 @@ public class TotalFreedomMod extends JavaPlugin ptero = new Pterodactyl(); } - private void initAdminUtils() { + private void initAdminUtils() + { // Single admin utils cs = new CommandSpy(); ca = new Cager(); @@ -350,7 +353,8 @@ public class TotalFreedomMod extends JavaPlugin mo = new Monitors(); } - private void initBridges() { + private void initBridges() + { // Start bridges btb = new BukkitTelnetBridge(); cpb = new CoreProtectBridge(); @@ -361,7 +365,8 @@ public class TotalFreedomMod extends JavaPlugin wgb = new WorldGuardBridge(); } - private void initFun() { + private void initFun() + { // Fun cul = new CurseListener(); it = new ItemFun(); @@ -371,7 +376,8 @@ public class TotalFreedomMod extends JavaPlugin tr = new Trailer(); } - private void initHTTPD() { + private void initHTTPD() + { // HTTPD hd = new HTTPDaemon(); } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java index e40d191e..d9925ca3 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_logs.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.io.File; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; import me.totalfreedom.totalfreedommod.util.FLog; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java index 64217059..3ae3fbbe 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_players.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.httpd.module; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java index 88ecd9eb..09adca04 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_punishments.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.httpd.module; import java.io.File; -import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon; import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java index d9614745..808467c5 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/module/Module_schematic.java @@ -2,7 +2,6 @@ package me.totalfreedom.totalfreedommod.httpd.module; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; -import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -181,6 +180,7 @@ public class Module_schematic extends HTTPDModule return out.toString(); } + //Reduced NPath Complexity. private void uploadSchematic(String remoteAddress) throws SchematicTransferException { Map files = getFiles(); @@ -203,6 +203,21 @@ public class Module_schematic extends HTTPDModule throw new SchematicTransferException("Can't resolve original file name."); } + func1(tempFile, origFileName); + + final File targetFile = new File(SCHEMATIC_FOLDER.getPath(), origFileName); + + if (targetFile.exists()) + { + throw new SchematicTransferException("Schematic already exists on the server."); + } + + func2(tempFile, targetFile, remoteAddress); + + } + + private void func1(File tempFile, String origFileName) throws SchematicTransferException + { if (tempFile.length() > FileUtils.ONE_MB) { throw new SchematicTransferException("Schematic is too big (1mb max)."); @@ -217,13 +232,10 @@ public class Module_schematic extends HTTPDModule { throw new SchematicTransferException("File name must be alphanumeric, between 1 and 30 characters long (inclusive), and have a \".schematic\" extension."); } + } - final File targetFile = new File(SCHEMATIC_FOLDER.getPath(), origFileName); - if (targetFile.exists()) - { - throw new SchematicTransferException("Schematic already exists on the server."); - } - + private void func2(File tempFile, File targetFile, String remoteAddress) throws SchematicTransferException + { try { FileUtils.copyFile(tempFile, targetFile); @@ -251,7 +263,6 @@ public class Module_schematic extends HTTPDModule FLog.severe(ex); throw new SchematicTransferException(); } - } private Response downloadSchematic(String schematicName) throws SchematicTransferException From 0a5ce5b9cc10c238a935c222779811d07e5418b9 Mon Sep 17 00:00:00 2001 From: speed <43330808+speedxx@users.noreply.github.com> Date: Thu, 31 Dec 2020 13:06:05 -0500 Subject: [PATCH 10/15] fix w/e in mbw --- .../me/totalfreedom/totalfreedommod/world/WorldRestrictions.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldRestrictions.java b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldRestrictions.java index 0eefd78f..6ad57329 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/world/WorldRestrictions.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/world/WorldRestrictions.java @@ -38,7 +38,6 @@ public class WorldRestrictions extends FreedomService put(Flags.DESTROY_VEHICLE, StateFlag.State.DENY); put(Flags.ENTITY_ITEM_FRAME_DESTROY, StateFlag.State.DENY); put(Flags.ENTITY_PAINTING_DESTROY, StateFlag.State.DENY); - put(net.goldtreeservers.worldguardextraflags.flags.Flags.WORLDEDIT, StateFlag.State.DENY); }}; @Override From 323fd1a031481e95b708d0566af5f75b03938ee9 Mon Sep 17 00:00:00 2001 From: Paldiu Date: Mon, 4 Jan 2021 18:27:57 -0600 Subject: [PATCH 11/15] Should be fine now --- .../totalfreedommod/config/ConfigEntry.java | 13 -------- .../httpd/ModuleExecutable.java | 32 +------------------ 2 files changed, 1 insertion(+), 44 deletions(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java index 71c41f0f..de923b8e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java @@ -247,17 +247,4 @@ public enum ConfigEntry { return TotalFreedomMod.getPlugin().config; } - - public static ConfigEntry findConfigEntry(String name) - { - name = name.toLowerCase().replace("_", ""); - for (ConfigEntry entry : values()) - { - if (entry.toString().toLowerCase().replace("_", "").equals(name)) - { - return entry; - } - } - return null; - } } diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java index b6adb6de..114777b4 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.httpd; import java.lang.reflect.Constructor; -import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.httpd.module.HTTPDModule; import me.totalfreedom.totalfreedommod.util.FLog; @@ -26,14 +25,7 @@ public abstract class ModuleExecutable } // Sync to server thread - return Bukkit.getScheduler().callSyncMethod(TotalFreedomMod.getPlugin(), new Callable() - { - @Override - public NanoHTTPD.Response call() throws Exception - { - return getResponse(session); - } - }).get(); + return Bukkit.getScheduler().callSyncMethod(TotalFreedomMod.getPlugin(), () -> getResponse(session)).get(); } catch (Exception ex) @@ -75,28 +67,6 @@ public abstract class ModuleExecutable }; } - public NanoHTTPD.Response execute(final NanoHTTPD.HTTPSession session) - { - try - { - if (async) - { - return getResponse(session); - } - - // Sync to server thread - return Bukkit.getScheduler().callSyncMethod(Objects.requireNonNull(TotalFreedomMod.plugin()), () -> getResponse(session)).get(); - - } - catch (Exception ex) - { - FLog.severe(ex); - } - return null; - } - - public abstract NanoHTTPD.Response getResponse(NanoHTTPD.HTTPSession session); - public boolean isAsync() { return async; From 260368585e817c49c79a40384981ace5e14676a9 Mon Sep 17 00:00:00 2001 From: Paldiu Date: Thu, 7 Jan 2021 13:29:47 -0600 Subject: [PATCH 12/15] reformat --- .../totalfreedommod/SavedFlags.java | 1 - .../blocking/command/CommandBlockerRank.java | 1 - .../totalfreedommod/command/Command_gcmd.java | 6 +-- .../totalfreedommod/config/ConfigEntry.java | 1 - .../discord/DiscordToAdminChatListener.java | 10 ++--- .../discord/PrivateMessageListener.java | 1 - .../totalfreedommod/fun/ItemFun.java | 2 +- .../totalfreedommod/fun/Jumppads.java | 2 +- .../totalfreedommod/fun/Trailer.java | 2 +- .../httpd/ModuleExecutable.java | 44 +++++++++---------- .../permissions/PermissionEntry.java | 1 - .../totalfreedommod/player/PlayerData.java | 1 - .../totalfreedommod/util/FUtil.java | 4 +- .../totalfreedommod/util/History.java | 1 - 14 files changed, 35 insertions(+), 42 deletions(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java b/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java index d3e979e4..a86320fa 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java @@ -7,7 +7,6 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; -import java.util.Objects; import me.totalfreedom.totalfreedommod.util.FLog; import static me.totalfreedom.totalfreedommod.util.FUtil.SAVED_FLAGS_FILENAME; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerRank.java b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerRank.java index 69058055..c533b96e 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerRank.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/blocking/command/CommandBlockerRank.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.blocking.command; -import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.rank.Rank; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_gcmd.java b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_gcmd.java index 410fb8b4..7d88d686 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/command/Command_gcmd.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/command/Command_gcmd.java @@ -2,8 +2,8 @@ package me.totalfreedom.totalfreedommod.command; import me.totalfreedom.totalfreedommod.rank.Rank; import org.apache.commons.lang3.StringUtils; -import org.bukkit.command.Command; import org.bukkit.ChatColor; +import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -33,8 +33,8 @@ public class Command_gcmd extends FreedomCommand { return true; } - - if (plugin.al.isAdmin(player)) + + if (plugin.al.isAdmin(player)) { msg(ChatColor.RED + "You can not use gcmd on admins"); return true; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java index de923b8e..90aee0ac 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.config; import java.util.List; -import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToAdminChatListener.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToAdminChatListener.java index 134810f1..8d9be126 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToAdminChatListener.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/DiscordToAdminChatListener.java @@ -24,6 +24,11 @@ public class DiscordToAdminChatListener extends ListenerAdapter { DiscordToMinecraftListener dtml = new DiscordToMinecraftListener(); + public static net.md_5.bungee.api.ChatColor getColor(Displayable display) + { + return display.getColor(); + } + public void onMessageReceived(MessageReceivedEvent event) { String chat_channel_id = ConfigEntry.DISCORD_ADMINCHAT_CHANNEL_ID.getString(); @@ -87,11 +92,6 @@ public class DiscordToAdminChatListener extends ListenerAdapter } } - public static net.md_5.bungee.api.ChatColor getColor(Displayable display) - { - return display.getColor(); - } - // Needed to display tags in custom AC messages public String getDisplay(Member member) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java b/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java index 9a596488..aee47a51 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java @@ -1,6 +1,5 @@ package me.totalfreedom.totalfreedommod.discord; -import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.player.PlayerData; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java index c42a10b3..67a0b86c 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java @@ -327,7 +327,7 @@ public class ItemFun extends FreedomService //Redundant Player cast is required to avoid suspicious method calls. if (arrow != null && (arrow.getShooter() instanceof Player) - && explosivePlayers.contains((Player)arrow.getShooter())) + && explosivePlayers.contains(arrow.getShooter())) { Objects.requireNonNull(arrow.getLocation().getWorld()).createExplosion(arrow.getLocation().getX(), arrow.getLocation().getY(), arrow.getLocation().getZ(), ConfigEntry.EXPLOSIVE_RADIUS.getDouble().floatValue(), false, ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()); arrow.remove(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/Jumppads.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/Jumppads.java index b551ea4b..2341272b 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/Jumppads.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/Jumppads.java @@ -19,9 +19,9 @@ public class Jumppads extends FreedomService public static final double DAMPING_COEFFICIENT = 0.8; // private final Map pushMap = Maps.newHashMap(); - public HashMap players = new HashMap<>(); // private final double strength = 1 + 0.1F; + public HashMap players = new HashMap<>(); public static double getDampingCoefficient() { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java index 77f2c9fe..012dc4d7 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java @@ -2,8 +2,8 @@ package me.totalfreedom.totalfreedommod.fun; import java.util.HashSet; import java.util.Objects; -import java.util.SplittableRandom; import java.util.Set; +import java.util.SplittableRandom; import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.util.Groups; import org.bukkit.Location; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java index 114777b4..873f457a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java @@ -15,28 +15,6 @@ public abstract class ModuleExecutable this.async = async; } - public NanoHTTPD.Response execute(final NanoHTTPD.HTTPSession session) - { - try - { - if (async) - { - return getResponse(session); - } - - // Sync to server thread - return Bukkit.getScheduler().callSyncMethod(TotalFreedomMod.getPlugin(), () -> getResponse(session)).get(); - - } - catch (Exception ex) - { - FLog.severe(ex); - } - return null; - } - - public abstract NanoHTTPD.Response getResponse(NanoHTTPD.HTTPSession session); - public static ModuleExecutable forClass(final TotalFreedomMod plugin, Class clazz, boolean async) { final Constructor cons; @@ -67,6 +45,28 @@ public abstract class ModuleExecutable }; } + public NanoHTTPD.Response execute(final NanoHTTPD.HTTPSession session) + { + try + { + if (async) + { + return getResponse(session); + } + + // Sync to server thread + return Bukkit.getScheduler().callSyncMethod(TotalFreedomMod.getPlugin(), () -> getResponse(session)).get(); + + } + catch (Exception ex) + { + FLog.severe(ex); + } + return null; + } + + public abstract NanoHTTPD.Response getResponse(NanoHTTPD.HTTPSession session); + public boolean isAsync() { return async; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionEntry.java b/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionEntry.java index 88fe5319..08b16351 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionEntry.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/permissions/PermissionEntry.java @@ -1,7 +1,6 @@ package me.totalfreedom.totalfreedommod.permissions; import java.util.List; -import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; public enum PermissionEntry diff --git a/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java b/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java index dc56badf..942f9db4 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/player/PlayerData.java @@ -7,7 +7,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.shop.ShopItem; import me.totalfreedom.totalfreedommod.util.FLog; diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java b/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java index 63dabb29..56cac942 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/FUtil.java @@ -21,8 +21,8 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; -import java.util.SplittableRandom; import java.util.Set; +import java.util.SplittableRandom; import java.util.TimeZone; import java.util.UUID; import java.util.regex.Matcher; @@ -148,7 +148,7 @@ public class FUtil return DEVELOPER_NAMES.contains(player.getName()); } } - + public static boolean inDeveloperMode() { return ConfigEntry.DEVELOPER_MODE.getBoolean(); diff --git a/src/main/java/me/totalfreedom/totalfreedommod/util/History.java b/src/main/java/me/totalfreedom/totalfreedommod/util/History.java index adb8a28c..3c5125f2 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/util/History.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/util/History.java @@ -10,7 +10,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; -import java.util.Objects; import java.util.UUID; import me.totalfreedom.totalfreedommod.TotalFreedomMod; import org.bukkit.ChatColor; From 3464a33678f3873231f7e3d4dd2408461170abcf Mon Sep 17 00:00:00 2001 From: Paldiu Date: Fri, 8 Jan 2021 00:25:46 -0600 Subject: [PATCH 13/15] NPE on Thread.join() possible fix This bug is hard to decipher mainly due to the thread being terminated somewhere before the thread.join is called. this may be due to the safeClose method defined with serverSocket, but again, I'm not too sure what's up here. This may also be because something failed to execute in one of the try catch statements, causing the thread to never be initialized in the first place. --- .../java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java index 702c20d6..b661a982 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java @@ -251,7 +251,8 @@ public abstract class NanoHTTPD try { safeClose(myServerSocket); - myThread.join(); + //This should prevent a null pointer :) + if (myThread != null) myThread.join(); } catch (Exception e) { From 9688827a397740b8468c24bb259d0804bcbb6532 Mon Sep 17 00:00:00 2001 From: speed <43330808+speedxx@users.noreply.github.com> Date: Fri, 8 Jan 2021 10:10:54 -0500 Subject: [PATCH 14/15] formatting --- .../me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java index b661a982..c0566cc1 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java @@ -252,7 +252,10 @@ public abstract class NanoHTTPD { safeClose(myServerSocket); //This should prevent a null pointer :) - if (myThread != null) myThread.join(); + if (myThread != null) + { + myThread.join(); + } } catch (Exception e) { From 830daab8f4bf33ff75110e6c5c459b7f8c132791 Mon Sep 17 00:00:00 2001 From: Paldiu Date: Fri, 8 Jan 2021 17:32:54 -0600 Subject: [PATCH 15/15] Fix Daemon Error Reflection issue when initializing the daemon; trying to call a constructor with one argument using two arguments. Removed an unused constructor. --- .../totalfreedom/totalfreedommod/httpd/HTTPDaemon.java | 9 ++------- .../totalfreedommod/httpd/ModuleExecutable.java | 6 +++--- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java index 21b647b6..177df52a 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/HTTPDaemon.java @@ -137,7 +137,7 @@ public class HTTPDaemon extends FreedomService private void module(String name, Class clazz, boolean async) { - modules.put(name, ModuleExecutable.forClass(plugin, clazz, async)); + modules.put(name, ModuleExecutable.forClass(clazz, async)); } private class HTTPD extends NanoHTTPD @@ -146,12 +146,7 @@ public class HTTPDaemon extends FreedomService { super(port); } - - private HTTPD(String hostname, int port) - { - super(hostname, port); - } - + @Override public Response serve(HTTPSession session) { diff --git a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java index 873f457a..a345f0ac 100644 --- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java +++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java @@ -15,12 +15,12 @@ public abstract class ModuleExecutable this.async = async; } - public static ModuleExecutable forClass(final TotalFreedomMod plugin, Class clazz, boolean async) + public static ModuleExecutable forClass(Class clazz, boolean async) { final Constructor cons; try { - cons = clazz.getConstructor(TotalFreedomMod.class, NanoHTTPD.HTTPSession.class); + cons = clazz.getConstructor(NanoHTTPD.HTTPSession.class); } catch (Exception ex) { @@ -34,7 +34,7 @@ public abstract class ModuleExecutable { try { - return cons.newInstance(plugin, session).getResponse(); + return cons.newInstance(session).getResponse(); } catch (Exception ex) {