From baab6e5f88862243ad835d21589d68430e9dcae8 Mon Sep 17 00:00:00 2001 From: Risto Lahtela <24460436+AuroraLS3@users.noreply.github.com> Date: Tue, 16 Mar 2021 10:41:17 +0200 Subject: [PATCH] Fixing sonarcloud bugs and smells Bugs fixed: - LinkCommands: The return value of "orElseThrow" must be used. - RegistrationCommands: Optional isPresent not same instance as Optional get Smells fixed: - Plan: "logger" is the name of a field in "JavaPlugin" - PlayersTableJSONCreator: Reduce the total number of break and continue statements in this loop to use at most one. - BukkitAFKListener, SpongeAFKListener, NukkitAFKListener, PlanAPI, CapabilityService: match the regular expression '^[a-z][a-zA-Z0-9]*$' - TaskSystem: Reorder the modifiers to comply with the Java Language Specification. - EntityNameFormatter: StringUtils.removeAll moved to RegExUtils.removeAll - FiltersJSONResolver: fulfill compareTo contract - ExportTask: Removed duplicate string literal - FinishedSession.Id: Rename field "id" --- .../plan/capability/CapabilityService.java | 4 +- .../web/resolver/request/URIPathTest.java | 98 +++++-------------- .../main/java/com/djrapitops/plan/Plan.java | 36 +++---- .../listeners/bukkit/BukkitAFKListener.java | 12 +-- .../bukkit/PlayerOnlineListener.java | 6 +- .../gathering/timed/BukkitPingCounter.java | 20 ++-- .../java/com/djrapitops/plan/TaskSystem.java | 2 +- .../java/com/djrapitops/plan/api/PlanAPI.java | 6 +- .../plan/capability/CapabilitySvc.java | 2 +- .../commands/subcommands/LinkCommands.java | 5 +- .../subcommands/RegistrationCommands.java | 8 +- .../plan/delivery/export/ExportTask.java | 8 +- .../formatting/EntityNameFormatter.java | 3 +- .../rendering/html/structure/TabsElement.java | 4 +- .../json/PlayersTableJSONCreator.java | 43 ++++---- .../resolver/json/FiltersJSONResolver.java | 15 +++ .../gathering/domain/FinishedSession.java | 8 +- .../listeners/nukkit/NukkitAFKListener.java | 12 +-- .../nukkit/PlayerOnlineListener.java | 6 +- .../sponge/PlayerOnlineListener.java | 6 +- .../listeners/sponge/SpongeAFKListener.java | 12 +-- 21 files changed, 143 insertions(+), 173 deletions(-) diff --git a/Plan/api/src/main/java/com/djrapitops/plan/capability/CapabilityService.java b/Plan/api/src/main/java/com/djrapitops/plan/capability/CapabilityService.java index 48f03d7a4..568d5be97 100644 --- a/Plan/api/src/main/java/com/djrapitops/plan/capability/CapabilityService.java +++ b/Plan/api/src/main/java/com/djrapitops/plan/capability/CapabilityService.java @@ -50,7 +50,7 @@ public interface CapabilityService { * @param isEnabledListener The boolean given to the method tells if Plan has enabled successfully. */ default void registerEnableListener(Consumer isEnabledListener) { - ListHolder.ENABLE_LISTENERS.get().add(isEnabledListener); + ListHolder.enableListeners.get().add(isEnabledListener); } /** @@ -65,7 +65,7 @@ public interface CapabilityService { } class ListHolder { - static volatile AtomicReference>> ENABLE_LISTENERS = new AtomicReference<>( + static volatile AtomicReference>> enableListeners = new AtomicReference<>( new CopyOnWriteArrayList<>() ); diff --git a/Plan/api/src/test/java/com/djrapitops/plan/delivery/web/resolver/request/URIPathTest.java b/Plan/api/src/test/java/com/djrapitops/plan/delivery/web/resolver/request/URIPathTest.java index e6aafa201..4c4f71f77 100644 --- a/Plan/api/src/test/java/com/djrapitops/plan/delivery/web/resolver/request/URIPathTest.java +++ b/Plan/api/src/test/java/com/djrapitops/plan/delivery/web/resolver/request/URIPathTest.java @@ -17,6 +17,8 @@ package com.djrapitops.plan.delivery.web.resolver.request; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import java.util.Optional; @@ -29,14 +31,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ class URIPathTest { - @Test - void firstPartEmptyForRoot() { - URIPath target = new URIPath("/"); - Optional expected = Optional.of(""); - Optional result = target.getPart(0); - assertEquals(expected, result); - } - @Test void fullTargetForRoot() { URIPath target = new URIPath("/"); @@ -45,14 +39,6 @@ class URIPathTest { assertEquals(expected, result); } - @Test - void firstPart() { - URIPath target = new URIPath("/example/target"); - Optional expected = Optional.of("example"); - Optional result = target.getPart(0); - assertEquals(expected, result); - } - @Test void fullTarget() { URIPath target = new URIPath("/example/target"); @@ -61,11 +47,17 @@ class URIPathTest { assertEquals(expected, result); } - @Test - void secondPart() { - URIPath target = new URIPath("/example/target"); - Optional expected = Optional.of("target"); - Optional result = target.getPart(1); + @ParameterizedTest + @CsvSource({ + "/", "0", "", + "/example/target", "0", "example", + "/example/target", "1", "target", + "/example/target/", "2", "", + }) + void partGettingWorksProperly(String targetURI, int partNumber, String expectedPart) { + URIPath target = new URIPath(targetURI); + Optional expected = Optional.ofNullable(expectedPart); + Optional result = target.getPart(partNumber); assertEquals(expected, result); } @@ -77,14 +69,6 @@ class URIPathTest { assertEquals(expected, result); } - @Test - void emptyLastPart() { - URIPath target = new URIPath("/example/target/"); - Optional expected = Optional.of(""); - Optional result = target.getPart(2); - assertEquals(expected, result); - } - @Test void omitRoot() { URIPath target = new URIPath("/").omitFirst(); @@ -117,51 +101,17 @@ class URIPathTest { assertEquals(expected, result); } - @Test - void partsAreRemoved() { - String test = "/example/target"; - String expected = "/target"; - String result = URIPath.removePartsBefore(test, 1); - assertEquals(expected, result); - } - - @Test - void partsAreRemoved2() { - String test = "/example/target/"; - String expected = "/"; - String result = URIPath.removePartsBefore(test, 2); - assertEquals(expected, result); - } - - @Test - void partsAreRemoved3() { - String test = "/example/target"; - String expected = ""; - String result = URIPath.removePartsBefore(test, 2); - assertEquals(expected, result); - } - - @Test - void partsAreRemoved4() { - String test = "/example/target"; - String expected = "/example/target"; - String result = URIPath.removePartsBefore(test, 0); - assertEquals(expected, result); - } - - @Test - void partsAreRemoved5() { - String test = "/example/target/"; - String expected = "/"; - String result = URIPath.removePartsBefore(test, 2); - assertEquals(expected, result); - } - - @Test - void noPartsToRemove() { - String test = ""; - String expected = ""; - String result = URIPath.removePartsBefore(test, 1); + @ParameterizedTest + @CsvSource({ + "/example/target", "1", "/target", + "/example/target/", "2", "/", + "/example/target", "2", "", + "/example/target", "0", "/example/target", + "/example/target/", "1", "/target/", + "", "1", "" + }) + void partsAreRemoved(String test, int removeThisMany, String expected) { + String result = URIPath.removePartsBefore(test, removeThisMany); assertEquals(expected, result); } diff --git a/Plan/bukkit/src/main/java/com/djrapitops/plan/Plan.java b/Plan/bukkit/src/main/java/com/djrapitops/plan/Plan.java index 0496333e2..285fa92bf 100644 --- a/Plan/bukkit/src/main/java/com/djrapitops/plan/Plan.java +++ b/Plan/bukkit/src/main/java/com/djrapitops/plan/Plan.java @@ -53,18 +53,18 @@ public class Plan extends JavaPlugin implements PlanPlugin { private Locale locale; private ServerShutdownSave serverShutdownSave; - private PluginLogger logger; + private PluginLogger pluginLogger; private RunnableFactory runnableFactory; private PlatformAbstractionLayer abstractionLayer; @Override public void onLoad() { abstractionLayer = new BukkitPlatformLayer(this); - logger = abstractionLayer.getPluginLogger(); + pluginLogger = abstractionLayer.getPluginLogger(); runnableFactory = abstractionLayer.getRunnableFactory(); try { - new DependencyStartup(logger, abstractionLayer.getDependencyLoader()).loadDependencies(); + new DependencyStartup(pluginLogger, abstractionLayer.getDependencyLoader()).loadDependencies(); } catch (IOException e) { getLogger().log(Level.SEVERE, e, () -> this.getClass().getSimpleName()); } @@ -86,20 +86,20 @@ public class Plan extends JavaPlugin implements PlanPlugin { registerMetrics(); registerPlaceholderAPIExtension(component.placeholders()); - logger.info(locale.getString(PluginLang.ENABLED)); + pluginLogger.info(locale.getString(PluginLang.ENABLED)); } catch (AbstractMethodError e) { - logger.error("Plugin ran into AbstractMethodError - Server restart is required. Likely cause is updating the jar without a restart."); + pluginLogger.error("Plugin ran into AbstractMethodError - Server restart is required. Likely cause is updating the jar without a restart."); } catch (EnableException e) { - logger.error("----------------------------------------"); - logger.error("Error: " + e.getMessage()); - logger.error("----------------------------------------"); - logger.error("Plugin Failed to Initialize Correctly. If this issue is caused by config settings you can use /plan reload"); + pluginLogger.error("----------------------------------------"); + pluginLogger.error("Error: " + e.getMessage()); + pluginLogger.error("----------------------------------------"); + pluginLogger.error("Plugin Failed to Initialize Correctly. If this issue is caused by config settings you can use /plan reload"); onDisable(); } catch (Exception e) { String version = abstractionLayer.getPluginInformation().getVersion(); getLogger().log(Level.SEVERE, e, () -> this.getClass().getSimpleName() + "-v" + version); - logger.error("Plugin Failed to Initialize Correctly. If this issue is caused by config settings you can use /plan reload"); - logger.error("This error should be reported at https://github.com/plan-player-analytics/Plan/issues"); + pluginLogger.error("Plugin Failed to Initialize Correctly. If this issue is caused by config settings you can use /plan reload"); + pluginLogger.error("This error should be reported at https://github.com/plan-player-analytics/Plan/issues"); onDisable(); } registerCommand(component.planCommand().build()); @@ -114,7 +114,7 @@ public class Plan extends JavaPlugin implements PlanPlugin { try { placeholders.register(); } catch (Exception | NoClassDefFoundError | NoSuchMethodError failed) { - logger.warn("Failed to register PlaceholderAPI placeholders: " + failed.toString()); + pluginLogger.warn("Failed to register PlaceholderAPI placeholders: " + failed.toString()); } } ).runTask(); @@ -131,7 +131,7 @@ public class Plan extends JavaPlugin implements PlanPlugin { @Override public ColorScheme getColorScheme() { - return PlanColorScheme.create(system.getConfigSystem().getConfig(), logger); + return PlanColorScheme.create(system.getConfigSystem().getConfig(), pluginLogger); } @Override @@ -140,7 +140,7 @@ public class Plan extends JavaPlugin implements PlanPlugin { cancelAllTasks(); if (system != null) system.disable(); - logger.info(Locale.getStringNullSafe(locale, PluginLang.DISABLED)); + pluginLogger.info(Locale.getStringNullSafe(locale, PluginLang.DISABLED)); } private void storeSessionsOnShutdown() { @@ -152,9 +152,9 @@ public class Plan extends JavaPlugin implements PlanPlugin { } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { - logger.error("Failed to save sessions to database on shutdown: " + e.getCause().getMessage()); + pluginLogger.error("Failed to save sessions to database on shutdown: " + e.getCause().getMessage()); } catch (TimeoutException e) { - logger.info(Locale.getStringNullSafe(locale, PluginLang.DISABLED_UNSAVED_SESSIONS_TIMEOUT)); + pluginLogger.info(Locale.getStringNullSafe(locale, PluginLang.DISABLED_UNSAVED_SESSIONS_TIMEOUT)); } } } @@ -168,13 +168,13 @@ public class Plan extends JavaPlugin implements PlanPlugin { @Override public void registerCommand(Subcommand command) { if (command == null) { - logger.warn("Attempted to register a null command!"); + pluginLogger.warn("Attempted to register a null command!"); return; } for (String name : command.getAliases()) { PluginCommand registering = getCommand(name); if (registering == null) { - logger.warn("Attempted to register '" + name + "'-command, but it is not in plugin.yml!"); + pluginLogger.warn("Attempted to register '" + name + "'-command, but it is not in plugin.yml!"); continue; } registering.setExecutor(new BukkitCommand(runnableFactory, system.getErrorLogger(), command)); diff --git a/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/listeners/bukkit/BukkitAFKListener.java b/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/listeners/bukkit/BukkitAFKListener.java index 8f32e5f57..7e46c1f57 100644 --- a/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/listeners/bukkit/BukkitAFKListener.java +++ b/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/listeners/bukkit/BukkitAFKListener.java @@ -43,7 +43,7 @@ import java.util.UUID; public class BukkitAFKListener implements Listener { // Static so that /reload does not cause afk tracking to fail. - static AFKTracker AFK_TRACKER; + static AFKTracker afkTracker; private final Map ignorePermissionInfo; private final ErrorLogger errorLogger; @@ -57,8 +57,8 @@ public class BukkitAFKListener implements Listener { } private static void assignAFKTracker(PlanConfig config) { - if (AFK_TRACKER == null) { - AFK_TRACKER = new AFKTracker(config); + if (afkTracker == null) { + afkTracker = new AFKTracker(config); } } @@ -70,14 +70,14 @@ public class BukkitAFKListener implements Listener { boolean ignored = ignorePermissionInfo.computeIfAbsent(uuid, keyUUID -> player.hasPermission(Permissions.IGNORE_AFK.getPermission())); if (ignored) { - AFK_TRACKER.hasIgnorePermission(uuid); + afkTracker.hasIgnorePermission(uuid); ignorePermissionInfo.put(uuid, true); return; } else { ignorePermissionInfo.put(uuid, false); } - AFK_TRACKER.performedAction(uuid, time); + afkTracker.performedAction(uuid, time); } catch (Exception e) { errorLogger.error(e, ErrorContext.builder().related(event).build()); } @@ -99,7 +99,7 @@ public class BukkitAFKListener implements Listener { boolean isAfkCommand = event.getMessage().substring(1).toLowerCase().startsWith("afk"); if (isAfkCommand) { UUID uuid = event.getPlayer().getUniqueId(); - AFK_TRACKER.usedAfkCommand(uuid, System.currentTimeMillis()); + afkTracker.usedAfkCommand(uuid, System.currentTimeMillis()); } } diff --git a/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/listeners/bukkit/PlayerOnlineListener.java b/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/listeners/bukkit/PlayerOnlineListener.java index c3f5118f1..ad4162d7c 100644 --- a/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/listeners/bukkit/PlayerOnlineListener.java +++ b/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/listeners/bukkit/PlayerOnlineListener.java @@ -127,7 +127,7 @@ public class PlayerOnlineListener implements Listener { return; } UUID uuid = event.getPlayer().getUniqueId(); - if (BukkitAFKListener.AFK_TRACKER.isAfk(uuid)) { + if (BukkitAFKListener.afkTracker.isAfk(uuid)) { return; } @@ -153,7 +153,7 @@ public class PlayerOnlineListener implements Listener { ServerUUID serverUUID = serverInfo.getServerUUID(); long time = System.currentTimeMillis(); - BukkitAFKListener.AFK_TRACKER.performedAction(playerUUID, time); + BukkitAFKListener.afkTracker.performedAction(playerUUID, time); String world = player.getWorld().getName(); String gm = player.getGameMode().name(); @@ -217,7 +217,7 @@ public class PlayerOnlineListener implements Listener { String playerName = player.getName(); UUID playerUUID = player.getUniqueId(); - BukkitAFKListener.AFK_TRACKER.loggedOut(playerUUID, time); + BukkitAFKListener.afkTracker.loggedOut(playerUUID, time); nicknameCache.removeDisplayName(playerUUID); diff --git a/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/timed/BukkitPingCounter.java b/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/timed/BukkitPingCounter.java index 998a71f5d..0532e8263 100644 --- a/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/timed/BukkitPingCounter.java +++ b/Plan/bukkit/src/main/java/com/djrapitops/plan/gathering/timed/BukkitPingCounter.java @@ -67,10 +67,10 @@ public class BukkitPingCounter extends TaskSystem.Task implements Listener { //the server is pinging the client every 40 Ticks (2 sec) - so check it then //https://github.com/bergerkiller/CraftSource/blob/master/net.minecraft.server/PlayerConnection.java#L178 - private static boolean PING_METHOD_AVAILABLE; + private static boolean pingMethodAvailable; - private static MethodHandle PING_FIELD; - private static MethodHandle GET_HANDLE_METHOD; + private static MethodHandle pingField; + private static MethodHandle getHandleMethod; private final Map>> playerHistory; @@ -99,11 +99,11 @@ public class BukkitPingCounter extends TaskSystem.Task implements Listener { private static void loadPingMethodDetails() { - PING_METHOD_AVAILABLE = isPingMethodAvailable(); + pingMethodAvailable = isPingMethodAvailable(); MethodHandle localHandle = null; MethodHandle localPing = null; - if (!PING_METHOD_AVAILABLE) { + if (!pingMethodAvailable) { try { Class craftPlayerClass = Reflection.getCraftBukkitClass("entity.CraftPlayer"); Class entityPlayer = Reflection.getMinecraftClass("EntityPlayer"); @@ -127,8 +127,8 @@ public class BukkitPingCounter extends TaskSystem.Task implements Listener { } } - GET_HANDLE_METHOD = localHandle; - PING_FIELD = localPing; + getHandleMethod = localHandle; + pingField = localPing; } private static boolean isPingMethodAvailable() { @@ -190,7 +190,7 @@ public class BukkitPingCounter extends TaskSystem.Task implements Listener { } private int getPing(Player player) { - if (PING_METHOD_AVAILABLE) { + if (pingMethodAvailable) { // This method is from Paper return player.spigot().getPing(); } @@ -200,8 +200,8 @@ public class BukkitPingCounter extends TaskSystem.Task implements Listener { private int getReflectionPing(Player player) { try { - Object entityPlayer = GET_HANDLE_METHOD.invoke(player); - return (int) PING_FIELD.invoke(entityPlayer); + Object entityPlayer = getHandleMethod.invoke(player); + return (int) pingField.invoke(entityPlayer); } catch (Exception ex) { return -1; } catch (Throwable throwable) { diff --git a/Plan/common/src/main/java/com/djrapitops/plan/TaskSystem.java b/Plan/common/src/main/java/com/djrapitops/plan/TaskSystem.java index 0417c2f16..5a1418927 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/TaskSystem.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/TaskSystem.java @@ -62,7 +62,7 @@ public class TaskSystem implements SubSystem { return Optional.empty(); } - public static abstract class Task extends PluginRunnable { + public abstract static class Task extends PluginRunnable { public abstract void register(RunnableFactory runnableFactory); } diff --git a/Plan/common/src/main/java/com/djrapitops/plan/api/PlanAPI.java b/Plan/common/src/main/java/com/djrapitops/plan/api/PlanAPI.java index 74536d71d..8e1724a6a 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/api/PlanAPI.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/api/PlanAPI.java @@ -41,16 +41,16 @@ import java.util.UUID; public interface PlanAPI { static PlanAPI getInstance() { - return Optional.ofNullable(PlanAPIHolder.API) + return Optional.ofNullable(PlanAPIHolder.api) .orElseThrow(() -> new IllegalStateException("PlanAPI has not been initialised yet.")); } @Singleton class PlanAPIHolder { - static PlanAPI API; + static PlanAPI api; static void set(PlanAPI api) { - PlanAPIHolder.API = api; + PlanAPIHolder.api = api; } @Inject diff --git a/Plan/common/src/main/java/com/djrapitops/plan/capability/CapabilitySvc.java b/Plan/common/src/main/java/com/djrapitops/plan/capability/CapabilitySvc.java index 8bb484577..6c2ba5022 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/capability/CapabilitySvc.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/capability/CapabilitySvc.java @@ -37,7 +37,7 @@ public class CapabilitySvc implements CapabilityService { * @param isEnabled Did the plugin enable properly. */ public static void notifyAboutEnable(boolean isEnabled) { - for (Consumer enableListener : CapabilityService.ListHolder.ENABLE_LISTENERS.get()) { + for (Consumer enableListener : CapabilityService.ListHolder.enableListeners.get()) { enableListener.accept(isEnabled); } } diff --git a/Plan/common/src/main/java/com/djrapitops/plan/commands/subcommands/LinkCommands.java b/Plan/common/src/main/java/com/djrapitops/plan/commands/subcommands/LinkCommands.java index a2699aca9..2f8194d0a 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/commands/subcommands/LinkCommands.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/commands/subcommands/LinkCommands.java @@ -198,8 +198,9 @@ public class LinkCommands { .addPart(colors.getMainColor() + locale.getString(CommandLang.LINK_NETWORK)) .apply(builder -> linkTo(builder, sender, address)) .send(); - dbSystem.getDatabase().query(ServerQueries.fetchProxyServerInformation()) - .orElseThrow(() -> new IllegalArgumentException(locale.getString(CommandLang.NOTIFY_NO_NETWORK))); + if (!dbSystem.getDatabase().query(ServerQueries.fetchProxyServerInformation()).isPresent()) { + throw new IllegalArgumentException(locale.getString(CommandLang.NOTIFY_NO_NETWORK)); + } } /** diff --git a/Plan/common/src/main/java/com/djrapitops/plan/commands/subcommands/RegistrationCommands.java b/Plan/common/src/main/java/com/djrapitops/plan/commands/subcommands/RegistrationCommands.java index 78ce721b8..e4a000638 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/commands/subcommands/RegistrationCommands.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/commands/subcommands/RegistrationCommands.java @@ -119,9 +119,11 @@ public class RegistrationCommands { .filter(arg -> sender.hasPermission(Permissions.REGISTER_OTHER)) // argument only allowed with register other permission .orElseGet(() -> getPermissionLevel(sender)); - if (sender.getUUID().isPresent() && sender.getPlayerName().isPresent()) { - String playerName = sender.getPlayerName().get(); - UUID linkedToUUID = sender.getUUID().get(); + Optional senderUUID = sender.getUUID(); + Optional senderName = sender.getPlayerName(); + if (senderUUID.isPresent() && senderName.isPresent()) { + String playerName = senderName.get(); + UUID linkedToUUID = senderUUID.get(); String username = arguments.get(1).orElse(playerName); registerUser(new User(username, playerName, linkedToUUID, passwordHash, permissionLevel, Collections.emptyList()), sender, permissionLevel); } else { diff --git a/Plan/common/src/main/java/com/djrapitops/plan/delivery/export/ExportTask.java b/Plan/common/src/main/java/com/djrapitops/plan/delivery/export/ExportTask.java index e52efd1d7..c8052d8cc 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/delivery/export/ExportTask.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/delivery/export/ExportTask.java @@ -44,13 +44,13 @@ public class ExportTask extends PluginRunnable { try { exportAction.accept(exporter); } catch (ExportException e) { - errorLogger.warn(e, ErrorContext.builder().related("Export task run").build()); + errorLogger.warn(e, ErrorContext.builder().related(getClass()).build()); } catch (DBOpException dbException) { handleDBException(dbException); } catch (Exception | NoClassDefFoundError | NoSuchMethodError | NoSuchFieldError e) { errorLogger.error(e, ErrorContext.builder() .whatToDo("Export Task Disabled due to error - reload Plan to re-enable.") - .related("Export task run").build()); + .related(getClass()).build()); cancel(); } } @@ -59,11 +59,11 @@ public class ExportTask extends PluginRunnable { if (dbException.getMessage().contains("closed")) { errorLogger.error(dbException, ErrorContext.builder() .whatToDo("Export Task Disabled due to error - database is closing, so this error can be ignored.).") - .related("Export task run").build()); + .related(getClass()).build()); } else { errorLogger.error(dbException, ErrorContext.builder() .whatToDo("Export Task Disabled due to error - reload Plan to re-enable.") - .related("Export task run").build()); + .related(getClass()).build()); } cancel(); } diff --git a/Plan/common/src/main/java/com/djrapitops/plan/delivery/formatting/EntityNameFormatter.java b/Plan/common/src/main/java/com/djrapitops/plan/delivery/formatting/EntityNameFormatter.java index e369582df..a9ec41459 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/delivery/formatting/EntityNameFormatter.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/delivery/formatting/EntityNameFormatter.java @@ -16,6 +16,7 @@ */ package com.djrapitops.plan.delivery.formatting; +import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.StringUtils; /** @@ -28,7 +29,7 @@ public class EntityNameFormatter implements Formatter { @Override public String apply(String name) { return StringUtils.capitalize( - StringUtils.removeAll(name, "[^a-zA-Z0-9_\\\\s]*").toLowerCase() + RegExUtils.removeAll(name, "[^a-zA-Z0-9_\\\\s]*").toLowerCase() ); } } \ No newline at end of file diff --git a/Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/html/structure/TabsElement.java b/Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/html/structure/TabsElement.java index c0c33b977..5d843bd6b 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/html/structure/TabsElement.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/html/structure/TabsElement.java @@ -16,7 +16,7 @@ */ package com.djrapitops.plan.delivery.rendering.html.structure; -import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.RegExUtils; /** * Represents a structural HTML element that has Tabs on the top. @@ -81,7 +81,7 @@ public class TabsElement { } public String getId() { - return "tab_" + StringUtils.removeAll(navText, "[^a-zA-Z0-9]*").toLowerCase(); + return "tab_" + RegExUtils.removeAll(navText, "[^a-zA-Z0-9]*").toLowerCase(); } } } diff --git a/Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/json/PlayersTableJSONCreator.java b/Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/json/PlayersTableJSONCreator.java index 98004522f..35e8975fa 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/json/PlayersTableJSONCreator.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/json/PlayersTableJSONCreator.java @@ -160,30 +160,31 @@ public class PlayersTableJSONCreator { private void addExtensionData(Map dataJson, ExtensionTabData tabData) { for (ExtensionDescriptive descriptive : extensionDescriptives) { - String key = descriptive.getName(); - - // If it's a double, append a double - Optional doubleValue = tabData.getDouble(key); - - if (doubleValue.isPresent()) { - putDataEntry(dataJson, doubleValue.get().getRawValue(), doubleValue.get().getFormattedValue(decimalFormatter), key); - continue; - } - - Optional numberValue = tabData.getNumber(key); - if (numberValue.isPresent()) { - ExtensionNumberData numberData = numberValue.get(); - FormatType formatType = numberData.getFormatType(); - putDataEntry(dataJson, numberData.getRawValue(), numberData.getFormattedValue(numberFormatters.get(formatType)), key); - continue; - } - - // If it's a String add a String, otherwise the player has no value for this extension provider. - String stringValue = tabData.getString(key).map(ExtensionStringData::getFormattedValue).orElse("-"); - putDataEntry(dataJson, stringValue, stringValue, key); + addValue(dataJson, tabData, descriptive.getName()); } } + private void addValue(Map dataJson, ExtensionTabData tabData, String key) { + // If it's a double, put a double + Optional doubleValue = tabData.getDouble(key); + if (doubleValue.isPresent()) { + putDataEntry(dataJson, doubleValue.get().getRawValue(), doubleValue.get().getFormattedValue(decimalFormatter), key); + return; + } + + Optional numberValue = tabData.getNumber(key); + if (numberValue.isPresent()) { + ExtensionNumberData numberData = numberValue.get(); + FormatType formatType = numberData.getFormatType(); + putDataEntry(dataJson, numberData.getRawValue(), numberData.getFormattedValue(numberFormatters.get(formatType)), key); + return; + } + + // If it's a String add a String, otherwise the player has no value for this extension provider. + String stringValue = tabData.getString(key).map(ExtensionStringData::getFormattedValue).orElse("-"); + putDataEntry(dataJson, stringValue, stringValue, key); + } + private List> createColumnHeaders() { List> columnHeaders = new ArrayList<>(); diff --git a/Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/resolver/json/FiltersJSONResolver.java b/Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/resolver/json/FiltersJSONResolver.java index 4c3b8b2cb..bef7819a2 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/resolver/json/FiltersJSONResolver.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/resolver/json/FiltersJSONResolver.java @@ -136,6 +136,21 @@ public class FiltersJSONResolver implements Resolver { this.expectedParameters = filter.getExpectedParameters(); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FilterJSON that = (FilterJSON) o; + return Objects.equals(kind, that.kind) && Objects.equals(options, that.options) && Arrays.equals(expectedParameters, that.expectedParameters); + } + + @Override + public int hashCode() { + int result = Objects.hash(kind, options); + result = 31 * result + Arrays.hashCode(expectedParameters); + return result; + } + @Override public int compareTo(FilterJSON o) { return String.CASE_INSENSITIVE_ORDER.compare(this.kind, o.kind); diff --git a/Plan/common/src/main/java/com/djrapitops/plan/gathering/domain/FinishedSession.java b/Plan/common/src/main/java/com/djrapitops/plan/gathering/domain/FinishedSession.java index 99a159b24..919398a44 100644 --- a/Plan/common/src/main/java/com/djrapitops/plan/gathering/domain/FinishedSession.java +++ b/Plan/common/src/main/java/com/djrapitops/plan/gathering/domain/FinishedSession.java @@ -146,14 +146,14 @@ public class FinishedSession implements DateHolder { } public static class Id { - private final int id; + private final int value; - public Id(int id) { - this.id = id; + public Id(int value) { + this.value = value; } public int get() { - return id; + return value; } } diff --git a/Plan/nukkit/src/main/java/com/djrapitops/plan/gathering/listeners/nukkit/NukkitAFKListener.java b/Plan/nukkit/src/main/java/com/djrapitops/plan/gathering/listeners/nukkit/NukkitAFKListener.java index 354202c79..2bf59f55e 100644 --- a/Plan/nukkit/src/main/java/com/djrapitops/plan/gathering/listeners/nukkit/NukkitAFKListener.java +++ b/Plan/nukkit/src/main/java/com/djrapitops/plan/gathering/listeners/nukkit/NukkitAFKListener.java @@ -43,7 +43,7 @@ import java.util.UUID; public class NukkitAFKListener implements Listener { // Static so that /reload does not cause afk tracking to fail. - static AFKTracker AFK_TRACKER; + static AFKTracker afkTracker; private final Map ignorePermissionInfo; private final ErrorLogger errorLogger; @@ -60,8 +60,8 @@ public class NukkitAFKListener implements Listener { } private static void assignAFKTracker(PlanConfig config) { - if (AFK_TRACKER == null) { - AFK_TRACKER = new AFKTracker(config); + if (afkTracker == null) { + afkTracker = new AFKTracker(config); } } @@ -73,14 +73,14 @@ public class NukkitAFKListener implements Listener { boolean ignored = ignorePermissionInfo.computeIfAbsent(uuid, keyUUID -> player.hasPermission(Permissions.IGNORE_AFK.getPermission())); if (ignored) { - AFK_TRACKER.hasIgnorePermission(uuid); + afkTracker.hasIgnorePermission(uuid); ignorePermissionInfo.put(uuid, true); return; } else { ignorePermissionInfo.put(uuid, false); } - AFK_TRACKER.performedAction(uuid, time); + afkTracker.performedAction(uuid, time); } catch (Exception e) { errorLogger.error(e, ErrorContext.builder().related(event).build()); } @@ -102,7 +102,7 @@ public class NukkitAFKListener implements Listener { boolean isAfkCommand = event.getMessage().substring(1).toLowerCase().startsWith("afk"); if (isAfkCommand) { UUID uuid = event.getPlayer().getUniqueId(); - AFK_TRACKER.usedAfkCommand(uuid, System.currentTimeMillis()); + afkTracker.usedAfkCommand(uuid, System.currentTimeMillis()); } } diff --git a/Plan/nukkit/src/main/java/com/djrapitops/plan/gathering/listeners/nukkit/PlayerOnlineListener.java b/Plan/nukkit/src/main/java/com/djrapitops/plan/gathering/listeners/nukkit/PlayerOnlineListener.java index 1b1a9e76b..a18a1e8a2 100644 --- a/Plan/nukkit/src/main/java/com/djrapitops/plan/gathering/listeners/nukkit/PlayerOnlineListener.java +++ b/Plan/nukkit/src/main/java/com/djrapitops/plan/gathering/listeners/nukkit/PlayerOnlineListener.java @@ -126,7 +126,7 @@ public class PlayerOnlineListener implements Listener { return; } UUID uuid = event.getPlayer().getUniqueId(); - if (NukkitAFKListener.AFK_TRACKER.isAfk(uuid)) { + if (NukkitAFKListener.afkTracker.isAfk(uuid)) { return; } @@ -152,7 +152,7 @@ public class PlayerOnlineListener implements Listener { ServerUUID serverUUID = serverInfo.getServerUUID(); long time = System.currentTimeMillis(); - NukkitAFKListener.AFK_TRACKER.performedAction(playerUUID, time); + NukkitAFKListener.afkTracker.performedAction(playerUUID, time); String world = player.getLevel().getName(); String gm = GMTimes.magicNumberToGMName(player.getGamemode()); @@ -217,7 +217,7 @@ public class PlayerOnlineListener implements Listener { UUID playerUUID = player.getUniqueId(); if (playerUUID == null) return; // Can be null when player is not signed in to xbox live - NukkitAFKListener.AFK_TRACKER.loggedOut(playerUUID, time); + NukkitAFKListener.afkTracker.loggedOut(playerUUID, time); nicknameCache.removeDisplayName(playerUUID); diff --git a/Plan/sponge/src/main/java/com/djrapitops/plan/gathering/listeners/sponge/PlayerOnlineListener.java b/Plan/sponge/src/main/java/com/djrapitops/plan/gathering/listeners/sponge/PlayerOnlineListener.java index 192d608a1..0260ac671 100644 --- a/Plan/sponge/src/main/java/com/djrapitops/plan/gathering/listeners/sponge/PlayerOnlineListener.java +++ b/Plan/sponge/src/main/java/com/djrapitops/plan/gathering/listeners/sponge/PlayerOnlineListener.java @@ -121,7 +121,7 @@ public class PlayerOnlineListener { public void onKick(KickPlayerEvent event) { try { UUID playerUUID = event.getTargetEntity().getUniqueId(); - if (status.areKicksNotCounted() || SpongeAFKListener.AFK_TRACKER.isAfk(playerUUID)) { + if (status.areKicksNotCounted() || SpongeAFKListener.afkTracker.isAfk(playerUUID)) { return; } dbSystem.getDatabase().executeTransaction(new KickStoreTransaction(playerUUID)); @@ -155,7 +155,7 @@ public class PlayerOnlineListener { ServerUUID serverUUID = serverInfo.getServerUUID(); long time = System.currentTimeMillis(); - SpongeAFKListener.AFK_TRACKER.performedAction(playerUUID, time); + SpongeAFKListener.afkTracker.performedAction(playerUUID, time); String world = player.getWorld().getName(); Optional gameMode = player.getGameModeData().get(Keys.GAME_MODE); @@ -219,7 +219,7 @@ public class PlayerOnlineListener { String playerName = player.getName(); UUID playerUUID = player.getUniqueId(); - SpongeAFKListener.AFK_TRACKER.loggedOut(playerUUID, time); + SpongeAFKListener.afkTracker.loggedOut(playerUUID, time); nicknameCache.removeDisplayName(playerUUID); diff --git a/Plan/sponge/src/main/java/com/djrapitops/plan/gathering/listeners/sponge/SpongeAFKListener.java b/Plan/sponge/src/main/java/com/djrapitops/plan/gathering/listeners/sponge/SpongeAFKListener.java index f00544a65..3d4991a4b 100644 --- a/Plan/sponge/src/main/java/com/djrapitops/plan/gathering/listeners/sponge/SpongeAFKListener.java +++ b/Plan/sponge/src/main/java/com/djrapitops/plan/gathering/listeners/sponge/SpongeAFKListener.java @@ -48,7 +48,7 @@ import java.util.UUID; public class SpongeAFKListener { // Static so that /reload does not cause afk tracking to fail. - static AFKTracker AFK_TRACKER; + static AFKTracker afkTracker; private final Map ignorePermissionInfo; private final ErrorLogger errorLogger; @@ -62,8 +62,8 @@ public class SpongeAFKListener { } private static void assignAFKTracker(PlanConfig config) { - if (AFK_TRACKER == null) { - AFK_TRACKER = new AFKTracker(config); + if (afkTracker == null) { + afkTracker = new AFKTracker(config); } } @@ -91,14 +91,14 @@ public class SpongeAFKListener { boolean ignored = ignorePermissionInfo.computeIfAbsent(uuid, keyUUID -> player.hasPermission(Permissions.IGNORE_AFK.getPermission())); if (ignored) { - AFK_TRACKER.hasIgnorePermission(uuid); + afkTracker.hasIgnorePermission(uuid); ignorePermissionInfo.put(uuid, true); return; } else { ignorePermissionInfo.put(uuid, false); } - AFK_TRACKER.performedAction(uuid, time); + afkTracker.performedAction(uuid, time); } @Listener(order = Order.POST) @@ -107,7 +107,7 @@ public class SpongeAFKListener { boolean isAfkCommand = event.getCommand().toLowerCase().startsWith("afk"); if (isAfkCommand) { - AFK_TRACKER.usedAfkCommand(player.getUniqueId(), System.currentTimeMillis()); + afkTracker.usedAfkCommand(player.getUniqueId(), System.currentTimeMillis()); } }