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/.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 @@
-
-
-
-
diff --git a/pom.xml b/pom.xml
index 787362a0..00e4ad55 100644
--- a/pom.xml
+++ b/pom.xml
@@ -117,12 +117,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 72d947a3..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)
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..12c0cefd 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 getServerKey()
+ {
+ return SERVER_KEY;
+ }
+
+ public String getAdminKey()
+ {
+ return ADMIN_KEY;
+ }
+
+ public List getServerHeaders()
+ {
+ return SERVER_HEADERS;
+ }
+
+ public List getAdminHeaders()
+ {
+ 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 4fd400f1..a86320fa 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/SavedFlags.java
@@ -26,8 +26,8 @@ public class SavedFlags extends FreedomService
public Map getSavedFlags()
{
Map flags = null;
-
File input = new File(TotalFreedomMod.getPlugin().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..d60be15a 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,79 +203,13 @@ public class TotalFreedomMod extends JavaPlugin
BackupManager backups = new BackupManager();
backups.createAllBackups();
- permissions = new PermissionConfig(this);
+ permissions = new PermissionConfig();
permissions.load();
- // Start services
- si = new ServerInterface();
- sf = new SavedFlags();
- wm = new WorldManager();
- lv = new LogViewer();
- sql = new SQLite();
- al = new AdminList();
- acl = new ActivityLog();
- rm = new RankManager();
- cb = new CommandBlocker();
- eb = new EventBlocker();
- bb = new BlockBlocker();
- mb = new MobBlocker();
- ib = new InteractBlocker();
- pb = new PotionBlocker();
- lp = new LoginProcess();
- nu = new AntiNuke();
- as = new AntiSpam();
- wr = new WorldRestrictions();
- pl = new PlayerList();
- sh = new Shop();
- vo = new Votifier();
- an = new Announcer();
- cm = new ChatManager();
- dc = new Discord();
- pul = new PunishmentList();
- bm = new BanManager();
- im = new IndefiniteBanList();
- pem = new PermissionManager();
- gr = new GameRuleHandler();
- snp = new SignBlocker();
- ew = new EntityWiper();
- st = new Sitter();
- vh = new VanishHandler();
- ptero = new Pterodactyl();
-
- // Single admin utils
- cs = new CommandSpy();
- ca = new Cager();
- fm = new Freezer();
- or = new Orbiter();
- mu = new Muter();
- ebl = new EditBlocker();
- pbl = new PVPBlocker();
- fo = new Fuckoff();
- ak = new AutoKick();
- ae = new AutoEject();
- mo = new Monitors();
-
mv = new MovementValidator();
sp = new ServerPing();
- // Fun
- cul = new CurseListener();
- it = new ItemFun();
- lm = new Landminer();
- mp = new MP44();
- jp = new Jumppads();
- tr = new Trailer();
- // HTTPD
- hd = new HTTPDaemon();
-
- // Start bridges
- btb = new BukkitTelnetBridge();
- cpb = new CoreProtectBridge();
- esb = new EssentialsBridge();
- ldb = new LibsDisguisesBridge();
- tfg = new TFGuildsBridge();
- web = new WorldEditBridge();
- wgb = new WorldGuardBridge();
+ new Initializer();
fsh.startServices();
@@ -291,6 +236,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;
@@ -333,21 +284,102 @@ public class TotalFreedomMod extends JavaPlugin
}
}
- public static TotalFreedomMod plugin()
+ /**
+ * This class is provided to please Codacy.
+ */
+ private final class Initializer
{
- for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
+ public Initializer()
{
- if (plugin.getName().equalsIgnoreCase(pluginName))
- {
- return (TotalFreedomMod)plugin;
- }
+ initServices();
+ initAdminUtils();
+ initBridges();
+ initFun();
+ initHTTPD();
}
- return null;
- }
- @Override
- public ChunkGenerator getDefaultWorldGenerator(String worldName, String id)
- {
- return new CleanroomChunkGenerator(id);
+ private void initServices()
+ {
+ // Start services
+ si = new ServerInterface();
+ sf = new SavedFlags();
+ wm = new WorldManager();
+ lv = new LogViewer();
+ sql = new SQLite();
+ al = new AdminList();
+ acl = new ActivityLog();
+ rm = new RankManager();
+ cb = new CommandBlocker();
+ eb = new EventBlocker();
+ bb = new BlockBlocker();
+ mb = new MobBlocker();
+ ib = new InteractBlocker();
+ pb = new PotionBlocker();
+ lp = new LoginProcess();
+ nu = new AntiNuke();
+ as = new AntiSpam();
+ wr = new WorldRestrictions();
+ pl = new PlayerList();
+ sh = new Shop();
+ vo = new Votifier();
+ an = new Announcer();
+ cm = new ChatManager();
+ dc = new Discord();
+ pul = new PunishmentList();
+ bm = new BanManager();
+ im = new IndefiniteBanList();
+ pem = new PermissionManager();
+ gr = new GameRuleHandler();
+ snp = new SignBlocker();
+ ew = new EntityWiper();
+ st = new Sitter();
+ vh = new VanishHandler();
+ ptero = new Pterodactyl();
+ }
+
+ private void initAdminUtils()
+ {
+ // Single admin utils
+ cs = new CommandSpy();
+ ca = new Cager();
+ fm = new Freezer();
+ or = new Orbiter();
+ mu = new Muter();
+ ebl = new EditBlocker();
+ pbl = new PVPBlocker();
+ fo = new Fuckoff();
+ ak = new AutoKick();
+ ae = new AutoEject();
+ mo = new Monitors();
+ }
+
+ private void initBridges()
+ {
+ // Start bridges
+ btb = new BukkitTelnetBridge();
+ cpb = new CoreProtectBridge();
+ esb = new EssentialsBridge();
+ ldb = new LibsDisguisesBridge();
+ tfg = new TFGuildsBridge();
+ web = new WorldEditBridge();
+ wgb = new WorldGuardBridge();
+ }
+
+ private void initFun()
+ {
+ // Fun
+ cul = new CurseListener();
+ it = new ItemFun();
+ lm = new Landminer();
+ mp = new MP44();
+ jp = new Jumppads();
+ tr = new Trailer();
+ }
+
+ private void initHTTPD()
+ {
+ // HTTPD
+ hd = new HTTPDaemon();
+ }
}
}
\ 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 30b543e1..7e89dbd9 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.getPlugin();
+ // 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 extends String>)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..f9e97dfe 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,16 +134,11 @@ public class EventBlocker extends FreedomService
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDamage(EntityDamageEvent event)
{
- switch (event.getCause())
+ if ((event.getCause() == EntityDamageEvent.DamageCause.LAVA)
+ && !ConfigEntry.ALLOW_LAVA_DAMAGE.getBoolean())
{
- case LAVA:
- {
- if (!ConfigEntry.ALLOW_LAVA_DAMAGE.getBoolean())
- {
- event.setCancelled(true);
- return;
- }
- }
+ event.setCancelled(true);
+ return;
}
if (ConfigEntry.ENABLE_PET_PROTECT.getBoolean())
@@ -203,18 +212,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 +228,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 8130b2f4..8ccde03e 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 be0448c4..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,8 +1,8 @@
package me.totalfreedom.totalfreedommod.blocking.command;
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,16 +20,6 @@ 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.getPlugin().al.getAdmin(sender);
@@ -61,4 +51,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..d58f8761 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,8 @@ public class EssentialsBridge extends FreedomService
User user = getEssentialsUser(username);
if (user != null)
{
- return FUtil.getField(user, "lastActivity");
+ Long l = FUtil.getField(user, "lastActivity");
+ return (l != null) ? l : 0L;
}
}
catch (Exception ex)
@@ -150,7 +152,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 +205,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..aab5299c 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);
+ 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);
+ 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)
+ {
+ 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/CommandLoader.java b/src/main/java/me/totalfreedom/totalfreedommod/command/CommandLoader.java
index fbbd0ec9..ed3acd5f 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/command/CommandLoader.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/command/CommandLoader.java
@@ -4,14 +4,12 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
-import lombok.Getter;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.util.FLog;
import org.reflections.Reflections;
public class CommandLoader extends FreedomService
{
- @Getter
private final List commands;
public CommandLoader()
@@ -79,4 +77,9 @@ public class CommandLoader extends FreedomService
FLog.info("Loaded " + commands.size() + " commands");
}
+
+ public List getCommands()
+ {
+ return commands;
+ }
}
\ No newline at end of file
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_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_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..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;
@@ -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 SplittableRandom random = new SplittableRandom();
+
+ 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_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/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..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;
@@ -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":
@@ -178,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(),
@@ -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 b88434c0..1c38639c 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..3e8d2780 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)
@@ -43,30 +44,25 @@ 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)
{
msg("Can't find that user. If target is not logged in, make sure that you spelled the name exactly.");
return true;
}
-
- username = entry.getName();
- ips.addAll(entry.getIps());
}
else
{
- final PlayerData entry = plugin.pl.getData(player);
- username = player.getName();
- ips.addAll(entry.getIps());
+ entry = plugin.pl.getData(player);
}
+ 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 +89,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 +103,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..8d2dd093 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/command/FreedomCommand.java
@@ -2,17 +2,17 @@ package me.totalfreedom.totalfreedommod.command;
import com.google.common.collect.Lists;
import java.lang.reflect.Field;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
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 +27,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 +69,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 +87,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 +187,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,12 +205,13 @@ public abstract class FreedomCommand implements CommandExecutor, TabCompleter
return false;
}
- public List onTabComplete(CommandSender sender, Command command, String alias, String[] args)
+ @NotNull
+ 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)
{
- return null;
+ return new ArrayList<>();
}
return StringUtil.copyPartialMatches(args[args.length - 1], options, Lists.newArrayList());
}
@@ -344,15 +266,166 @@ 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)
{
- return null;
+ this.cmd = cmd;
+ }
+
+ public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, String[] args)
+ {
+ if (cmd != null)
+ {
+ cmd.sender = sender;
+
+ if (func4())
+ {
+ return true;
+ }
+
+ if (func1())
+ {
+ return true;
+ }
+
+ if (func2())
+ {
+ return true;
+ }
+
+ func3();
+
+ return cmd.onCommand(sender, this, commandLabel, args);
+ }
+ return false;
+ }
+
+ public boolean func1()
+ {
+ 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;
+ }
+
+ return false;
+ }
+
+ public boolean func2()
+ {
+ if (!plugin.rm.getRank(sender).isAtLeast(perms.level()))
+ {
+ msg(NO_PERMISSION);
+ 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;
+ }
+ return false;
+ }
+
+ public void func3()
+ {
+ 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);
+ }
+ }
+
+ public boolean func4()
+ {
+ if (COOLDOWN_TIMERS.containsKey(sender) && COOLDOWN_TIMERS.containsValue(cmd))
+ {
+ msg(ChatColor.RED + "You are on cooldown for this command.");
+ return true;
+ }
+ return false;
+ }
+
+ @NotNull
+ @Override
+ public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, String[] args)
+ {
+ if (cmd != null)
+ {
+ return cmd.onTabComplete(sender, this, alias, args);
+ }
+ return new ArrayList<>();
}
}
}
\ No newline at end of file
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 e597b9c6..90aee0ac 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/config/ConfigEntry.java
@@ -172,6 +172,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 +200,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 +226,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()
@@ -241,17 +246,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/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 37d5464b..211e9a73 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.Random;
+import java.util.Objects;
+import java.util.SplittableRandom;
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,320 +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())
@@ -374,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)
@@ -509,4 +151,359 @@ 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().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();
+ SplittableRandom random = new SplittableRandom();
+ 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 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 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/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 cd964ac4..aee47a51 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/discord/PrivateMessageListener.java
@@ -1,8 +1,8 @@
package me.totalfreedom.totalfreedommod.discord;
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;
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..67a0b86c 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/ItemFun.java
@@ -4,7 +4,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Random;
+import java.util.Objects;
+import java.util.SplittableRandom;
import java.util.UUID;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
@@ -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 SplittableRandom random = new SplittableRandom();
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);
@@ -327,13 +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(arrow.getShooter()))
{
- if (explosivePlayers.contains((Player)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());
- 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)
@@ -355,9 +352,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..2341272b 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;
@@ -21,11 +20,14 @@ public class Jumppads extends FreedomService
//
private final Map pushMap = Maps.newHashMap();
//
- @Getter
- @Setter
- private double strength = 1 + 0.1F;
+ private final double strength = 1 + 0.1F;
public HashMap players = new HashMap<>();
+ 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..bf9c8bde 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/fun/Landminer.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/Landminer.java
@@ -3,7 +3,6 @@ package me.totalfreedom.totalfreedommod.fun;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import lombok.Getter;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import org.bukkit.GameMode;
@@ -18,8 +17,6 @@ import org.bukkit.util.Vector;
public class Landminer extends FreedomService
{
-
- @Getter
private final List landmines = new ArrayList<>();
@Override
@@ -43,6 +40,7 @@ public class Landminer extends FreedomService
landmines.remove(landmine);
}
+ @SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerMove(PlayerMoveEvent event)
{
@@ -95,14 +93,15 @@ public class Landminer extends FreedomService
}
}
+ public List getLandmines()
+ {
+ return landmines;
+ }
+
public static class Landmine
{
-
- @Getter
private final Location location;
- @Getter
private final Player planter;
- @Getter
private final double radius;
public Landmine(Location location, Player player, double radius)
@@ -117,5 +116,20 @@ public class Landminer extends FreedomService
{
return this.location.toString() + ", " + this.radius + ", " + this.planter.getName();
}
+
+ public Location getLocation()
+ {
+ return location;
+ }
+
+ public Player getPlanter()
+ {
+ return planter;
+ }
+
+ public double getRadius()
+ {
+ return radius;
+ }
}
}
\ No newline at end of file
diff --git a/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java b/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java
index f1de102d..012dc4d7 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/fun/Trailer.java
@@ -1,8 +1,9 @@
package me.totalfreedom.totalfreedommod.fun;
import java.util.HashSet;
-import java.util.Random;
+import java.util.Objects;
import java.util.Set;
+import java.util.SplittableRandom;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.util.Groups;
import org.bukkit.Location;
@@ -16,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
@@ -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..177df52a 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()
@@ -99,7 +137,7 @@ public class HTTPDaemon extends FreedomService
private void module(String name, Class extends HTTPDModule> clazz, boolean async)
{
- modules.put(name, ModuleExecutable.forClass(plugin, clazz, async));
+ modules.put(name, ModuleExecutable.forClass(clazz, async));
}
private class HTTPD extends NanoHTTPD
@@ -108,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)
{
@@ -141,42 +174,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 f0bd63d5..a345f0ac 100644
--- a/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java
+++ b/src/main/java/me/totalfreedom/totalfreedommod/httpd/ModuleExecutable.java
@@ -1,8 +1,6 @@
package me.totalfreedom.totalfreedommod.httpd;
import java.lang.reflect.Constructor;
-import java.util.concurrent.Callable;
-import lombok.Getter;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.httpd.module.HTTPDModule;
import me.totalfreedom.totalfreedommod.util.FLog;
@@ -10,8 +8,6 @@ import org.bukkit.Bukkit;
public abstract class ModuleExecutable
{
-
- @Getter
private final boolean async;
public ModuleExecutable(boolean async)
@@ -19,41 +15,12 @@ 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(), 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 extends HTTPDModule> clazz, boolean async)
+ public static ModuleExecutable forClass(Class extends HTTPDModule> clazz, boolean async)
{
final Constructor extends HTTPDModule> cons;
try
{
- cons = clazz.getConstructor(TotalFreedomMod.class, NanoHTTPD.HTTPSession.class);
+ cons = clazz.getConstructor(NanoHTTPD.HTTPSession.class);
}
catch (Exception ex)
{
@@ -67,7 +34,7 @@ public abstract class ModuleExecutable
{
try
{
- return cons.newInstance(plugin, session).getResponse();
+ return cons.newInstance(session).getResponse();
}
catch (Exception ex)
{
@@ -78,4 +45,30 @@ 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/httpd/NanoHTTPD.java b/src/main/java/me/totalfreedom/totalfreedommod/httpd/NanoHTTPD.java
index fe784f09..c0566cc1 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");
@@ -257,7 +251,11 @@ public abstract class NanoHTTPD
try
{
safeClose(myServerSocket);
- myThread.join();
+ //This should prevent a null pointer :)
+ if (myThread != null)
+ {
+ myThread.join();
+ }
}
catch (Exception e)
{
@@ -382,7 +380,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 +571,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 +581,7 @@ public abstract class NanoHTTPD
}
@Override
- public OutputStream open() throws Exception
+ public OutputStream open()
{
return fstream;
}
@@ -608,6 +606,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 +622,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 +656,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 +690,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 +735,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 +752,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 +864,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 +919,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 +1065,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 +1155,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 +1196,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 +1207,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 +1349,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 +1360,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 +1378,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 +1579,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("