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"
This commit is contained in:
Risto Lahtela 2021-03-16 10:41:17 +02:00
parent c54c3ce88b
commit baab6e5f88
21 changed files with 143 additions and 173 deletions

View File

@ -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<Boolean> isEnabledListener) {
ListHolder.ENABLE_LISTENERS.get().add(isEnabledListener);
ListHolder.enableListeners.get().add(isEnabledListener);
}
/**
@ -65,7 +65,7 @@ public interface CapabilityService {
}
class ListHolder {
static volatile AtomicReference<List<Consumer<Boolean>>> ENABLE_LISTENERS = new AtomicReference<>(
static volatile AtomicReference<List<Consumer<Boolean>>> enableListeners = new AtomicReference<>(
new CopyOnWriteArrayList<>()
);

View File

@ -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<String> expected = Optional.of("");
Optional<String> 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<String> expected = Optional.of("example");
Optional<String> 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<String> expected = Optional.of("target");
Optional<String> 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<String> expected = Optional.ofNullable(expectedPart);
Optional<String> 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<String> expected = Optional.of("");
Optional<String> 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);
}

View File

@ -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));

View File

@ -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<UUID, Boolean> 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());
}
}

View File

@ -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);

View File

@ -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<UUID, List<DateObj<Integer>>> 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) {

View File

@ -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);
}

View File

@ -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

View File

@ -37,7 +37,7 @@ public class CapabilitySvc implements CapabilityService {
* @param isEnabled Did the plugin enable properly.
*/
public static void notifyAboutEnable(boolean isEnabled) {
for (Consumer<Boolean> enableListener : CapabilityService.ListHolder.ENABLE_LISTENERS.get()) {
for (Consumer<Boolean> enableListener : CapabilityService.ListHolder.enableListeners.get()) {
enableListener.accept(isEnabled);
}
}

View File

@ -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));
}
}
/**

View File

@ -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<UUID> senderUUID = sender.getUUID();
Optional<String> 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 {

View File

@ -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();
}

View File

@ -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<String> {
@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()
);
}
}

View File

@ -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();
}
}
}

View File

@ -160,30 +160,31 @@ public class PlayersTableJSONCreator {
private void addExtensionData(Map<String, Object> dataJson, ExtensionTabData tabData) {
for (ExtensionDescriptive descriptive : extensionDescriptives) {
String key = descriptive.getName();
// If it's a double, append a double
Optional<ExtensionDoubleData> doubleValue = tabData.getDouble(key);
if (doubleValue.isPresent()) {
putDataEntry(dataJson, doubleValue.get().getRawValue(), doubleValue.get().getFormattedValue(decimalFormatter), key);
continue;
}
Optional<ExtensionNumberData> 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<String, Object> dataJson, ExtensionTabData tabData, String key) {
// If it's a double, put a double
Optional<ExtensionDoubleData> doubleValue = tabData.getDouble(key);
if (doubleValue.isPresent()) {
putDataEntry(dataJson, doubleValue.get().getRawValue(), doubleValue.get().getFormattedValue(decimalFormatter), key);
return;
}
Optional<ExtensionNumberData> 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<Map<String, Object>> createColumnHeaders() {
List<Map<String, Object>> columnHeaders = new ArrayList<>();

View File

@ -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);

View File

@ -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;
}
}

View File

@ -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<UUID, Boolean> 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());
}
}

View File

@ -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);

View File

@ -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> 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);

View File

@ -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<UUID, Boolean> 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());
}
}