diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/AuthorizationHandler.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/AuthorizationHandler.java index 95f56221..51375ab3 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/AuthorizationHandler.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/AuthorizationHandler.java @@ -20,13 +20,6 @@ public AuthorizationHandler(RoyalCommands instance) { this.plugin = instance; } - private boolean chatLoaded() { - return this.plugin.vh.usingVault() && this.plugin.vh.getChat() != null; - } - - private boolean economyLoaded() { - return this.plugin.vh.usingVault() && this.plugin.vh.getEconomy() != null; - } private boolean iABlockCommandSender(BlockCommandSender cb, String node) { return true; diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/MessageColor.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/MessageColor.java index 3af9c761..84bbc55b 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/MessageColor.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/MessageColor.java @@ -34,22 +34,13 @@ protected ChatColor byStringOrDefault(final String s) { public ChatColor getChatColor() { final String s; - switch (this) { - case NEGATIVE: - s = Config.negativeChatColor; - break; - case NEUTRAL: - s = Config.neutralChatColor; - break; - case POSITIVE: - s = Config.positiveChatColor; - break; - case RESET: - s = Config.resetChatColor; - break; - default: - s = null; - } + s = switch (this) { + case NEGATIVE -> Config.negativeChatColor; + case NEUTRAL -> Config.neutralChatColor; + case POSITIVE -> Config.positiveChatColor; + case RESET -> Config.resetChatColor; + default -> null; + }; return this.byStringOrDefault(s); } diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/RUtils.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/RUtils.java index a924863a..6e4a4f55 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/RUtils.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/RUtils.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.logging.Level; import java.util.regex.Pattern; import net.milkbowl.vault.chat.Chat; import org.bukkit.BanList; @@ -55,7 +56,6 @@ import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataType; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import org.royaldev.royalchat.RoyalChat; @@ -90,7 +90,6 @@ public static FancyMessage addCommandTo(FancyMessage fm, String command) { } public static FancyMessage addDataTo(FancyMessage fm, String[] fields, Object... values) { - final Iterator i = fm.iterator(); for (final Object o : fm) { try { RUtils.setFields(o, fields, values); @@ -123,7 +122,7 @@ public static ItemStack addLore(ItemStack is, String newLore) { public static ItemStack applySpawnLore(ItemStack stack) { final ItemMeta im = stack.getItemMeta(); - final List lore = (im.hasLore()) ? im.getLore() : new ArrayList(); + final List lore = (im.hasLore()) ? im.getLore() : new ArrayList<>(); for (String s : Config.itemSpawnTagLore) lore.add(RUtils.colorize(s)); im.setLore(lore); stack.setItemMeta(im); @@ -238,8 +237,7 @@ public static String colorize(final String text) { /** * Replaces processed color codes with raw color codes. Not to be confused with decolorize - * @param textToReverse - * @param altChar + * @param text * @return Processed string */ public static String uncolorize(final String text) { @@ -319,7 +317,7 @@ public static boolean deleteDirectory(File f) { continue; } if (!delete.delete()) { - RoyalCommands.getInstance().getLogger().warning("Could not delete " + delete.getAbsolutePath()); + RoyalCommands.getInstance().getLogger().log(Level.WARNING, "Could not delete {0}", delete.getAbsolutePath()); success = false; } } @@ -334,7 +332,7 @@ public static boolean deleteDirectory(File f) { */ public static void dispNoPerms(CommandSender cs) { cs.sendMessage(MessageColor.NEGATIVE + "You don't have permission for that!"); - RoyalCommands.getInstance().getLogger().warning(cs.getName() + " was denied access to that!"); + RoyalCommands.getInstance().getLogger().log(Level.WARNING, "{0} was denied access to that!", cs.getName()); } /** @@ -345,7 +343,7 @@ public static void dispNoPerms(CommandSender cs) { */ public static void dispNoPerms(CommandSender cs, String message) { cs.sendMessage(message); - RoyalCommands.getInstance().getLogger().warning(cs.getName() + " was denied access to that!"); + RoyalCommands.getInstance().getLogger().log(Level.WARNING, "{0} was denied access to that!", cs.getName()); } public static void dispNoPerms(CommandSender cs, String... permissionsNeeded) { @@ -359,7 +357,7 @@ public static void dispNoPerms(CommandSender cs, String... permissionsNeeded) { .formattedTooltip(tooltip) .send(cs); // @formatter:on - RoyalCommands.getInstance().getLogger().warning(cs.getName() + " was denied access to that!"); + RoyalCommands.getInstance().getLogger().log(Level.WARNING, "{0} was denied access to that!", cs.getName()); } private static void executeBanActions(OfflinePlayer banned, CommandSender banner, String reason) { @@ -429,8 +427,7 @@ public static String getAssignmentPath(ItemStack is, boolean customNames, boolea if (customNames) { ItemMeta im = is.getItemMeta(); if (im != null) { - String displayName = im.getDisplayName(); - if (displayName != null) path.append(".").append(displayName.replace('.', ',')).append("."); + if (im.hasDisplayName()) path.append(".").append(im.getDisplayName().replace('.', ',')).append("."); List lore = im.getLore(); if (lore != null && !lore.isEmpty()) { for (String l : lore) { @@ -449,6 +446,7 @@ public static String getAssignmentPath(ItemStack is, boolean customNames, boolea * Gets a player backpack * * @param u UUID of player to get backpack for + * @param w * @return Backpack - never null * @deprecated Use {@link org.royaldev.royalcommands.wrappers.player.MemoryRPlayer#getBackpack}. */ @@ -496,6 +494,8 @@ public static Command getCommand(String name) { } /** + * @param p + * @return * @deprecated Use {@link org.royaldev.royalcommands.wrappers.player.MemoryRPlayer#getHomes}.size() */ @Deprecated @@ -504,6 +504,8 @@ public static int getCurrentHomes(Player p) { } /** + * @param u + * @return * @deprecated Use {@link org.royaldev.royalcommands.wrappers.player.MemoryRPlayer#getHomes}.size() */ @Deprecated @@ -567,6 +569,8 @@ public static String getFriendlyEnumName(Enum e) { } /** + * @param p + * @return * @deprecated Use {@link org.royaldev.royalcommands.wrappers.player.MemoryRPlayer#getHomeLimit} */ @Deprecated @@ -780,8 +784,7 @@ public static List getPlayerTooltip(final Object o) { } } if (o instanceof Player) { - final Player p = (Player) o; - if (tooltip.size() > 0) { // Replace Offline Player with Player + if (!tooltip.isEmpty()) { // Replace Offline Player with Player tooltip.remove(0); tooltip.add(0, new FancyMessage("Player").color(MessageColor.NEUTRAL.cc()).style(ChatColor.BOLD, ChatColor.UNDERLINE)); } @@ -796,7 +799,6 @@ public static List getPlayerTooltip(final Object o) { public static List getItemTooltip(final Object o) { final List tooltip = new ArrayList<>(); - final VaultHandler vh = RoyalCommands.getInstance().vh; if (o instanceof Material) { final Material item = (Material) o; tooltip.add(new FancyMessage("Item").color(MessageColor.NEUTRAL.cc()).style(ChatColor.BOLD, ChatColor.UNDERLINE)); @@ -1068,6 +1070,7 @@ public static String join(Object[] i, String between) { * Kicks a player and sets the last kick for history writing. * * @param kicked Player to kick + * @param kicker Who requested the kick * @param reason Reason for kick */ public static void kickPlayer(final Player kicked, final CommandSender kicker, final String reason) { @@ -1143,17 +1146,6 @@ public void run() { return id; } - /** - * Makes a scheduled Bukkit task for watching a player when he's warming up for teleport. - * - * @param p Player to teleport when warmup is finished - * @param t Entity to teleport to when warmup is finished - * @return ID of Bukkit task - */ - private static int makeTeleportRunner(final Player p, final Entity t) { - return makeTeleportRunner(p, t.getLocation()); - } - public static boolean nearEqual(double a, double b, double margin) { return Math.abs(a - b) < margin; } @@ -1174,7 +1166,7 @@ public static void playTeleportSound(Location at) { try { toPlay = Sound.valueOf(Config.teleportSoundName); } catch (IllegalArgumentException e) { - RoyalCommands.getInstance().getLogger().warning("A teleport sound was attempted, but " + Config.teleportSoundName + " was not a valid sound name!"); + RoyalCommands.getInstance().getLogger().log(Level.WARNING, "A teleport sound was attempted, but {0} was not a valid sound name!", Config.teleportSoundName); return; } at.getWorld().playSound(at, toPlay, Config.teleportSoundVolume, Config.teleportSoundPitch); @@ -1242,6 +1234,7 @@ public static void saveBackpack(Player p, Inventory i) { * Saves player backpacks in a forwards-compatible method, using native Bukkit methods. * * @param u UUID of player to save backpack for + * @param w World of the backpack * @param i Inventory to save as backpack */ public static void saveBackpack(UUID u, World w, Inventory i) { @@ -1548,7 +1541,6 @@ public static void unbanPlayer(OfflinePlayer t) { * @param len Length to wrap at * @return Array of strings */ - @SuppressWarnings("unchecked") public static String[] wrapText(String text, int len) { // return empty array for null text if (text == null) return new String[]{}; @@ -1557,7 +1549,7 @@ public static String[] wrapText(String text, int len) { // return text if less than length if (text.length() <= len) return new String[]{text}; char[] chars = text.toCharArray(); - java.util.Vector lines = new java.util.Vector(); + List lines = new ArrayList(); StringBuilder line = new StringBuilder(); StringBuilder word = new StringBuilder(); for (char aChar : chars) { @@ -1583,7 +1575,10 @@ public static String[] wrapText(String text, int len) { if (line.length() > 0) lines.add(line.toString()); String[] ret = new String[lines.size()]; int c = 0; // counter - for (Enumeration e = lines.elements(); e.hasMoreElements(); c++) ret[c] = (String) e.nextElement(); + for (String l : lines) { + ret[c] = l; + c++; + } return ret; } @@ -1598,7 +1593,6 @@ public static void writeBanHistory(OfflinePlayer t) { PlayerConfiguration pcm = PlayerConfigurationManager.getConfiguration(t); if (!pcm.exists()) pcm.createFile(); List prevBans = pcm.getStringList("prevbans"); - if (prevBans == null) prevBans = new ArrayList<>(); // banner,banreason,bannedat,istempban prevBans.add(pcm.getString("banner") + "\u00b5" + pcm.getString("banreason") + "\u00b5" + pcm.getString("bannedat") + "\u00b5" + (pcm.get("bantime") != null)); pcm.set("prevbans", prevBans); diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/RoyalCommands.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/RoyalCommands.java index db123daa..ca4fa948 100755 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/RoyalCommands.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/RoyalCommands.java @@ -58,6 +58,7 @@ import java.lang.reflect.Field; import java.nio.file.Files; import java.util.*; +import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -187,15 +188,15 @@ public void run() { String currentVersion = useVersion.toString(); if (!dev.equalsIgnoreCase(currentVersion) && currentVersion.contains("-SNAPSHOT")) { RoyalCommands.this.getLogger().warning("A newer version of RoyalCommands is available!"); - RoyalCommands.this.getLogger().warning("Currently installed: v" + currentVersion + ", newest: v" + dev); + RoyalCommands.this.getLogger().log(Level.WARNING, "Currently installed: v{0}, newest: v{1}", new Object[]{currentVersion, dev}); RoyalCommands.this.getLogger().warning("Development builds are available at https://jenkins.blny.me/"); } else if (!stable.equalsIgnoreCase(currentVersion) && !currentVersion.equalsIgnoreCase(dev)) { RoyalCommands.this.getLogger().warning("A newer version of RoyalCommands is available!"); - RoyalCommands.this.getLogger().warning("Currently installed: v" + currentVersion + ", newest: v" + stable); + RoyalCommands.this.getLogger().log(Level.WARNING, "Currently installed: v{0}, newest: v{1}", new Object[]{currentVersion, stable}); RoyalCommands.this.getLogger().warning("Stable builds are available at https://www.spigotmc.org/resources/royalcommands.4113/"); } else if (!stable.equalsIgnoreCase(currentVersion) && currentVersion.replace("-SNAPSHOT", "").equalsIgnoreCase(stable)) { RoyalCommands.this.getLogger().warning("A newer version of RoyalCommands is available!"); - RoyalCommands.this.getLogger().warning("Currently installed: v" + currentVersion + ", newest: v" + stable); + RoyalCommands.this.getLogger().log(Level.WARNING, "Currently installed: v{0}, newest: v{1}", new Object[]{currentVersion, stable}); RoyalCommands.this.getLogger().warning("Stable builds are available at https://www.spigotmc.org/resources/royalcommands.4113/"); } } catch (Exception ignored) {} @@ -244,7 +245,7 @@ private void registerCommand(CommandExecutor ce, String command) { pc.setUsage(this.getUsage(command)); this.getCommandMap().register(this.getDescription().getName(), pc); } catch (Exception e) { - this.getLogger().warning("Could not register command \"" + command + "\" - an error occurred: " + e.getMessage() + "."); + this.getLogger().log(Level.WARNING, "Could not register command \"{0}\" - an error occurred: {1}.", new Object[]{command, e.getMessage()}); } } @@ -268,9 +269,9 @@ public boolean accept(File dir, String name) { playersToConvert.add(playerName); } final List> partitions = this.partitionList(playersToConvert, 100); - this.getLogger().info("Converting " + playersToConvert.size() + " players in " + partitions.size() + " request" + (partitions.size() == 1 ? "" : "s") + "."); + this.getLogger().log(Level.INFO, "Converting {0} players in {1} request{2}.", new Object[]{playersToConvert.size(), partitions.size(), partitions.size() == 1 ? "" : "s"}); for (List lookup : partitions) { - this.getLogger().info("Converting next " + lookup.size() + " players."); + this.getLogger().log(Level.INFO, "Converting next {0} players.", lookup.size()); final Map uuids; try { uuids = new UUIDFetcher(lookup).call(); @@ -283,10 +284,10 @@ public boolean accept(File dir, String name) { if (!userFile.exists()) continue; try { Files.move(userFile.toPath(), new File(userdataFolder, e.getValue() + ".yml").toPath()); - this.getLogger().info("Converted " + e.getKey().toLowerCase() + ".yml to " + e.getValue() + ".yml"); + this.getLogger().log(Level.INFO, "Converted {0}.yml to {1}.yml", new Object[]{e.getKey().toLowerCase(), e.getValue()}); playersConverted.add(e.getKey().toLowerCase()); } catch (IOException ex) { - this.getLogger().warning("Could not convert " + e.getKey() + ".yml: " + ex.getClass().getSimpleName() + " (" + ex.getMessage() + ")"); + this.getLogger().log(Level.WARNING, "Could not convert {0}.yml: {1} ({2})", new Object[]{e.getKey(), ex.getClass().getSimpleName(), ex.getMessage()}); } } } @@ -297,9 +298,9 @@ public boolean accept(File dir, String name) { final UUID uuid = RUtils.getOfflinePlayer(name).getUniqueId(); try { Files.move(new File(userdataFolder, name + ".yml").toPath(), new File(userdataFolder, uuid + ".yml").toPath()); - this.getLogger().info("Converted offline-mode player " + name + ".yml to " + uuid + ".yml"); + this.getLogger().log(Level.INFO, "Converted offline-mode player {0}.yml to {1}.yml", new Object[]{name, uuid}); } catch (IOException ex) { - this.getLogger().warning("Could not convert " + name + ".yml: " + ex.getClass().getSimpleName() + " (" + ex.getMessage() + ")"); + this.getLogger().log(Level.WARNING, "Could not convert {0}.yml: {1} ({2})", new Object[]{name, ex.getClass().getSimpleName(), ex.getMessage()}); } } } @@ -409,7 +410,7 @@ public void onDisable() { //-- Save all userdata --// - this.getLogger().info("Saving userdata and configurations (" + (PlayerConfigurationManager.configurationsCreated() + Configuration.configurationsCreated()) + " files in all)..."); + this.getLogger().log(Level.INFO, "Saving userdata and configurations ({0}{1} files in all)...", new Object[]{PlayerConfigurationManager.configurationsCreated(), Configuration.configurationsCreated()}); PlayerConfigurationManager.saveAllConfigurations(); Configuration.saveAllConfigurations(); this.getLogger().info("Userdata saved."); @@ -420,7 +421,7 @@ public void onDisable() { //-- We're done! --// - this.getLogger().info("RoyalCommands v" + this.version + " disabled."); + this.getLogger().log(Level.INFO, "RoyalCommands v{0} disabled.", this.version); } @Override @@ -454,7 +455,7 @@ public void onEnable() { if (!versionCheck()) { this.getLogger().severe("This version of CraftBukkit is too old to run RoyalCommands!"); - this.getLogger().severe("This version of RoyalCommands needs at least CraftBukkit " + this.minVersion + "."); + this.getLogger().log(Level.SEVERE, "This version of RoyalCommands needs at least CraftBukkit {0}.", this.minVersion); this.getLogger().severe("Disabling plugin. You can turn this check off in the config."); this.getServer().getPluginManager().disablePlugin(this); return; @@ -522,7 +523,7 @@ public void onEnable() { if (!(o instanceof BaseCommand)) continue; this.registerCommand((CommandExecutor) o, command); } catch (Exception e) { - this.getLogger().warning("Could not register command \"" + command + "\" - an error occurred (" + e.getClass().getSimpleName() + "): " + e.getMessage() + "."); + this.getLogger().log(Level.WARNING, "Could not register command \"{0}\" - an error occurred ({1}): {2}.", new Object[]{command, e.getClass().getSimpleName(), e.getMessage()}); } } @@ -536,7 +537,7 @@ public void onEnable() { //-- We're done! --// - this.getLogger().info("RoyalCommands v" + this.version + " initiated."); + this.getLogger().log(Level.INFO, "RoyalCommands v{0} initiated.", this.version); } private class BackpackConverter implements Listener { diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/WorldManager.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/WorldManager.java index 4b08a85b..e6837239 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/WorldManager.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/WorldManager.java @@ -24,6 +24,7 @@ import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.logging.Level; import java.util.logging.Logger; public class WorldManager { @@ -32,7 +33,7 @@ public class WorldManager { private final List loadedWorlds = new ArrayList<>(); private final List configuredWorlds = new ArrayList<>(); private final Configuration config = Configuration.getConfiguration("worlds.yml"); - private final Logger log = RoyalCommands.getInstance().getLogger(); + private static final Logger log = RoyalCommands.getInstance().getLogger(); public WorldManager() { il = new InventoryListener(RoyalCommands.getInstance()); @@ -82,7 +83,6 @@ public void addNewToConfig() { config.set(path + "animalspawnticks", w.getTicksPerSpawns(SpawnCategory.ANIMAL)); config.set(path + "monsterspawnticks", w.getTicksPerSpawns(SpawnCategory.MONSTER)); config.set(path + "difficulty", w.getDifficulty().name()); - config.set(path + "worldtype", w.getWorldType().name()); config.set(path + "environment", w.getEnvironment().name()); config.set(path + "gamemode", Bukkit.getServer().getDefaultGameMode().name()); if (w.getGenerator() == null) config.set(path + "generator", "DefaultGen"); @@ -199,17 +199,17 @@ public void setupWorlds() { try { w = loadWorld(ws); } catch (IllegalArgumentException e) { - log.warning("Could not load world " + ws + " as specified in worlds.yml: " + e.getMessage()); + log.log(Level.WARNING, "Could not load world {0} as specified in worlds.yml: {1}", new Object[]{ws, e.getMessage()}); continue; } catch (NullPointerException e) { - log.warning("Could not load world " + ws + " as specified in worlds.yml: " + e.getMessage()); + log.log(Level.WARNING, "Could not load world {0} as specified in worlds.yml: {1}", new Object[]{ws, e.getMessage()}); continue; } } if (!loadedWorlds.contains(ws)) continue; if (w == null) w = Bukkit.getWorld(ws); if (w == null) { - log.warning("Could not manage world " + ws + ": No such world"); + log.log(Level.WARNING, "Could not manage world {0}: No such world", ws); continue; } w.setSpawnFlags(config.getBoolean(path + "spawnmonsters", true), config.getBoolean(path + "spawnanimals", true)); diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/attribute/NbtFactory.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/attribute/NbtFactory.java index 4ee31e1b..5f6cc4f2 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/attribute/NbtFactory.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/attribute/NbtFactory.java @@ -99,6 +99,7 @@ private static NbtFactory get(){ /** * Construct a new NBT list of an unspecified type. * + * @param content * @return The NBT list. */ public static NbtList createList(Object... content){ @@ -108,6 +109,7 @@ public static NbtList createList(Object... content){ /** * Construct a new NBT list of an unspecified type. * + * @param iterable * @return The NBT list. */ public static NbtList createList(Iterable iterable){ @@ -266,72 +268,6 @@ private static void setFieldValue(Field field, Object target, Object value){ } } -// /** -// * Load the content of a file from a stream. -// *

-// * Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file. -// * @param stream - the stream supplier. -// * @param option - whether or not to decompress the input stream. -// * @return The decoded NBT compound. -// * @throws IOException If anything went wrong. -// */ -// public static NbtCompound fromStream(InputSupplier stream, StreamOptions option) throws IOException { -// InputStream input = null; -// DataInputStream data = null; -// -// try { -// input = stream.getInput(); -// data = new DataInputStream(new BufferedInputStream( -// option == StreamOptions.GZIP_COMPRESSION ? new GZIPInputStream(input) : input -// )); -// -// return fromCompound(invokeMethod(get().LOAD_COMPOUND, null, data)); -// } finally { -// if (data != null) -// Closeables.closeQuietly(data); -// if (input != null) -// Closeables.closeQuietly(input); -// } -// } - - // /** -// * Save the content of a NBT compound to a stream. -// *

-// * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. -// * -// * @param source - the NBT compound to save. -// * @param stream - the stream. -// * @param option - whether or not to compress the output. -// * @throws IOException If anything went wrong. -// */ -// public static void saveStream(NbtCompound source, OutputSupplier stream, StreamOptions option) throws IOException { -// OutputStream output = null; -// DataOutputStream data = null; -// -// try { -// output = stream.getOutput(); -// data = new DataOutputStream( -// option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output -// ); -// -// invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data); -// } finally { -// if (data != null) { -// try { -// data.close(); -// } catch (Exception e) { -// -// } -// } -// if (output != null) { -// try { -// output.close(); -// } catch (Exception e) { -// -// } -// } -// } -// } private static Object getFieldValue(Field field, Object target){ try{ return field.get(target); @@ -341,7 +277,7 @@ private static Object getFieldValue(Field field, Object target){ } /** - * Search for the first publically and privately defined method of the given name and parameter count. + * Search for the first publicly and privately defined method of the given name and parameter count. * * @param requireMod - modifiers that are required. * @param bannedMod - modifiers that are banned. @@ -369,7 +305,7 @@ private static Method getMethod(int requireMod, int bannedMod, Class clazz, S } /** - * Search for the first publically and privately defined field of the given name. + * Search for the first publicly and privately defined field of the given name. * * @param instance - an instance of the class with the field. * @param clazz - an optional class to start with, or NULL to deduce it from instance. @@ -393,13 +329,11 @@ private static Field getField(Object instance, Class clazz, String fieldName) throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance); } - @SuppressWarnings("unchecked") private Map getDataMap(Object handle){ return (Map) getFieldValue( getDataField(NbtType.TAG_COMPOUND, handle), handle); } - @SuppressWarnings("unchecked") private List getDataList(Object handle){ return (List) getFieldValue( getDataField(NbtType.TAG_LIST, handle), handle); @@ -416,8 +350,8 @@ private Object unwrapValue(String name, Object value){ if(value == null) return null; - if(value instanceof Wrapper){ - return ((Wrapper) value).getHandle(); + if(value instanceof Wrapper wrapper){ + return wrapper.getHandle(); } else if(value instanceof List){ throw new IllegalArgumentException("Can only insert a WrappedList."); @@ -444,15 +378,12 @@ private Object wrapNative(Object nms){ if(BASE_CLASS.isAssignableFrom(nms.getClass())){ final NbtType type = getNbtType(nms); - // Handle the different types - switch(type){ - case TAG_COMPOUND: - return new NbtCompound(nms); - case TAG_LIST: - return new NbtList(nms); - default: - return getFieldValue(getDataField(type, nms), nms); - } + // Handle the different types + return switch (type) { + case TAG_COMPOUND -> new NbtCompound(nms); + case TAG_LIST -> new NbtList(nms); + default -> getFieldValue(getDataField(type, nms), nms); + }; } throw new IllegalArgumentException("Unexpected type: " + nms); } @@ -636,6 +567,9 @@ public int[] getIntegerArray(String key, int[] defaultValue){ /** * Method for when items are not created following NBTtag convention and have Integers where there should be Longs + * @param key + * @param defaultValue + * @return */ public Long getIntegerOrLong(String key, Long defaultValue){ if(!containsKey(key)) return defaultValue; @@ -889,11 +823,12 @@ private Iterator> iterator(){ return new Iterator>() { + @Override public boolean hasNext(){ return proxy.hasNext(); } - + @Override public Entry next(){ Entry entry = proxy.next(); @@ -902,13 +837,14 @@ public Entry next(){ ); } - + @Override public void remove(){ proxy.remove(); } }; } + @Override public Object getHandle(){ return handle; } @@ -963,7 +899,7 @@ public void add(int index, Object element){ Object nbt = unwrapIncoming(element); // Set the list type if its the first element - if(size() == 0) + if(isEmpty()) setFieldValue(NBT_LIST_TYPE, handle, (byte) getNbtType(nbt).id); original.add(index, nbt); } @@ -978,6 +914,7 @@ public boolean remove(Object o){ return original.remove(unwrapIncoming(o)); } + @Override public Object getHandle(){ return handle; } diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/configuration/PlayerConfigurationManager.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/configuration/PlayerConfigurationManager.java index 1a22417e..02eb5d90 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/configuration/PlayerConfigurationManager.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/configuration/PlayerConfigurationManager.java @@ -16,7 +16,7 @@ public final class PlayerConfigurationManager { - static final Map pcs = Collections.synchronizedMap(new HashMap()); + static final Map pcs = Collections.synchronizedMap(new HashMap<>()); public static int configurationsCreated() { synchronized (PlayerConfigurationManager.pcs) { diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/data/block/BlockData.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/data/block/BlockData.java index 87a0a34e..172b2de0 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/data/block/BlockData.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/data/block/BlockData.java @@ -81,10 +81,10 @@ public void load() throws IOException, ClassNotFoundException { final Object o = ois.readObject(); ois.close(); if (!(o instanceof Map)) return; - final HashMap> data = (HashMap>) o; + final HashMap> d = (HashMap>) o; synchronized (BlockData.data) { BlockData.data.clear(); - BlockData.data.putAll(data); + BlockData.data.putAll(d); } synchronized (this.thisData) { this.thisData.clear(); diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/gui/inventory/InventoryGUI.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/gui/inventory/InventoryGUI.java index 1a97dd8b..7700de61 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/gui/inventory/InventoryGUI.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/gui/inventory/InventoryGUI.java @@ -262,7 +262,7 @@ public ItemStack setItemMeta(final ItemStack is, final String name, final String public void setName(final UUID uuid, final String name) { final ItemStack is = this.getItemStack(uuid); if (is == null) throw new IllegalArgumentException("No such ItemStack UUID found"); - this.replaceItemStack(uuid, this.setItemMeta(is, name, null)); + this.replaceItemStack(uuid, this.setItemMeta(is, name)); } /** diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/EntityListener.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/EntityListener.java index 34ce8569..9abc1b12 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/EntityListener.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/EntityListener.java @@ -106,13 +106,11 @@ public void oneHitKill(EntityDamageEvent event) { if (!(e instanceof Player)) return; Player p = (Player) e; if (!PlayerConfigurationManager.getConfiguration(p).getBoolean("ohk")) return; - if (ed instanceof LivingEntity) { - LivingEntity le = (LivingEntity) ed; + if (ed instanceof LivingEntity le) { le.damage(le.getHealth() * 1000); le.setLastDamageCause(new EntityDamageByEntityEvent(p, le, EntityDamageEvent.DamageCause.ENTITY_ATTACK, 1D)); } - if (ed instanceof EnderDragonPart) { - EnderDragonPart ldp = (EnderDragonPart) ed; + if (ed instanceof EnderDragonPart ldp) { LivingEntity le = ldp.getParent(); le.damage(le.getHealth() * 1000); le.setLastDamageCause(new EntityDamageByEntityEvent(p, le, EntityDamageEvent.DamageCause.ENTITY_ATTACK, 1D)); diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/InventoryListener.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/InventoryListener.java index 42e304bd..3d2eaf65 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/InventoryListener.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/InventoryListener.java @@ -129,8 +129,7 @@ private void saveInventory(Player p, Inventory i, World w) { for (int slot = 0; slot < i.getSize(); slot++) { pcm.set("inventory." + group + ".slot." + slot, i.getItem(slot)); } - if (i instanceof PlayerInventory) { - PlayerInventory pi = (PlayerInventory) i; + if (i instanceof PlayerInventory pi) { pcm.set("inventory." + group + ".slot.helm", pi.getHelmet()); pcm.set("inventory." + group + ".slot.chestplate", pi.getChestplate()); pcm.set("inventory." + group + ".slot.leggings", pi.getLeggings()); @@ -353,8 +352,7 @@ public void saveInventory(OfflinePlayer op, String world, Inventory i) { for (int slot = 0; slot < i.getSize(); slot++) { pcm.set("inventory." + group + ".slot." + slot, i.getItem(slot)); } - if (i instanceof PlayerInventory) { - PlayerInventory pi = (PlayerInventory) i; + if (i instanceof PlayerInventory pi) { pcm.set("inventory." + group + ".slot.helm", pi.getHelmet()); pcm.set("inventory." + group + ".slot.chestplate", pi.getChestplate()); pcm.set("inventory." + group + ".slot.leggings", pi.getLeggings()); diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/MonitorListener.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/MonitorListener.java index 93b284db..5071db23 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/MonitorListener.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/MonitorListener.java @@ -144,13 +144,6 @@ public void onInvClick(InventoryClickEvent e) { e.setCancelled(true); } - /*@EventHandler - public void onInvCloseMonitor(InventoryCloseEvent e) { - if (!MonitorListener.openInvs.contains(e.getPlayer().getName())) return; - e.getPlayer().openInventory(e.getInventory()); - }*/ - // Seems a bit harsh ^ - @EventHandler public void onInvCloseViewee(InventoryCloseEvent e) { if (!CmdMonitor.viewees.containsKey(e.getPlayer().getName())) return; @@ -171,18 +164,17 @@ public void onInvOpen(InventoryOpenEvent e) { final Inventory i = e.getInventory(); final Block b = RUtils.getTarget(p); switch (i.getType()) { - case WORKBENCH: - if (!b.getType().equals(Material.CRAFTING_TABLE)) return; - t.openWorkbench(b.getLocation(), false); - break; - case ENCHANTING: - if (!b.getType().equals(Material.ENCHANTING_TABLE)) return; - t.openEnchanting(b.getLocation(), false); - break; - case BREWING: - case CRAFTING: - case DISPENSER: - return; + case WORKBENCH -> { + if (!b.getType().equals(Material.CRAFTING_TABLE)) return; + t.openWorkbench(b.getLocation(), false); + } + case ENCHANTING -> { + if (!b.getType().equals(Material.ENCHANTING_TABLE)) return; + t.openEnchanting(b.getLocation(), false); + } + case BREWING, CRAFTING, DISPENSER -> { + return; + } } t.openInventory(e.getInventory()); MonitorListener.openInvs.add(t.getName()); diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/PlayerListener.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/PlayerListener.java index 43c38ae8..4883ff1f 100755 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/PlayerListener.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/listeners/PlayerListener.java @@ -9,6 +9,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -66,7 +67,7 @@ public class PlayerListener implements Listener { private final RoyalCommands plugin; - private final Logger log = Logger.getLogger("Minecraft"); + private static final Logger log = Logger.getLogger("Minecraft"); public PlayerListener(final RoyalCommands instance) { this.plugin = instance; @@ -114,7 +115,7 @@ public void assign(PlayerInteractEvent event) { if (parts.length > 0) { String command = parts[0].toLowerCase(); if (!Config.logBlacklist.contains(command.substring(1))) - log.info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": /" + s); + log.log(Level.INFO, "[PLAYER_COMMAND] {0}: /{1}", new Object[]{event.getPlayer().getName(), s}); } } } @@ -272,7 +273,7 @@ public void onAssignInteractPlayer(PlayerInteractEntityEvent e) { if (publicAssigns != null) cmds.addAll(publicAssigns); if (cmds.isEmpty()) return; Player clicked = null; - if (e.getRightClicked() instanceof Player) clicked = (Player) e.getRightClicked(); + if (e.getRightClicked() instanceof Player player) clicked = player; for (String s : cmds) { if (clicked != null) s = s.replace("{player}", clicked.getName()); if (s.toLowerCase().trim().startsWith("c:")) e.getPlayer().chat(s.trim().substring(2)); @@ -283,7 +284,7 @@ public void onAssignInteractPlayer(PlayerInteractEntityEvent e) { if (parts.length > 0) { String command = parts[0].toLowerCase(); if (!Config.logBlacklist.contains(command.substring(1))) - log.info("[PLAYER_COMMAND] " + e.getPlayer().getName() + ": /" + s); + log.log(Level.INFO, "[PLAYER_COMMAND] {0}: /{1}", new Object[]{e.getPlayer().getName(), s}); } } } @@ -353,7 +354,7 @@ public void onPlayerChat(AsyncPlayerChatEvent event) { howLong = " for " + MessageColor.NEUTRAL + RUtils.formatDateDiff(muteTime + mutedAt).substring(1) + MessageColor.NEGATIVE; } p.sendMessage(MessageColor.NEGATIVE + "You are muted and cannot speak" + howLong + "."); - plugin.getLogger().info(p.getName() + " is muted but tried to say \"" + event.getMessage() + "\""); + plugin.getLogger().log(Level.INFO, "{0} is muted but tried to say \"{1}\"", new Object[]{p.getName(), event.getMessage()}); event.setFormat(""); event.setCancelled(true); } @@ -367,7 +368,7 @@ public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { if (Config.showcommands) { String command = event.getMessage().split(" ")[0].toLowerCase(); if (!Config.logBlacklist.contains(command.substring(1))) - log.info("[PLAYER_COMMAND] " + p.getName() + ": " + event.getMessage()); + log.log(Level.INFO, "[PLAYER_COMMAND] {0}: {1}", new Object[]{p.getName(), event.getMessage()}); } if (pcm.getBoolean("muted")) { if (pcm.get("mutetime") != null && !RUtils.isTimeStampValidAddTime(p, "mutetime", "mutedat")) @@ -376,14 +377,14 @@ public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { if (!(event.getMessage().toLowerCase().startsWith(command.toLowerCase() + " ") || event.getMessage().equalsIgnoreCase(command.toLowerCase()))) continue; p.sendMessage(MessageColor.NEGATIVE + "You are muted."); - log.info("[RoyalCommands] " + p.getName() + " tried to use that command, but is muted."); + log.log(Level.INFO, "[RoyalCommands] {0} tried to use that command, but is muted.", p.getName()); event.setCancelled(true); } } if (pcm.getBoolean("jailed")) { p.sendMessage(MessageColor.NEGATIVE + "You are jailed."); - log.info("[RoyalCommands] " + p.getName() + " tried to use that command, but is jailed."); + log.log(Level.INFO, "[RoyalCommands] {0} tried to use that command, but is jailed.", p.getName()); event.setCancelled(true); } } @@ -406,7 +407,7 @@ public void onPlayerJoin(PlayerJoinEvent event) { } pcm.setFirstJoin(false); } else { - log.info("[RoyalCommands] Updating the IP for " + event.getPlayer().getName() + "."); + log.log(Level.INFO, "[RoyalCommands] Updating the IP for {0}.", event.getPlayer().getName()); String playerip = event.getPlayer().getAddress().getAddress().toString(); playerip = playerip.replace("/", ""); pcm.set("ip", playerip); @@ -584,7 +585,7 @@ public void silentKicks(PlayerKickEvent e) { if (e.isCancelled()) return; String reason = e.getReason(); if (!reason.endsWith("\00-silent")) return; - e.setLeaveMessage(null); + e.setLeaveMessage(""); e.setReason(reason.replace("\00-silent", "")); } diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/rcommands/kits/Kit.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/rcommands/kits/Kit.java index 6e87bf5e..a98fa8bc 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/rcommands/kits/Kit.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/rcommands/kits/Kit.java @@ -105,7 +105,7 @@ private List getItemStacks(final List items) { private List getLore(final ConfigurationNode item) { final List lore = new ArrayList<>(); if (item == null) return lore; - for (final String loreItem : item.getStringList("lore", new ArrayList())) { + for (final String loreItem : item.getStringList("lore", new ArrayList<>())) { lore.add(RUtils.colorize(loreItem)); } return lore; diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/runners/AFKWatcher.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/runners/AFKWatcher.java index 9406a4d0..cfc76d76 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/runners/AFKWatcher.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/runners/AFKWatcher.java @@ -5,6 +5,7 @@ */ package org.royaldev.royalcommands.runners; +import java.util.logging.Level; import org.bukkit.entity.Player; import org.royaldev.royalcommands.AFKUtils; import org.royaldev.royalcommands.Config; @@ -49,7 +50,7 @@ public void run() { try { RUtils.scheduleKick(p, "You have been AFK for too long!"); } catch (IllegalArgumentException | NullPointerException e) { - Logger.getLogger("Minecraft").warning("[RoyalCommands] Could not kick " + p.getName() + " for being AFK: " + e.getMessage()); + Logger.getLogger("Minecraft").log(Level.WARNING, "[RoyalCommands] Could not kick {0} for being AFK: {1}", new Object[]{p.getName(), e.getMessage()}); } } } diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/tools/Vector2D.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/tools/Vector2D.java index a836343d..0b96e44c 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/tools/Vector2D.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/tools/Vector2D.java @@ -6,7 +6,7 @@ package org.royaldev.royalcommands.tools; /** - * A two-dimsensional vector. + * A two-dimensional vector. */ public class Vector2D { diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/wrappers/player/MemoryRPlayer.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/wrappers/player/MemoryRPlayer.java index f2d3f31c..9447631d 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/wrappers/player/MemoryRPlayer.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/wrappers/player/MemoryRPlayer.java @@ -33,15 +33,17 @@ */ public class MemoryRPlayer implements RPlayer { - private static final Map players = Collections.synchronizedMap(new HashMap()); + private static final Map players = Collections.synchronizedMap(new HashMap<>()); private final UUID uuid; private final Nick nick; + @Deprecated private MemoryRPlayer(final OfflinePlayer op) { this.uuid = op.getUniqueId(); this.nick = new Nick(this); } + @Deprecated private MemoryRPlayer(final String name) { this.uuid = RUtils.getOfflinePlayer(name).getUniqueId(); this.nick = new Nick(this); diff --git a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/wrappers/teleport/PlayerTeleporter.java b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/wrappers/teleport/PlayerTeleporter.java index cd445c0f..774f2bca 100644 --- a/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/wrappers/teleport/PlayerTeleporter.java +++ b/modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/wrappers/teleport/PlayerTeleporter.java @@ -5,6 +5,7 @@ */ package org.royaldev.royalcommands.wrappers.teleport; +import java.util.logging.Level; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Sound; @@ -54,7 +55,7 @@ private Sound getTeleportSound() { try { return Sound.valueOf(Config.teleportSoundName); } catch (final IllegalArgumentException e) { - RoyalCommands.getInstance().getLogger().warning("A teleport sound was attempted, but " + Config.teleportSoundName + " was not a valid sound name!"); + RoyalCommands.getInstance().getLogger().log(Level.WARNING, "A teleport sound was attempted, but {0} was not a valid sound name!", Config.teleportSoundName); return null; } }