diff --git a/worldedit-bukkit/build.gradle b/worldedit-bukkit/build.gradle index acefe8c9b..1e315e6b1 100644 --- a/worldedit-bukkit/build.gradle +++ b/worldedit-bukkit/build.gradle @@ -4,6 +4,8 @@ apply plugin: 'maven' repositories { maven { url "https://hub.spigotmc.org/nexus/content/groups/public" } + maven { url "https://repo.codemc.org/repository/maven-public" } + maven { url 'https://papermc.io/repo/repository/maven-public/' } } dependencies { @@ -12,6 +14,7 @@ dependencies { compile 'com.sk89q:dummypermscompat:1.10' compile 'com.destroystokyo.paper:paper-api:1.13.2-R0.1-SNAPSHOT' compile 'org.spigotmc:spigot:1.13.2-R0.1-SNAPSHOT' + compile 'org.slf4j:slf4j-jdk14:1.7.26' testCompile 'org.mockito:mockito-core:1.9.0-rc1' compile 'com.massivecraft:factions:2.8.0' compile 'com.drtshock:factions:1.6.9.5' diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java index 628956cdf..8c5c639d2 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java @@ -49,20 +49,21 @@ import org.bukkit.craftbukkit.v1_13_R2.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_13_R2.entity.CraftEntity; import org.bukkit.entity.Player; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkNotNull; public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements BukkitImplAdapter{ - private final Logger logger = Logger.getLogger(getClass().getCanonicalName()); + private final Logger logger = LoggerFactory.getLogger(getClass()); private final Field nbtListTagListField; private final Method nbtCreateTagMethod; @@ -348,7 +349,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit return Collections.emptyMap(); } if (block == null) { - logger.warning("Failed to find properties for " + blockType.getId()); + logger.warn("Failed to find properties for " + blockType.getId()); return Collections.emptyMap(); } Map> properties = Maps.newLinkedHashMap(); @@ -414,7 +415,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit try { return toNativeList((NBTTagList) foreign); } catch (Throwable e) { - logger.log(Level.WARNING, "Failed to convert NBTTagList", e); + logger.warn("Failed to convert NBTTagList", e); return new ListTag(ByteTag.class, new ArrayList()); } } else if (foreign instanceof NBTTagLong) { diff --git a/worldedit-bukkit/src/main/java/com/sk89q/wepif/FlatFilePermissionsResolver.java b/worldedit-bukkit/src/main/java/com/sk89q/wepif/FlatFilePermissionsResolver.java index 3f2324596..9b5229cf3 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/wepif/FlatFilePermissionsResolver.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/wepif/FlatFilePermissionsResolver.java @@ -22,6 +22,8 @@ package com.sk89q.wepif; import com.sk89q.util.yaml.YAMLProcessor; import org.bukkit.OfflinePlayer; import org.bukkit.Server; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; @@ -32,12 +34,10 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; public class FlatFilePermissionsResolver implements PermissionsResolver { - private static final Logger log = Logger.getLogger(FlatFilePermissionsResolver.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(FlatFilePermissionsResolver.class); private Map> userPermissionsCache; private Set defaultPermissionsCache; @@ -98,7 +98,7 @@ public class FlatFilePermissionsResolver implements PermissionsResolver { } } } catch (IOException e) { - log.log(Level.WARNING, "Failed to load permissions", e); + log.warn("Failed to load permissions", e); } finally { try { if (buff != null) { @@ -164,7 +164,7 @@ public class FlatFilePermissionsResolver implements PermissionsResolver { } } } catch (IOException e) { - log.log(Level.WARNING, "Failed to load permissions", e); + log.warn("Failed to load permissions", e); } finally { try { if (buff != null) { diff --git a/worldedit-bukkit/src/main/java/com/sk89q/wepif/NijiPermissionsResolver.java b/worldedit-bukkit/src/main/java/com/sk89q/wepif/NijiPermissionsResolver.java index fe23bfa46..ef12e2ff4 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/wepif/NijiPermissionsResolver.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/wepif/NijiPermissionsResolver.java @@ -28,13 +28,12 @@ import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; - -import java.util.logging.Level; -import java.util.logging.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NijiPermissionsResolver implements PermissionsResolver { - private static final Logger log = Logger.getLogger(NijiPermissionsResolver.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(NijiPermissionsResolver.class); private Server server; private Permissions api; @@ -84,7 +83,7 @@ public class NijiPermissionsResolver implements PermissionsResolver { return api.Security.permission(player, permission); } } catch (Throwable t) { - log.log(Level.WARNING, "Failed to check permissions", t); + log.warn("Failed to check permissions", t); return false; } } @@ -98,7 +97,7 @@ public class NijiPermissionsResolver implements PermissionsResolver { return api.getHandler().has(server.getPlayerExact(name), permission); } } catch (Throwable t) { - log.log(Level.WARNING, "Failed to check permissions", t); + log.warn("Failed to check permissions", t); return false; } } @@ -115,7 +114,7 @@ public class NijiPermissionsResolver implements PermissionsResolver { return api.Security.inGroup(name, group); } } catch (Throwable t) { - log.log(Level.WARNING, "Failed to check groups", t); + log.warn("Failed to check groups", t); return false; } } @@ -139,7 +138,7 @@ public class NijiPermissionsResolver implements PermissionsResolver { return groups; } } catch (Throwable t) { - log.log(Level.WARNING, "Failed to get groups", t); + log.warn("Failed to get groups", t); return new String[0]; } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java b/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java index 4775d86c4..6514912a8 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java @@ -27,6 +27,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.plugin.Plugin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; @@ -35,8 +37,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; public class PermissionsResolverManager implements PermissionsResolver { @@ -85,7 +85,7 @@ public class PermissionsResolverManager implements PermissionsResolver { private Server server; private PermissionsResolver permissionResolver; private YAMLProcessor config; - private Logger logger = Logger.getLogger(getClass().getCanonicalName()); + private Logger logger = LoggerFactory.getLogger(getClass()); private List> enabledResolvers = new ArrayList<>(); @SuppressWarnings("unchecked") @@ -119,7 +119,7 @@ public class PermissionsResolverManager implements PermissionsResolver { break; } } catch (Throwable e) { - logger.log(Level.WARNING, "Error in factory method for " + resolverClass.getSimpleName(), e); + logger.warn("Error in factory method for " + resolverClass.getSimpleName(), e); continue; } } @@ -195,14 +195,14 @@ public class PermissionsResolverManager implements PermissionsResolver { try { file.createNewFile(); } catch (IOException e) { - logger.log(Level.WARNING, "Failed to create new configuration file", e); + logger.warn("Failed to create new configuration file", e); } } config = new YAMLProcessor(file, false, YAMLFormat.EXTENDED); try { config.load(); } catch (IOException e) { - logger.log(Level.WARNING, "Error loading WEPIF configuration", e); + logger.warn("Error loading WEPIF configuration", e); } List keys = config.getKeys(null); config.setHeader(CONFIG_HEADER); @@ -232,7 +232,7 @@ public class PermissionsResolverManager implements PermissionsResolver { } catch (ClassNotFoundException e) {} if (next == null || !PermissionsResolver.class.isAssignableFrom(next)) { - logger.warning("WEPIF: Invalid or unknown class found in enabled resolvers: " + logger.warn("WEPIF: Invalid or unknown class found in enabled resolvers: " + nextName + ". Moving to disabled resolvers list."); i.remove(); disabledResolvers.add(nextName); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/wepif/VaultResolver.java b/worldedit-bukkit/src/main/java/com/sk89q/wepif/VaultResolver.java index a918d601a..a97017ceb 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/wepif/VaultResolver.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/wepif/VaultResolver.java @@ -35,9 +35,6 @@ public class VaultResolver implements PermissionsResolver { return null; } RegisteredServiceProvider rsp = server.getServicesManager().getRegistration(Permission.class); - if (rsp == null) { - return null; - } perms = rsp.getProvider(); if (perms == null) { return null; diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockRegistry.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockRegistry.java index 0264ba49e..fcf2fd25d 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockRegistry.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockRegistry.java @@ -54,18 +54,18 @@ public class BukkitBlockRegistry extends BundledBlockRegistry { BlockMaterial result = adapter.getMaterial(blockType); if (result != null) return result; } - Material type = BukkitAdapter.adapt(blockType); - if (type == null) { + Material mat = BukkitAdapter.adapt(blockType); + if (mat == null) { if (blockType == BlockTypes.__RESERVED__) return new PassthroughBlockMaterial(super.getMaterial(BlockTypes.AIR)); return new PassthroughBlockMaterial(null); } if (materialMap == null) { materialMap = new BukkitBlockMaterial[Material.values().length]; } - BukkitBlockMaterial result = materialMap[type.ordinal()]; + BukkitBlockMaterial result = materialMap[mat.ordinal()]; if (result == null) { - result = new BukkitBlockMaterial(BukkitBlockRegistry.super.getMaterial(blockType), type); - materialMap[type.ordinal()] = result; + result = new BukkitBlockMaterial(BukkitBlockRegistry.super.getMaterial(blockType), mat); + materialMap[mat.ordinal()] = result; } return result; } @@ -84,9 +84,8 @@ public class BukkitBlockRegistry extends BundledBlockRegistry { @Nullable @Override public Map> getProperties(BlockType blockType) { - BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); - if (adapter != null) { - return adapter.getProperties(blockType); + if (WorldEditPlugin.getInstance().getBukkitImplAdapter() != null) { + return WorldEditPlugin.getInstance().getBukkitImplAdapter().getProperties(blockType); } return super.getProperties(blockType); } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandInspector.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandInspector.java index b392c50ac..fa3f2917f 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandInspector.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandInspector.java @@ -19,8 +19,6 @@ package com.sk89q.worldedit.bukkit; -import static com.google.common.base.Preconditions.checkNotNull; - import com.sk89q.bukkit.util.CommandInspector; import com.sk89q.minecraft.util.commands.CommandLocals; import com.sk89q.worldedit.extension.platform.Actor; @@ -29,12 +27,14 @@ import com.sk89q.worldedit.util.command.Description; import com.sk89q.worldedit.util.command.Dispatcher; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.logging.Logger; +import static com.google.common.base.Preconditions.checkNotNull; class BukkitCommandInspector implements CommandInspector { - private static final Logger logger = Logger.getLogger(BukkitCommandInspector.class.getCanonicalName()); + private static final Logger logger = LoggerFactory.getLogger(BukkitCommandInspector.class); private final WorldEditPlugin plugin; private final Dispatcher dispatcher; @@ -51,7 +51,7 @@ class BukkitCommandInspector implements CommandInspector { if (mapping != null) { return mapping.getDescription().getDescription(); } else { - logger.warning("BukkitCommandInspector doesn't know how about the command '" + command + "'"); + logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'"); return "Help text not available"; } } @@ -63,7 +63,7 @@ class BukkitCommandInspector implements CommandInspector { Description description = mapping.getDescription(); return "Usage: " + description.getUsage() + (description.getHelp() != null ? "\n" + description.getHelp() : ""); } else { - logger.warning("BukkitCommandInspector doesn't know how about the command '" + command + "'"); + logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'"); return "Help text not available"; } } @@ -76,7 +76,7 @@ class BukkitCommandInspector implements CommandInspector { locals.put(Actor.class, plugin.wrapCommandSender(sender)); return mapping.getCallable().testPermission(locals); } else { - logger.warning("BukkitCommandInspector doesn't know how about the command '" + command + "'"); + logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'"); return false; } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitConfiguration.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitConfiguration.java index 494a464ea..96c755083 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitConfiguration.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitConfiguration.java @@ -22,6 +22,7 @@ package com.sk89q.worldedit.bukkit; import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.worldedit.util.YAMLConfiguration; import com.sk89q.worldedit.util.report.Unreported; +import org.slf4j.LoggerFactory; import java.io.File; @@ -34,7 +35,7 @@ public class BukkitConfiguration extends YAMLConfiguration { @Unreported private final WorldEditPlugin plugin; public BukkitConfiguration(YAMLProcessor config, WorldEditPlugin plugin) { - super(config, plugin.getLogger()); + super(config, LoggerFactory.getLogger(plugin.getLogger().getName())); this.plugin = plugin; } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitItemCategoryRegistry.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitItemCategoryRegistry.java index b5291b4e1..c75c56eb2 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitItemCategoryRegistry.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitItemCategoryRegistry.java @@ -49,4 +49,4 @@ public class BukkitItemCategoryRegistry implements ItemCategoryRegistry { public Set getAll(Category category) { return getCategorisedByName(category.getId()); } -} \ No newline at end of file +} diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitServerInterface.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitServerInterface.java index bf460997e..2d312c19f 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitServerInterface.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitServerInterface.java @@ -149,7 +149,7 @@ public class BukkitServerInterface implements MultiUserPlatform { @Override public String getPlatformName() { - return "bukkit"; + return "Bukkit"; } @Override diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitWorld.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitWorld.java index a199b6069..820d4a396 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitWorld.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitWorld.java @@ -48,6 +48,7 @@ import org.bukkit.block.Chest; import org.bukkit.entity.Entity; import org.bukkit.inventory.DoubleChestInventory; import org.bukkit.inventory.Inventory; +import org.slf4j.Logger; import javax.annotation.Nullable; import java.lang.ref.WeakReference; @@ -56,8 +57,7 @@ import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; + import static com.google.common.base.Preconditions.checkNotNull; public class BukkitWorld extends AbstractWorld { @@ -118,9 +118,9 @@ public class BukkitWorld extends AbstractWorld { return null; } } catch (Exception e) { - logger.warning("Corrupt entity found when creating: " + entity.getType().getId()); + logger.warn("Corrupt entity found when creating: " + entity.getType().getId()); if (entity.getNbtData() != null) { - logger.warning(entity.getNbtData().toString()); + logger.warn(entity.getNbtData().toString()); } e.printStackTrace(); return null; @@ -183,7 +183,7 @@ public class BukkitWorld extends AbstractWorld { try { getWorld().regenerateChunk(chunk.getBlockX(), chunk.getBlockZ()); } catch (Throwable t) { - logger.log(Level.WARNING, "Chunk generation via Bukkit raised an error", t); + logger.warn("Chunk generation via Bukkit raised an error", t); } // Then restore @@ -280,7 +280,7 @@ public class BukkitWorld extends AbstractWorld { treeTypeMapping.put(TreeGenerator.TreeType.RANDOM_MUSHROOM, TreeType.BROWN_MUSHROOM); for (TreeGenerator.TreeType type : TreeGenerator.TreeType.values()) { if (treeTypeMapping.get(type) == null) { - WorldEdit.logger.severe("No TreeType mapping for TreeGenerator.TreeType." + type); + WorldEdit.logger.error("No TreeType mapping for TreeGenerator.TreeType." + type); } } } @@ -425,9 +425,9 @@ public class BukkitWorld extends AbstractWorld { try { return adapter.setBlock(BukkitAdapter.adapt(getWorld(), position), block, notifyAndLight); } catch (Exception e) { - if (block instanceof BaseBlock && ((BaseBlock)block).getNbtData() != null) { - logger.warning("Tried to set a corrupt tile entity at " + position.toString()); - logger.warning(((BaseBlock)block).getNbtData().toString()); + if (block instanceof BaseBlock && ((BaseBlock) block).getNbtData() != null) { + logger.warn("Tried to set a corrupt tile entity at " + position.toString()); + logger.warn(((BaseBlock) block).getNbtData().toString()); } e.printStackTrace(); Block bukkitBlock = getWorld().getBlockAt(position.getBlockX(), position.getBlockY(), position.getBlockZ()); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java index 78f8c8091..23e64aec2 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java @@ -33,24 +33,46 @@ import com.sk89q.worldedit.bukkit.adapter.AdapterLoadException; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplLoader; import com.sk89q.worldedit.event.platform.CommandEvent; +import com.sk89q.worldedit.event.platform.CommandSuggestionEvent; import com.sk89q.worldedit.event.platform.PlatformReadyEvent; +import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Capability; -import com.sk89q.worldedit.extension.platform.NoCapablePlatformException; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extent.inventory.BlockBag; +import com.sk89q.worldedit.registry.state.Property; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BlockCategory; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.FuzzyBlockState; +import com.sk89q.worldedit.world.entity.EntityType; +import com.sk89q.worldedit.world.item.ItemCategory; +import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.registry.LegacyMapper; +import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.block.Biome; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; -import org.bukkit.plugin.*; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPluginLoader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nullable; -import java.io.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; @@ -59,7 +81,6 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.jar.JarFile; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.zip.ZipEntry; import static com.google.common.base.Preconditions.checkNotNull; @@ -67,10 +88,9 @@ import static com.google.common.base.Preconditions.checkNotNull; /** * Plugin for Bukkit. */ -public class WorldEditPlugin extends JavaPlugin //implements TabCompleter -{ +public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter - private static final Logger log = Logger.getLogger("FastAsyncWorldEdit"); + private static final Logger log = LoggerFactory.getLogger(WorldEditPlugin.class); public static final String CUI_PLUGIN_CHANNEL = "worldedit:cui"; private static WorldEditPlugin INSTANCE; @@ -220,18 +240,18 @@ public class WorldEditPlugin extends JavaPlugin //implements TabCompleter } } } - { - Logger logger = getLogger(); - if (logger != null) { - try { - Field nameField = Logger.class.getDeclaredField("name"); - nameField.setAccessible(true); - nameField.set(logger, "FastAsyncWorldEdit"); - } catch (Throwable ignore) { - ignore.printStackTrace(); - } - } - } +// { +// Logger logger = getLogger(); +// if (logger != null) { +// try { +// Field nameField = Logger.class.getDeclaredField("name"); +// nameField.setAccessible(true); +// nameField.set(logger, "FastAsyncWorldEdit"); +// } catch (Throwable ignore) { +// ignore.printStackTrace(); +// } +// } +// } { File pluginsFolder = MainUtil.getJarFile().getParentFile(); for (File file : pluginsFolder.listFiles()) { @@ -245,7 +265,7 @@ public class WorldEditPlugin extends JavaPlugin //implements TabCompleter e.printStackTrace(); } } - log.log(Level.INFO, "Please restart the server if you have any plugins which depend on FAWE."); + getLogger().info("Please restart the server if you have any plugins which depend on FAWE."); } } @@ -253,7 +273,7 @@ public class WorldEditPlugin extends JavaPlugin //implements TabCompleter try { run.run(); } catch (Throwable e) { - log.log(Level.SEVERE, message); + getLogger().severe(message); e.printStackTrace(); } } @@ -264,7 +284,7 @@ public class WorldEditPlugin extends JavaPlugin //implements TabCompleter config = new BukkitConfiguration(new YAMLProcessor(new File(getDataFolder(), "config-legacy.yml"), true), this); config.load(); } catch (Throwable e) { - log.log(Level.SEVERE, "Failed to load config.yml"); + getLogger().severe("Failed to load config.yml"); e.printStackTrace(); } // Create schematics folder @@ -280,37 +300,33 @@ public class WorldEditPlugin extends JavaPlugin //implements TabCompleter BukkitImplLoader adapterLoader = new BukkitImplLoader(); try { adapterLoader.addClass(Spigot_v1_13_R2.class); - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (Throwable throwable) { + throwable.printStackTrace(); } try { adapterLoader.addFromPath(getClass().getClassLoader()); } catch (IOException e) { - log.log(Level.WARNING, "Failed to search path for Bukkit adapters"); + log.warn("Failed to search path for Bukkit adapters"); } try { adapterLoader.addFromJar(getFile()); } catch (IOException e) { - log.log(Level.WARNING, "Failed to search " + getFile() + " for Bukkit adapters", e); + log.warn("Failed to search " + getFile() + " for Bukkit adapters", e); } try { bukkitAdapter = adapterLoader.loadAdapter(); - log.log(Level.INFO, "Using " + bukkitAdapter.getClass().getCanonicalName() + " as the Bukkit adapter"); + log.info("Using " + bukkitAdapter.getClass().getCanonicalName() + " as the Bukkit adapter"); } catch (AdapterLoadException e) { - try { - Platform platform = worldEdit.getPlatformManager().queryCapability(Capability.WORLD_EDITING); - if (platform instanceof BukkitServerInterface) { - log.log(Level.WARNING, e.getMessage()); - return; - } else { - log.log(Level.INFO, "WorldEdit could not find a Bukkit adapter for this MC version, " + - "but it seems that you have another implementation of WorldEdit installed (" + platform.getPlatformName() + ") " + - "that handles the world editing."); - } - } catch (NoCapablePlatformException ignore) {} - log.log(Level.INFO, "WorldEdit could not find a Bukkit adapter for this MC version"); + Platform platform = worldEdit.getPlatformManager().queryCapability(Capability.WORLD_EDITING); + if (platform instanceof BukkitServerInterface) { + log.warn(e.getMessage()); + } else { + log.info("WorldEdit could not find a Bukkit adapter for this MC version, " + + "but it seems that you have another implementation of WorldEdit installed (" + platform.getPlatformName() + ") " + + "that handles the world editing."); + } } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplLoader.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplLoader.java index db82a2abb..db87058d3 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplLoader.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplLoader.java @@ -20,6 +20,8 @@ package com.sk89q.worldedit.bukkit.adapter; import com.sk89q.worldedit.util.io.Closer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; @@ -29,15 +31,13 @@ import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; -import java.util.logging.Level; -import java.util.logging.Logger; /** * Loads Bukkit implementation adapters. */ public class BukkitImplLoader { - private static final Logger log = Logger.getLogger(BukkitImplLoader.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(BukkitImplLoader.class); private final List adapterCandidates = new ArrayList<>(); private String customCandidate; @@ -73,7 +73,7 @@ public class BukkitImplLoader { if (className != null) { customCandidate = className; adapterCandidates.add(className); - log.log(Level.INFO, "-Dworldedit.bukkit.adapter used to add " + className + " to the list of available Bukkit adapters"); + log.info("-Dworldedit.bukkit.adapter used to add " + className + " to the list of available Bukkit adapters"); } } @@ -161,19 +161,18 @@ public class BukkitImplLoader { if (BukkitImplAdapter.class.isAssignableFrom(cls)) { return (BukkitImplAdapter) cls.newInstance(); } else { - log.log(Level.WARNING, "Failed to load the Bukkit adapter class '" + className + + log.warn("Failed to load the Bukkit adapter class '" + className + "' because it does not implement " + BukkitImplAdapter.class.getCanonicalName()); } } catch (ClassNotFoundException e) { - log.log(Level.WARNING, "Failed to load the Bukkit adapter class '" + className + + log.warn("Failed to load the Bukkit adapter class '" + className + "' that is not supposed to be missing", e); } catch (IllegalAccessException e) { - log.log(Level.WARNING, "Failed to load the Bukkit adapter class '" + className + + log.warn("Failed to load the Bukkit adapter class '" + className + "' that is not supposed to be raising this error", e); } catch (Throwable e) { - e.printStackTrace(); if (className.equals(customCandidate)) { - log.log(Level.WARNING, "Failed to load the Bukkit adapter class '" + className + "'", e); + log.warn("Failed to load the Bukkit adapter class '" + className + "'", e); } } } diff --git a/worldedit-core/build.gradle b/worldedit-core/build.gradle index 89a595b92..eb0f957c3 100644 --- a/worldedit-core/build.gradle +++ b/worldedit-core/build.gradle @@ -1,87 +1,89 @@ -apply plugin: 'eclipse' -apply plugin: 'idea' -repositories { - maven {url "http://ci.athion.net/job/PlotSquared-Breaking/ws/mvn/"} -} -dependencies { - compile 'de.schlichtherle:truezip:6.8.3' - compile 'rhino:js:1.7R2' - compile 'com.google.guava:guava:21.0' - compile 'com.sk89q:jchronic:0.2.4a' - compile 'com.google.code.findbugs:jsr305:1.3.9' - compile 'com.thoughtworks.paranamer:paranamer:2.6' - compile 'com.google.code.gson:gson:2.8.0' - compile 'com.sk89q.lib:jlibnoise:1.0.0' - compile 'com.googlecode.json-simple:json-simple:1.1.1' - testCompile 'org.mockito:mockito-core:1.9.0-rc1' - - // Fawe depends - compile 'org.yaml:snakeyaml:1.19' - compile 'net.fabiozumbi12:redprotect:1.9.6' - compile ("com.github.intellectualsites.plotsquared:PlotSquared-API:latest") { - transitive = false - } - compile 'com.github.luben:zstd-jni:1.1.1' - compile 'co.aikar:fastutil-lite:1.0' -} - -sourceSets { - main { - java { - srcDir 'src/main/java' - srcDir 'src/legacy/java' - } - resources { - srcDir 'src/main/resources' - } - } -} - -processResources { - from('src/main/resources') { - include 'fawe.properties' - expand( - internalVersion: "${project.parent.version}", - name: project.parent.name, - ) - } -} - -jar.archiveName="fawe-api-${project.parent.version}.jar" -jar.destinationDir = file '../mvn/com/boydti/fawe-api/' + project.parent.version -task createPom << { - pom { - project { - groupId 'com.boydti' - artifactId 'fawe-api' - version project.parent.version - } - } - .getEffectivePom() - .setDependencies(new ArrayList<>()) - .writeTo("../mvn/com/boydti/fawe-api/${project.parent.version}/fawe-api-${project.parent.version}.pom") - pom { - project { - groupId 'com.boydti' - artifactId 'fawe-api' - version 'latest' - } - } - .getEffectivePom() - .setDependencies(new ArrayList<>()) - .writeTo("../mvn/com/boydti/fawe-api/latest/fawe-api-latest.pom") -} -task copyFiles { - doLast { - copy { - from "../mvn/com/boydti/fawe-api/${project.parent.version}/" - into '../mvn/com/boydti/fawe-api/latest/' - include('*.jar') - rename ("fawe-api-${project.parent.version}.jar", 'fawe-api-latest.jar') - } - } -} - -build.dependsOn(shadowJar) -build.finalizedBy(copyFiles) -copyFiles.dependsOn(createPom) +apply plugin: 'eclipse' +apply plugin: 'idea' +repositories { + maven {url "http://ci.athion.net/job/PlotSquared-Breaking/ws/mvn/"} +} +dependencies { + compile 'de.schlichtherle:truezip:6.8.3' + compile 'rhino:js:1.7R2' + compile 'com.google.guava:guava:21.0' + compile 'com.sk89q:jchronic:0.2.4a' + compile 'com.google.code.findbugs:jsr305:1.3.9' + compile 'com.thoughtworks.paranamer:paranamer:2.6' + compile 'com.google.code.gson:gson:2.8.0' + compile 'com.sk89q.lib:jlibnoise:1.0.0' + compile 'com.googlecode.json-simple:json-simple:1.1.1' + compile 'org.slf4j:slf4j-api:1.7.26' + //compile 'net.sf.trove4j:trove4j:3.0.3' + testCompile 'org.mockito:mockito-core:1.9.0-rc1' + + // Fawe depends + compile 'org.yaml:snakeyaml:1.19' + compile 'net.fabiozumbi12:redprotect:1.9.6' + compile ("com.github.intellectualsites.plotsquared:PlotSquared-API:latest") { + transitive = false + } + compile 'com.github.luben:zstd-jni:1.1.1' + compile 'co.aikar:fastutil-lite:1.0' +} + +sourceSets { + main { + java { + srcDir 'src/main/java' + srcDir 'src/legacy/java' + } + resources { + srcDir 'src/main/resources' + } + } +} + +processResources { + from('src/main/resources') { + include 'fawe.properties' + expand( + internalVersion: "${project.parent.version}", + name: project.parent.name, + ) + } +} + +jar.archiveName="fawe-api-${project.parent.version}.jar" +jar.destinationDir = file '../mvn/com/boydti/fawe-api/' + project.parent.version +task createPom << { + pom { + project { + groupId 'com.boydti' + artifactId 'fawe-api' + version project.parent.version + } + } + .getEffectivePom() + .setDependencies(new ArrayList<>()) + .writeTo("../mvn/com/boydti/fawe-api/${project.parent.version}/fawe-api-${project.parent.version}.pom") + pom { + project { + groupId 'com.boydti' + artifactId 'fawe-api' + version 'latest' + } + } + .getEffectivePom() + .setDependencies(new ArrayList<>()) + .writeTo("../mvn/com/boydti/fawe-api/latest/fawe-api-latest.pom") +} +task copyFiles { + doLast { + copy { + from "../mvn/com/boydti/fawe-api/${project.parent.version}/" + into '../mvn/com/boydti/fawe-api/latest/' + include('*.jar') + rename ("fawe-api-${project.parent.version}.jar", 'fawe-api-latest.jar') + } + } +} + +build.dependsOn(shadowJar) +build.finalizedBy(copyFiles) +copyFiles.dependsOn(createPom) diff --git a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SignBlock.java b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SignBlock.java index 60dabd6c7..4cc0e5bcb 100644 --- a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SignBlock.java +++ b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SignBlock.java @@ -25,6 +25,7 @@ import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.util.gson.GsonUtil; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; + import java.util.HashMap; import java.util.Map; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/configuration/serialization/ConfigurationSerialization.java b/worldedit-core/src/main/java/com/boydti/fawe/configuration/serialization/ConfigurationSerialization.java index 445702c6f..f3249bbbf 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/configuration/serialization/ConfigurationSerialization.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/configuration/serialization/ConfigurationSerialization.java @@ -1,16 +1,16 @@ package com.boydti.fawe.configuration.serialization; +import com.boydti.fawe.configuration.Configuration; +import org.slf4j.LoggerFactory; + import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - /** - * Utility class for storing and retrieving classes for {@link com.boydti.fawe.configuration.Configuration}. + * Utility class for storing and retrieving classes for {@link Configuration}. */ public class ConfigurationSerialization { @@ -27,7 +27,7 @@ public class ConfigurationSerialization { * Attempts to deserialize the given arguments into a new instance of the * given class. *

- *

The class must implement {@link com.boydti.fawe.configuration.serialization.ConfigurationSerializable}, including + *

The class must implement {@link ConfigurationSerializable}, including * the extra methods as specified in the javadoc of * ConfigurationSerializable.

*

@@ -39,7 +39,7 @@ public class ConfigurationSerialization { * @return New instance of the specified class */ public static ConfigurationSerializable deserializeObject(Map args, Class clazz) { - return new com.boydti.fawe.configuration.serialization.ConfigurationSerialization(clazz).deserialize(args); + return new ConfigurationSerialization(clazz).deserialize(args); } /** @@ -47,7 +47,7 @@ public class ConfigurationSerialization { *

* given class. *

- * The class must implement {@link com.boydti.fawe.configuration.serialization.ConfigurationSerializable}, including + * The class must implement {@link ConfigurationSerializable}, including * the extra methods as specified in the javadoc of * ConfigurationSerializable.

*

@@ -80,17 +80,17 @@ public class ConfigurationSerialization { throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); } - return new com.boydti.fawe.configuration.serialization.ConfigurationSerialization(clazz).deserialize(args); + return new ConfigurationSerialization(clazz).deserialize(args); } /** - * Registers the given {@link com.boydti.fawe.configuration.serialization.ConfigurationSerializable} class by its + * Registers the given {@link ConfigurationSerializable} class by its * alias. * * @param clazz Class to register */ public static void registerClass(Class clazz) { - com.boydti.fawe.configuration.serialization.DelegateDeserialization delegate = clazz.getAnnotation(com.boydti.fawe.configuration.serialization.DelegateDeserialization.class); + DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); if (delegate == null) { registerClass(clazz, getAlias(clazz)); @@ -99,19 +99,18 @@ public class ConfigurationSerialization { } /** - * Registers the given alias to the specified {@link - * com.boydti.fawe.configuration.serialization.ConfigurationSerializable} class. + * Registers the given alias to the specified {@link ConfigurationSerializable} class. * * @param clazz Class to register * @param alias Alias to register as - * @see com.boydti.fawe.configuration.serialization.SerializableAs + * @see SerializableAs */ public static void registerClass(Class clazz, String alias) { aliases.put(alias, clazz); } /** - * Unregisters the specified alias to a {@link com.boydti.fawe.configuration.serialization.ConfigurationSerializable} + * Unregisters the specified alias to a {@link ConfigurationSerializable} * * @param alias Alias to unregister */ @@ -120,8 +119,7 @@ public class ConfigurationSerialization { } /** - * Unregisters any aliases for the specified {@link - * com.boydti.fawe.configuration.serialization.ConfigurationSerializable} class. + * Unregisters any aliases for the specified {@link ConfigurationSerializable} class. * * @param clazz Class to unregister */ @@ -131,7 +129,7 @@ public class ConfigurationSerialization { } /** - * Attempts to get a registered {@link com.boydti.fawe.configuration.serialization.ConfigurationSerializable} class by + * Attempts to get a registered {@link ConfigurationSerializable} class by * its alias. * * @param alias Alias of the serializable @@ -142,14 +140,14 @@ public class ConfigurationSerialization { } /** - * Gets the correct alias for the given {@link com.boydti.fawe.configuration.serialization.ConfigurationSerializable} + * Gets the correct alias for the given {@link ConfigurationSerializable} * class. * * @param clazz Class to get alias for * @return Alias to use for the class */ public static String getAlias(Class clazz) { - com.boydti.fawe.configuration.serialization.DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); + DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); if (delegate != null) { if ((delegate.value() == null) || (delegate.value() == clazz)) { @@ -180,9 +178,7 @@ public class ConfigurationSerialization { } return method; - } catch (NoSuchMethodException ex) { - return null; - } catch (SecurityException ex) { + } catch (NoSuchMethodException | SecurityException ex) { return null; } } @@ -190,9 +186,7 @@ public class ConfigurationSerialization { protected Constructor getConstructor() { try { return this.clazz.getConstructor(Map.class); - } catch (NoSuchMethodException ex) { - return null; - } catch (SecurityException ex) { + } catch (NoSuchMethodException | SecurityException ex) { return null; } } @@ -202,14 +196,13 @@ public class ConfigurationSerialization { ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args); if (result == null) { - Logger.getLogger(com.boydti.fawe.configuration.serialization.ConfigurationSerialization.class.getName()).log(Level.SEVERE, + LoggerFactory.getLogger(ConfigurationSerialization.class).error( "Could not call method '" + method.toString() + "' of " + this.clazz + " for deserialization: method returned null"); } else { return result; } } catch (Throwable ex) { - Logger.getLogger(com.boydti.fawe.configuration.serialization.ConfigurationSerialization.class.getName()) - .log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + this.clazz + LoggerFactory.getLogger(ConfigurationSerialization.class).error("Could not call method '" + method.toString() + "' of " + this.clazz + " for deserialization", ex instanceof InvocationTargetException ? ex.getCause() : ex); } @@ -221,8 +214,7 @@ public class ConfigurationSerialization { try { return ctor.newInstance(args); } catch (Throwable ex) { - Logger.getLogger(com.boydti.fawe.configuration.serialization.ConfigurationSerialization.class.getName()) - .log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + this.clazz + LoggerFactory.getLogger(ConfigurationSerialization.class).error("Could not call constructor '" + ctor.toString() + "' of " + this.clazz + " for deserialization", ex instanceof InvocationTargetException ? ex.getCause() : ex); } diff --git a/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/CommandsManager.java b/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/CommandsManager.java index a8f49678b..f8af6a8c2 100644 --- a/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/CommandsManager.java +++ b/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/CommandsManager.java @@ -1,585 +1,585 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.minecraft.util.commands; - -import com.sk89q.util.StringUtil; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Manager for handling commands. This allows you to easily process commands, - * including nested commands, by correctly annotating methods of a class. - * - *

To use this, it is merely a matter of registering classes containing - * the commands (as methods with the proper annotations) with the - * manager. When you want to process a command, use one of the - * {@code execute} methods. If something is wrong, such as incorrect - * usage, insufficient permissions, or a missing command altogether, an - * exception will be raised for upstream handling.

- * - *

Methods of a class to be registered can be static, but if an injector - * is registered with the class, the instances of the command classes - * will be created automatically and methods will be called non-statically.

- * - *

To mark a method as a command, use {@link Command}. For nested commands, - * see {@link NestedCommand}. To handle permissions, use - * {@link CommandPermissions}.

- * - *

This uses Java reflection extensively, but to reduce the overhead of - * reflection, command lookups are completely cached on registration. This - * allows for fast command handling. Method invocation still has to be done - * with reflection, but this is quite fast in that of itself.

- * - * @param command sender class - */ -@SuppressWarnings("ProtectedField") -public abstract class CommandsManager { - - protected static final Logger logger = - Logger.getLogger(CommandsManager.class.getCanonicalName()); - - /** - * Mapping of commands (including aliases) with a description. Root - * commands are stored under a key of null, whereas child commands are - * cached under their respective {@link Method}. The child map has - * the key of the command name (one for each alias) with the - * method. - */ - protected Map> commands = new HashMap<>(); - - /** - * Used to store the instances associated with a method. - */ - protected Map instances = new HashMap<>(); - - /** - * Mapping of commands (not including aliases) with a description. This - * is only for top level commands. - */ - protected Map descs = new HashMap<>(); - - /** - * Stores the injector used to getInstance. - */ - protected Injector injector; - - /** - * Mapping of commands (not including aliases) with a description. This - * is only for top level commands. - */ - protected Map helpMessages = new HashMap<>(); - - /** - * Register an class that contains commands (denoted by {@link Command}. - * If no dependency injector is specified, then the methods of the - * class will be registered to be called statically. Otherwise, new - * instances will be created of the command classes and methods will - * not be called statically. - * - * @param cls the class to register - */ - public void register(Class cls) { - registerMethods(cls, null); - } - - /** - * Register an class that contains commands (denoted by {@link Command}. - * If no dependency injector is specified, then the methods of the - * class will be registered to be called statically. Otherwise, new - * instances will be created of the command classes and methods will - * not be called statically. A List of {@link Command} annotations from - * registered commands is returned. - * - * @param cls the class to register - * @return A List of {@link Command} annotations from registered commands, - * for use in eg. a dynamic command registration system. - */ - public List registerAndReturn(Class cls) { - return registerMethods(cls, null); - } - - /** - * Register the methods of a class. This will automatically construct - * instances as necessary. - * - * @param cls the class to register - * @param parent the parent method - * @return Commands Registered - */ - public List registerMethods(Class cls, Method parent) { - try { - if (getInjector() == null) { - return registerMethods(cls, parent, null); - } else { - Object obj = getInjector().getInstance(cls); - return registerMethods(cls, parent, obj); - } - } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { - logger.log(Level.SEVERE, "Failed to register commands", e); - } - return null; - } - - /** - * Register the methods of a class. - * - * @param cls the class to register - * @param parent the parent method - * @param obj the object whose methods will become commands if they are annotated - * @return a list of commands - */ - private List registerMethods(Class cls, Method parent, Object obj) { - Map map; - List registered = new ArrayList<>(); - - // Make a new hash map to cache the commands for this class - // as looking up methods via reflection is fairly slow - if (commands.containsKey(parent)) { - map = commands.get(parent); - } else { - map = new HashMap<>(); - commands.put(parent, map); - } - - for (Method method : cls.getMethods()) { - if (!method.isAnnotationPresent(Command.class)) { - continue; - } - - boolean isStatic = Modifier.isStatic(method.getModifiers()); - - Command cmd = method.getAnnotation(Command.class); - - // Cache the aliases too - for (String alias : cmd.aliases()) { - map.put(alias, method); - } - - // We want to be able invoke with an instance - if (!isStatic) { - // Can't register this command if we don't have an instance - if (obj == null) { - continue; - } - - instances.put(method, obj); - } - - // Build a list of commands and their usage details, at least for - // root level commands - if (parent == null) { - final String commandName = cmd.aliases()[0]; - final String desc = cmd.desc(); - - final String usage = cmd.usage(); - if (usage.isEmpty()) { - descs.put(commandName, desc); - } else { - descs.put(commandName, usage + " - " + desc); - } - - String help = cmd.help(); - if (help.isEmpty()) { - help = desc; - } - - final CharSequence arguments = getArguments(cmd); - for (String alias : cmd.aliases()) { - final String helpMessage = "/" + alias + " " + arguments + "\n\n" + help; - final String key = alias.replaceAll("/", ""); - String previous = helpMessages.put(key, helpMessage); - - if (previous != null && !previous.replaceAll("^/[^ ]+ ", "").equals(helpMessage.replaceAll("^/[^ ]+ ", ""))) { - helpMessages.put(key, previous + "\n\n" + helpMessage); - } - } - - } - - // Add the command to the registered command list for return - registered.add(cmd); - - // Look for nested commands -- if there are any, those have - // to be cached too so that they can be quickly looked - // up when processing commands - if (method.isAnnotationPresent(NestedCommand.class)) { - NestedCommand nestedCmd = method.getAnnotation(NestedCommand.class); - - for (Class nestedCls : nestedCmd.value()) { - registerMethods(nestedCls, method); - } - } - } - - if (cls.getSuperclass() != null) { - registerMethods(cls.getSuperclass(), parent, obj); - } - - return registered; - } - - /** - * Checks to see whether there is a command named such at the root level. - * This will check aliases as well. - * - * @param command the command - * @return true if the command exists - */ - public boolean hasCommand(String command) { - return commands.get(null).containsKey(command.toLowerCase()); - } - - /** - * Get a list of command descriptions. This is only for root commands. - * - * @return a map of commands - */ - public Map getCommands() { - return descs; - } - - /** - * Get the mapping of methods under a parent command. - * - * @return the mapping - */ - public Map> getMethods() { - return commands; - } - - /** - * Get a map from command name to help message. This is only for root commands. - * - * @return a map of help messages for each command - */ - public Map getHelpMessages() { - return helpMessages; - } - - /** - * Get the usage string for a command. - * - * @param args the arguments - * @param level the depth of the command - * @param cmd the command annotation - * @return the usage string - */ - protected String getUsage(String[] args, int level, Command cmd) { - final StringBuilder command = new StringBuilder(); - - command.append('/'); - - for (int i = 0; i <= level; ++i) { - command.append(args[i]); - command.append(' '); - } - command.append(getArguments(cmd)); - - final String help = cmd.help(); - if (!help.isEmpty()) { - command.append("\n\n"); - command.append(help); - } - - return command.toString(); - } - - protected CharSequence getArguments(Command cmd) { - final String flags = cmd.flags(); - - final StringBuilder command2 = new StringBuilder(); - if (!flags.isEmpty()) { - String flagString = flags.replaceAll(".:", ""); - if (!flagString.isEmpty()) { - command2.append("[-"); - for (int i = 0; i < flagString.length(); ++i) { - command2.append(flagString.charAt(i)); - } - command2.append("] "); - } - } - - command2.append(cmd.usage()); - - return command2; - } - - /** - * Get the usage string for a nested command. - * - * @param args the arguments - * @param level the depth of the command - * @param method the parent method - * @param player the player - * @return the usage string - * @throws CommandException on some error - */ - protected String getNestedUsage(String[] args, int level, Method method, T player) throws CommandException { - StringBuilder command = new StringBuilder(); - - command.append("/"); - - for (int i = 0; i <= level; ++i) { - command.append(args[i]).append(" "); - } - - Map map = commands.get(method); - boolean found = false; - - command.append("<"); - - Set allowedCommands = new HashSet<>(); - - for (Map.Entry entry : map.entrySet()) { - Method childMethod = entry.getValue(); - found = true; - - if (hasPermission(childMethod, player)) { - Command childCmd = childMethod.getAnnotation(Command.class); - - allowedCommands.add(childCmd.aliases()[0]); - } - } - - if (!allowedCommands.isEmpty()) { - command.append(StringUtil.joinString(allowedCommands, "|", 0)); - } else { - if (!found) { - command.append("?"); - } else { - //command.append("action"); - throw new CommandPermissionsException(); - } - } - - command.append(">"); - - return command.toString(); - } - - /** - * Attempt to execute a command. This version takes a separate command - * name (for the root command) and then a list of following arguments. - * - * @param cmd command to run - * @param args arguments - * @param player command source - * @param methodArgs method arguments - * @throws CommandException thrown when the command throws an error - */ - public void execute(String cmd, String[] args, T player, Object... methodArgs) throws CommandException { - - String[] newArgs = new String[args.length + 1]; - System.arraycopy(args, 0, newArgs, 1, args.length); - newArgs[0] = cmd; - Object[] newMethodArgs = new Object[methodArgs.length + 1]; - System.arraycopy(methodArgs, 0, newMethodArgs, 1, methodArgs.length); - - executeMethod(null, newArgs, player, newMethodArgs, 0); - } - - /** - * Attempt to execute a command. - * - * @param args the arguments - * @param player the player - * @param methodArgs the arguments for the method - * @throws CommandException thrown on command error - */ - public void execute(String[] args, T player, Object... methodArgs) throws CommandException { - Object[] newMethodArgs = new Object[methodArgs.length + 1]; - System.arraycopy(methodArgs, 0, newMethodArgs, 1, methodArgs.length); - executeMethod(null, args, player, newMethodArgs, 0); - } - - /** - * Attempt to execute a command. - * - * @param parent the parent method - * @param args an array of arguments - * @param player the player - * @param methodArgs the array of method arguments - * @param level the depth of the command - * @throws CommandException thrown on a command error - */ - public void executeMethod(Method parent, String[] args, T player, Object[] methodArgs, int level) throws CommandException { - String cmdName = args[level]; - - Map map = commands.get(parent); - Method method = map.get(cmdName.toLowerCase()); - - if (method == null) { - if (parent == null) { // Root - throw new UnhandledCommandException(); - } else { - throw new MissingNestedCommandException("Unknown command: " + cmdName, - getNestedUsage(args, level - 1, parent, player)); - } - } - - checkPermission(player, method); - - int argsCount = args.length - 1 - level; - - // checks if we need to execute the body of the nested command method (false) - // or display the help what commands are available (true) - // this is all for an args count of 0 if it is > 0 and a NestedCommand Annotation is present - // it will always handle the methods that NestedCommand points to - // e.g.: - // - /cmd - @NestedCommand(executeBody = true) will go into the else loop and execute code in that method - // - /cmd - @NestedCommand(executeBody = true) will always go to the nested command class - // - /cmd - @NestedCommand(executeBody = false) will always go to the nested command class not matter the args - boolean executeNested = method.isAnnotationPresent(NestedCommand.class) - && (argsCount > 0 || !method.getAnnotation(NestedCommand.class).executeBody()); - - if (executeNested) { - if (argsCount == 0) { - throw new MissingNestedCommandException("Sub-command required.", - getNestedUsage(args, level, method, player)); - } else { - executeMethod(method, args, player, methodArgs, level + 1); - } - } else if (method.isAnnotationPresent(CommandAlias.class)) { - CommandAlias aCmd = method.getAnnotation(CommandAlias.class); - executeMethod(parent, aCmd.value(), player, methodArgs, level); - } else { - Command cmd = method.getAnnotation(Command.class); - - String[] newArgs = new String[args.length - level]; - System.arraycopy(args, level, newArgs, 0, args.length - level); - - final Set valueFlags = new HashSet<>(); - - char[] flags = cmd.flags().toCharArray(); - Set newFlags = new HashSet<>(); - for (int i = 0; i < flags.length; ++i) { - if (flags.length > i + 1 && flags[i + 1] == ':') { - valueFlags.add(flags[i]); - ++i; - } - newFlags.add(flags[i]); - } - - CommandContext context = new CommandContext(newArgs, valueFlags); - - if (context.argsLength() < cmd.min()) { - throw new CommandUsageException("Too few arguments.", getUsage(args, level, cmd)); - } - - if (cmd.max() != -1 && context.argsLength() > cmd.max()) { - throw new CommandUsageException("Too many arguments.", getUsage(args, level, cmd)); - } - - if (!cmd.anyFlags()) { - for (char flag : context.getFlags()) { - if (!newFlags.contains(flag)) { - throw new CommandUsageException("Unknown flag: " + flag, getUsage(args, level, cmd)); - } - } - } - - methodArgs[0] = context; - - Object instance = instances.get(method); - - invokeMethod(parent, args, player, method, instance, methodArgs, argsCount); - } - } - - protected void checkPermission(T player, Method method) throws CommandException { - if (!hasPermission(method, player)) { - throw new CommandPermissionsException(); - } - } - - public void invokeMethod(Method parent, String[] args, T player, Method method, Object instance, Object[] methodArgs, int level) throws CommandException { - try { - method.invoke(instance, methodArgs); - } catch (IllegalArgumentException | IllegalAccessException e) { - logger.log(Level.SEVERE, "Failed to execute command", e); - } catch (InvocationTargetException e) { - if (e.getCause() instanceof CommandException) { - throw (CommandException) e.getCause(); - } - - throw new WrappedCommandException(e.getCause()); - } - } - - /** - * Returns whether a player has access to a command. - * - * @param method the method - * @param player the player - * @return true if permission is granted - */ - protected boolean hasPermission(Method method, T player) { - CommandPermissions perms = method.getAnnotation(CommandPermissions.class); - if (perms == null) { - return true; - } - - for (String perm : perms.value()) { - if (hasPermission(player, perm)) { - return true; - } - } - - return false; - } - - /** - * Returns whether a player permission.. - * - * @param player the player - * @param permission the permission - * @return true if permission is granted - */ - public abstract boolean hasPermission(T player, String permission); - - /** - * Get the injector used to create new instances. This can be - * null, in which case only classes will be registered statically. - * - * @return an injector instance - */ - public Injector getInjector() { - return injector; - } - - /** - * Set the injector for creating new instances. - * - * @param injector injector or null - */ - public void setInjector(Injector injector) { - this.injector = injector; - } -} +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.minecraft.util.commands; + +import com.sk89q.util.StringUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Manager for handling commands. This allows you to easily process commands, + * including nested commands, by correctly annotating methods of a class. + * + *

To use this, it is merely a matter of registering classes containing + * the commands (as methods with the proper annotations) with the + * manager. When you want to process a command, use one of the + * {@code execute} methods. If something is wrong, such as incorrect + * usage, insufficient permissions, or a missing command altogether, an + * exception will be raised for upstream handling.

+ * + *

Methods of a class to be registered can be static, but if an injector + * is registered with the class, the instances of the command classes + * will be created automatically and methods will be called non-statically.

+ * + *

To mark a method as a command, use {@link Command}. For nested commands, + * see {@link NestedCommand}. To handle permissions, use + * {@link CommandPermissions}.

+ * + *

This uses Java reflection extensively, but to reduce the overhead of + * reflection, command lookups are completely cached on registration. This + * allows for fast command handling. Method invocation still has to be done + * with reflection, but this is quite fast in that of itself.

+ * + * @param command sender class + */ +@SuppressWarnings("ProtectedField") +public abstract class CommandsManager { + + protected static final Logger logger = + LoggerFactory.getLogger(CommandsManager.class); + + /** + * Mapping of commands (including aliases) with a description. Root + * commands are stored under a key of null, whereas child commands are + * cached under their respective {@link Method}. The child map has + * the key of the command name (one for each alias) with the + * method. + */ + protected Map> commands = new HashMap<>(); + + /** + * Used to store the instances associated with a method. + */ + protected Map instances = new HashMap<>(); + + /** + * Mapping of commands (not including aliases) with a description. This + * is only for top level commands. + */ + protected Map descs = new HashMap<>(); + + /** + * Stores the injector used to getInstance. + */ + protected Injector injector; + + /** + * Mapping of commands (not including aliases) with a description. This + * is only for top level commands. + */ + protected Map helpMessages = new HashMap<>(); + + /** + * Register an class that contains commands (denoted by {@link Command}. + * If no dependency injector is specified, then the methods of the + * class will be registered to be called statically. Otherwise, new + * instances will be created of the command classes and methods will + * not be called statically. + * + * @param cls the class to register + */ + public void register(Class cls) { + registerMethods(cls, null); + } + + /** + * Register an class that contains commands (denoted by {@link Command}. + * If no dependency injector is specified, then the methods of the + * class will be registered to be called statically. Otherwise, new + * instances will be created of the command classes and methods will + * not be called statically. A List of {@link Command} annotations from + * registered commands is returned. + * + * @param cls the class to register + * @return A List of {@link Command} annotations from registered commands, + * for use in eg. a dynamic command registration system. + */ + public List registerAndReturn(Class cls) { + return registerMethods(cls, null); + } + + /** + * Register the methods of a class. This will automatically construct + * instances as necessary. + * + * @param cls the class to register + * @param parent the parent method + * @return Commands Registered + */ + public List registerMethods(Class cls, Method parent) { + try { + if (getInjector() == null) { + return registerMethods(cls, parent, null); + } else { + Object obj = getInjector().getInstance(cls); + return registerMethods(cls, parent, obj); + } + } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { + logger.error("Failed to register commands", e); + } + return null; + } + + /** + * Register the methods of a class. + * + * @param cls the class to register + * @param parent the parent method + * @param obj the object whose methods will become commands if they are annotated + * @return a list of commands + */ + private List registerMethods(Class cls, Method parent, Object obj) { + Map map; + List registered = new ArrayList<>(); + + // Make a new hash map to cache the commands for this class + // as looking up methods via reflection is fairly slow + if (commands.containsKey(parent)) { + map = commands.get(parent); + } else { + map = new HashMap<>(); + commands.put(parent, map); + } + + for (Method method : cls.getMethods()) { + if (!method.isAnnotationPresent(Command.class)) { + continue; + } + + boolean isStatic = Modifier.isStatic(method.getModifiers()); + + Command cmd = method.getAnnotation(Command.class); + + // Cache the aliases too + for (String alias : cmd.aliases()) { + map.put(alias, method); + } + + // We want to be able invoke with an instance + if (!isStatic) { + // Can't register this command if we don't have an instance + if (obj == null) { + continue; + } + + instances.put(method, obj); + } + + // Build a list of commands and their usage details, at least for + // root level commands + if (parent == null) { + final String commandName = cmd.aliases()[0]; + final String desc = cmd.desc(); + + final String usage = cmd.usage(); + if (usage.isEmpty()) { + descs.put(commandName, desc); + } else { + descs.put(commandName, usage + " - " + desc); + } + + String help = cmd.help(); + if (help.isEmpty()) { + help = desc; + } + + final CharSequence arguments = getArguments(cmd); + for (String alias : cmd.aliases()) { + final String helpMessage = "/" + alias + " " + arguments + "\n\n" + help; + final String key = alias.replaceAll("/", ""); + String previous = helpMessages.put(key, helpMessage); + + if (previous != null && !previous.replaceAll("^/[^ ]+ ", "").equals(helpMessage.replaceAll("^/[^ ]+ ", ""))) { + helpMessages.put(key, previous + "\n\n" + helpMessage); + } + } + + } + + // Add the command to the registered command list for return + registered.add(cmd); + + // Look for nested commands -- if there are any, those have + // to be cached too so that they can be quickly looked + // up when processing commands + if (method.isAnnotationPresent(NestedCommand.class)) { + NestedCommand nestedCmd = method.getAnnotation(NestedCommand.class); + + for (Class nestedCls : nestedCmd.value()) { + registerMethods(nestedCls, method); + } + } + } + + if (cls.getSuperclass() != null) { + registerMethods(cls.getSuperclass(), parent, obj); + } + + return registered; + } + + /** + * Checks to see whether there is a command named such at the root level. + * This will check aliases as well. + * + * @param command the command + * @return true if the command exists + */ + public boolean hasCommand(String command) { + return commands.get(null).containsKey(command.toLowerCase()); + } + + /** + * Get a list of command descriptions. This is only for root commands. + * + * @return a map of commands + */ + public Map getCommands() { + return descs; + } + + /** + * Get the mapping of methods under a parent command. + * + * @return the mapping + */ + public Map> getMethods() { + return commands; + } + + /** + * Get a map from command name to help message. This is only for root commands. + * + * @return a map of help messages for each command + */ + public Map getHelpMessages() { + return helpMessages; + } + + /** + * Get the usage string for a command. + * + * @param args the arguments + * @param level the depth of the command + * @param cmd the command annotation + * @return the usage string + */ + protected String getUsage(String[] args, int level, Command cmd) { + final StringBuilder command = new StringBuilder(); + + command.append('/'); + + for (int i = 0; i <= level; ++i) { + command.append(args[i]); + command.append(' '); + } + command.append(getArguments(cmd)); + + final String help = cmd.help(); + if (!help.isEmpty()) { + command.append("\n\n"); + command.append(help); + } + + return command.toString(); + } + + protected CharSequence getArguments(Command cmd) { + final String flags = cmd.flags(); + + final StringBuilder command2 = new StringBuilder(); + if (!flags.isEmpty()) { + String flagString = flags.replaceAll(".:", ""); + if (!flagString.isEmpty()) { + command2.append("[-"); + for (int i = 0; i < flagString.length(); ++i) { + command2.append(flagString.charAt(i)); + } + command2.append("] "); + } + } + + command2.append(cmd.usage()); + + return command2; + } + + /** + * Get the usage string for a nested command. + * + * @param args the arguments + * @param level the depth of the command + * @param method the parent method + * @param player the player + * @return the usage string + * @throws CommandException on some error + */ + protected String getNestedUsage(String[] args, int level, Method method, T player) throws CommandException { + StringBuilder command = new StringBuilder(); + + command.append("/"); + + for (int i = 0; i <= level; ++i) { + command.append(args[i]).append(" "); + } + + Map map = commands.get(method); + boolean found = false; + + command.append("<"); + + Set allowedCommands = new HashSet<>(); + + for (Map.Entry entry : map.entrySet()) { + Method childMethod = entry.getValue(); + found = true; + + if (hasPermission(childMethod, player)) { + Command childCmd = childMethod.getAnnotation(Command.class); + + allowedCommands.add(childCmd.aliases()[0]); + } + } + + if (!allowedCommands.isEmpty()) { + command.append(StringUtil.joinString(allowedCommands, "|", 0)); + } else { + if (!found) { + command.append("?"); + } else { + //command.append("action"); + throw new CommandPermissionsException(); + } + } + + command.append(">"); + + return command.toString(); + } + + /** + * Attempt to execute a command. This version takes a separate command + * name (for the root command) and then a list of following arguments. + * + * @param cmd command to run + * @param args arguments + * @param player command source + * @param methodArgs method arguments + * @throws CommandException thrown when the command throws an error + */ + public void execute(String cmd, String[] args, T player, Object... methodArgs) throws CommandException { + + String[] newArgs = new String[args.length + 1]; + System.arraycopy(args, 0, newArgs, 1, args.length); + newArgs[0] = cmd; + Object[] newMethodArgs = new Object[methodArgs.length + 1]; + System.arraycopy(methodArgs, 0, newMethodArgs, 1, methodArgs.length); + + executeMethod(null, newArgs, player, newMethodArgs, 0); + } + + /** + * Attempt to execute a command. + * + * @param args the arguments + * @param player the player + * @param methodArgs the arguments for the method + * @throws CommandException thrown on command error + */ + public void execute(String[] args, T player, Object... methodArgs) throws CommandException { + Object[] newMethodArgs = new Object[methodArgs.length + 1]; + System.arraycopy(methodArgs, 0, newMethodArgs, 1, methodArgs.length); + executeMethod(null, args, player, newMethodArgs, 0); + } + + /** + * Attempt to execute a command. + * + * @param parent the parent method + * @param args an array of arguments + * @param player the player + * @param methodArgs the array of method arguments + * @param level the depth of the command + * @throws CommandException thrown on a command error + */ + public void executeMethod(Method parent, String[] args, T player, Object[] methodArgs, int level) throws CommandException { + String cmdName = args[level]; + + Map map = commands.get(parent); + Method method = map.get(cmdName.toLowerCase()); + + if (method == null) { + if (parent == null) { // Root + throw new UnhandledCommandException(); + } else { + throw new MissingNestedCommandException("Unknown command: " + cmdName, + getNestedUsage(args, level - 1, parent, player)); + } + } + + checkPermission(player, method); + + int argsCount = args.length - 1 - level; + + // checks if we need to execute the body of the nested command method (false) + // or display the help what commands are available (true) + // this is all for an args count of 0 if it is > 0 and a NestedCommand Annotation is present + // it will always handle the methods that NestedCommand points to + // e.g.: + // - /cmd - @NestedCommand(executeBody = true) will go into the else loop and execute code in that method + // - /cmd - @NestedCommand(executeBody = true) will always go to the nested command class + // - /cmd - @NestedCommand(executeBody = false) will always go to the nested command class not matter the args + boolean executeNested = method.isAnnotationPresent(NestedCommand.class) + && (argsCount > 0 || !method.getAnnotation(NestedCommand.class).executeBody()); + + if (executeNested) { + if (argsCount == 0) { + throw new MissingNestedCommandException("Sub-command required.", + getNestedUsage(args, level, method, player)); + } else { + executeMethod(method, args, player, methodArgs, level + 1); + } + } else if (method.isAnnotationPresent(CommandAlias.class)) { + CommandAlias aCmd = method.getAnnotation(CommandAlias.class); + executeMethod(parent, aCmd.value(), player, methodArgs, level); + } else { + Command cmd = method.getAnnotation(Command.class); + + String[] newArgs = new String[args.length - level]; + System.arraycopy(args, level, newArgs, 0, args.length - level); + + final Set valueFlags = new HashSet<>(); + + char[] flags = cmd.flags().toCharArray(); + Set newFlags = new HashSet<>(); + for (int i = 0; i < flags.length; ++i) { + if (flags.length > i + 1 && flags[i + 1] == ':') { + valueFlags.add(flags[i]); + ++i; + } + newFlags.add(flags[i]); + } + + CommandContext context = new CommandContext(newArgs, valueFlags); + + if (context.argsLength() < cmd.min()) { + throw new CommandUsageException("Too few arguments.", getUsage(args, level, cmd)); + } + + if (cmd.max() != -1 && context.argsLength() > cmd.max()) { + throw new CommandUsageException("Too many arguments.", getUsage(args, level, cmd)); + } + + if (!cmd.anyFlags()) { + for (char flag : context.getFlags()) { + if (!newFlags.contains(flag)) { + throw new CommandUsageException("Unknown flag: " + flag, getUsage(args, level, cmd)); + } + } + } + + methodArgs[0] = context; + + Object instance = instances.get(method); + + invokeMethod(parent, args, player, method, instance, methodArgs, argsCount); + } + } + + protected void checkPermission(T player, Method method) throws CommandException { + if (!hasPermission(method, player)) { + throw new CommandPermissionsException(); + } + } + + public void invokeMethod(Method parent, String[] args, T player, Method method, Object instance, Object[] methodArgs, int level) throws CommandException { + try { + method.invoke(instance, methodArgs); + } catch (IllegalArgumentException | IllegalAccessException e) { + logger.error("Failed to execute command", e); + } catch (InvocationTargetException e) { + if (e.getCause() instanceof CommandException) { + throw (CommandException) e.getCause(); + } + + throw new WrappedCommandException(e.getCause()); + } + } + + /** + * Returns whether a player has access to a command. + * + * @param method the method + * @param player the player + * @return true if permission is granted + */ + protected boolean hasPermission(Method method, T player) { + CommandPermissions perms = method.getAnnotation(CommandPermissions.class); + if (perms == null) { + return true; + } + + for (String perm : perms.value()) { + if (hasPermission(player, perm)) { + return true; + } + } + + return false; + } + + /** + * Returns whether a player permission.. + * + * @param player the player + * @param permission the permission + * @return true if permission is granted + */ + public abstract boolean hasPermission(T player, String permission); + + /** + * Get the injector used to create new instances. This can be + * null, in which case only classes will be registered statically. + * + * @return an injector instance + */ + public Injector getInjector() { + return injector; + } + + /** + * Set the injector for creating new instances. + * + * @param injector injector or null + */ + public void setInjector(Injector injector) { + this.injector = injector; + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/SimpleInjector.java b/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/SimpleInjector.java index eb6097512..652c69a5d 100644 --- a/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/SimpleInjector.java +++ b/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/SimpleInjector.java @@ -19,14 +19,15 @@ package com.sk89q.minecraft.util.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.logging.Level; -import java.util.logging.Logger; public class SimpleInjector implements Injector { - private static final Logger log = Logger.getLogger(SimpleInjector.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(SimpleInjector.class); private Object[] args; private Class[] argClasses; @@ -45,7 +46,7 @@ public class SimpleInjector implements Injector { ctr.setAccessible(true); return ctr.newInstance(args); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { - log.log(Level.SEVERE, "Error initializing commands class " + clazz, e); + log.error("Error initializing commands class " + clazz, e); return null; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java b/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java index 452fbe70d..bc6ed024a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java @@ -95,6 +95,8 @@ import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.*; import com.sk89q.worldedit.world.weather.WeatherType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -108,12 +110,15 @@ import static com.sk89q.worldedit.regions.Regions.*; /** * An {@link Extent} that handles history, {@link BlockBag}s, change limits, * block re-ordering, and much more. Most operations in WorldEdit use this class. - *

+ * *

Most of the actual functionality is implemented with a number of other * {@link Extent}s that are chained together. For example, history is logged * using the {@link ChangeSetExtent}.

*/ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, SimpleWorld, AutoCloseable { + + private static final Logger log = LoggerFactory.getLogger(EditSession.class); + /** * Used by {@link EditSession#setBlock(BlockVector3, BlockStateHolder, Stage)} to * determine which {@link Extent}s should be bypassed. @@ -2901,8 +2906,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } return BlockTypes.get((int) typeVariable.getValue()).withPropertyId((int) dataVariable.getValue()).toBaseBlock(); - } catch (final Exception e) { - Fawe.debug("Failed to create shape: " + e); + } catch (Exception e) { + log.warn("Failed to create shape", e); return null; } } @@ -3299,8 +3304,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } return defaultBiomeType; - } catch (final Exception e) { - Fawe.debug("Failed to create shape: " + e); + } catch (Exception e) { + log.warn("Failed to create shape", e); return null; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java index a4cefa188..8b342d316 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java @@ -81,7 +81,6 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class LocalSession implements TextureHolder { - @Deprecated public transient static int MAX_HISTORY_SIZE = 15; // Non-session related fields @@ -1260,7 +1259,7 @@ public class LocalSession implements TextureHolder { String msg = e.getMessage(); if (msg != null && msg.length() > 256) msg = msg.substring(0, 256); this.failedCuiAttempts++; - WorldEdit.logger.warning("Error while reading CUI init message for player " + uuid + ": " + msg); + WorldEdit.logger.warn("Error while reading CUI init message: " + e.getMessage()); } } @@ -1442,4 +1441,4 @@ public class LocalSession implements TextureHolder { } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEdit.java b/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEdit.java index 3ec352d07..624aae973 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEdit.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEdit.java @@ -61,6 +61,8 @@ import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.registry.BundledBlockData; import com.sk89q.worldedit.world.registry.BundledItemData; import com.sk89q.worldedit.world.registry.LegacyMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.script.ScriptException; @@ -76,8 +78,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; import static com.sk89q.worldedit.event.platform.Interaction.HIT; import static com.sk89q.worldedit.event.platform.Interaction.OPEN; @@ -97,9 +97,9 @@ import static com.sk89q.worldedit.event.platform.Interaction.OPEN; */ public final class WorldEdit { - public static final Logger logger = Logger.getLogger(WorldEdit.class.getCanonicalName()); + public static final Logger logger = LoggerFactory.getLogger(WorldEdit.class); - private final static WorldEdit instance = new WorldEdit(); + private static final WorldEdit instance = new WorldEdit(); private static String version; private final EventBus eventBus = new EventBus(); @@ -670,13 +670,13 @@ public final class WorldEdit { } catch (ScriptException e) { player.printError("Failed to execute:"); player.printRaw(e.getMessage()); - logger.log(Level.WARNING, "Failed to execute script", e); + logger.warn("Failed to execute script", e); } catch (NumberFormatException | WorldEditException e) { throw e; } catch (Throwable e) { player.printError("Failed to execute (see console):"); player.printRaw(e.getClass().getCanonicalName()); - logger.log(Level.WARNING, "Failed to execute script", e); + logger.warn("Failed to execute script", e); } finally { for (EditSession editSession : scriptContext.getEditSessions()) { editSession.flushQueue(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ChunkCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ChunkCommands.java index 542aef756..0d5646ca1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ChunkCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ChunkCommands.java @@ -35,6 +35,7 @@ import com.sk89q.worldedit.math.MathUtils; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.storage.LegacyChunkStore; import com.sk89q.worldedit.world.storage.McRegionChunkStore; + import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; @@ -184,4 +185,5 @@ public class ChunkCommands { player.printError(BBC.getPrefix() + "Shell script type must be configured: 'bat' or 'bash' expected."); } } + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/NavigationCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/NavigationCommands.java index af2d20284..dac5d5371 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/NavigationCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/NavigationCommands.java @@ -19,6 +19,9 @@ package com.sk89q.worldedit.command; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION; + import com.boydti.fawe.FaweAPI; import com.boydti.fawe.config.BBC; import com.boydti.fawe.util.MathMan; @@ -35,10 +38,6 @@ import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.command.parametric.Optional; import com.sk89q.worldedit.world.World; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION; - /** * Commands for moving the player around. */ @@ -58,11 +57,11 @@ public class NavigationCommands { } @Command( - aliases = {"unstuck", "!"}, - usage = "", - desc = "Escape from being stuck inside a block", - min = 0, - max = 0 + aliases = { "unstuck", "!" }, + usage = "", + desc = "Escape from being stuck inside a block", + min = 0, + max = 0 ) @CommandPermissions("worldedit.navigation.unstuck") public void unstuck(Player player) throws WorldEditException { @@ -234,4 +233,4 @@ public class NavigationCommands { } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java index 2ce053148..6917c7949 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java @@ -48,15 +48,18 @@ import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.util.command.binding.Switch; import com.sk89q.worldedit.util.command.parametric.Optional; +import com.sk89q.worldedit.util.io.Closer; import com.sk89q.worldedit.util.io.file.FilenameException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; import java.io.*; import java.net.URI; import java.net.URISyntaxException; @@ -66,12 +69,10 @@ import java.nio.channels.ReadableByteChannel; import java.nio.file.Files; import java.util.*; import java.util.concurrent.atomic.LongAdder; -import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; - import static com.boydti.fawe.util.ReflectionUtils.as; +import static com.google.common.base.Preconditions.checkNotNull; /** * Commands that work with schematic files. @@ -79,7 +80,7 @@ import static com.boydti.fawe.util.ReflectionUtils.as; @Command(aliases = {"schematic", "schem", "/schematic", "/schem", "clipboard", "/clipboard"}, desc = "Commands that work with schematic files") public class SchematicCommands extends MethodCommands { - private static final Logger log = Logger.getLogger(SchematicCommands.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(SchematicCommands.class); /** * Create a new instance. @@ -266,7 +267,7 @@ public class SchematicCommands extends MethodCommands { player.printError("Unknown filename: " + filename); } catch (URISyntaxException | IOException e) { player.printError("File could not be read or it does not exist: " + e.getMessage()); - log.log(Level.WARNING, "Failed to load a saved clipboard", e); + log.warn("Failed to load a saved clipboard", e); } finally { if (in != null) { try { @@ -363,7 +364,7 @@ public class SchematicCommands extends MethodCommands { } catch (IOException e) { e.printStackTrace(); player.printError("Schematic could not written: " + e.getMessage()); - log.log(Level.WARNING, "Failed to write a saved clipboard", e); + log.warn("Failed to write a saved clipboard", e); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SnapshotCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SnapshotCommands.java index 0a433ac82..c5f019ddc 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SnapshotCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SnapshotCommands.java @@ -33,13 +33,13 @@ import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.world.snapshot.InvalidSnapshotException; import com.sk89q.worldedit.world.snapshot.Snapshot; import com.sk89q.worldedit.world.storage.MissingWorldException; + import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; -import java.util.logging.Logger; /** * Snapshot commands. @@ -47,7 +47,6 @@ import java.util.logging.Logger; @Command(aliases = {"snapshot", "snap"}, desc = "List, load and view information related to snapshots") public class SnapshotCommands { - private static final Logger logger = Logger.getLogger("Minecraft.WorldEdit"); private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); private final WorldEdit we; @@ -93,10 +92,10 @@ public class SnapshotCommands { File dir = config.snapshotRepo.getDirectory(); try { - logger.info("WorldEdit found no snapshots: looked in: " + WorldEdit.logger.info("WorldEdit found no snapshots: looked in: " + dir.getCanonicalPath()); } catch (IOException e) { - logger.info("WorldEdit found no snapshots: looked in " + WorldEdit.logger.info("WorldEdit found no snapshots: looked in " + "(NON-RESOLVABLE PATH - does it exist?): " + dir.getPath()); } @@ -107,7 +106,7 @@ public class SnapshotCommands { } @Command( - aliases = {"use"}, + aliases = { "use" }, usage = "", desc = "Choose a snapshot to use", min = 1, @@ -150,7 +149,7 @@ public class SnapshotCommands { } @Command( - aliases = {"sel"}, + aliases = { "sel" }, usage = "", desc = "Choose the snapshot based on the list id", min = 1, @@ -197,7 +196,7 @@ public class SnapshotCommands { } @Command( - aliases = {"before"}, + aliases = { "before" }, usage = "", desc = "Choose the nearest snapshot before a date", min = 1, @@ -236,7 +235,7 @@ public class SnapshotCommands { } @Command( - aliases = {"after"}, + aliases = { "after" }, usage = "", desc = "Choose the nearest snapshot after a date", min = 1, @@ -261,7 +260,8 @@ public class SnapshotCommands { Snapshot snapshot = config.snapshotRepo.getSnapshotAfter(date, player.getWorld().getName()); if (snapshot == null) { dateFormat.setTimeZone(session.getTimeZone()); - player.printError("Couldn't find a snapshot after " + dateFormat.format(date.getTime()) + "."); + player.printError("Couldn't find a snapshot after " + + dateFormat.format(date.getTime()) + "."); } else { session.setSnapshot(snapshot); BBC.SNAPSHOT_SET.send(player, snapshot.getName()); @@ -271,4 +271,5 @@ public class SnapshotCommands { } } } + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SnapshotUtilCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SnapshotUtilCommands.java index 53df86c15..5c86654f1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SnapshotUtilCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SnapshotUtilCommands.java @@ -37,18 +37,15 @@ import com.sk89q.worldedit.world.snapshot.Snapshot; import com.sk89q.worldedit.world.snapshot.SnapshotRestore; import com.sk89q.worldedit.world.storage.ChunkStore; import com.sk89q.worldedit.world.storage.MissingWorldException; + import java.io.File; import java.io.IOException; -import java.util.logging.Logger; - import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION; @Command(aliases = {}, desc = "[More Info](http://wiki.sk89q.com/wiki/WorldEdit/Snapshots)") public class SnapshotUtilCommands { - private static final Logger logger = Logger.getLogger("Minecraft.WorldEdit"); - private final WorldEdit we; public SnapshotUtilCommands(WorldEdit we) { @@ -56,7 +53,7 @@ public class SnapshotUtilCommands { } @Command( - aliases = {"restore", "/restore"}, + aliases = { "restore", "/restore" }, usage = "[snapshot]", desc = "Restore the selection from a snapshot", min = 0, @@ -99,10 +96,10 @@ public class SnapshotUtilCommands { File dir = config.snapshotRepo.getDirectory(); try { - logger.info("FAWE found no snapshots: looked in: " + WorldEdit.logger.info("WorldEdit found no snapshots: looked in: " + dir.getCanonicalPath()); } catch (IOException e) { - logger.info("FAWE found no snapshots: looked in " + WorldEdit.logger.info("WorldEdit found no snapshots: looked in " + "(NON-RESOLVABLE PATH - does it exist?): " + dir.getPath()); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java index 645d1f232..59ce8e448 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java @@ -81,20 +81,25 @@ public class SelectionCommand extends SimpleCommand { if (!testPermission(locals)) { throw new CommandPermissionsException(); } + Contextual operationFactory = delegate.call(args, locals); + Actor actor = locals.get(Actor.class); if (actor instanceof Player) { try { Player player = (Player) actor; LocalSession session = WorldEdit.getInstance().getSessionManager().get(player); Region selection = session.getSelection(player.getWorld()); + EditSession editSession = session.createEditSession(player); editSession.enableQueue(); locals.put(EditSession.class, editSession); session.tellVersion(player); + EditContext editContext = new EditContext(); editContext.setDestination(locals.get(EditSession.class)); editContext.setRegion(selection); + Operation operation = operationFactory.createFromContext(editContext); // Shortcut if (selection instanceof CuboidRegion && editSession.hasFastMode() && operation instanceof RegionVisitor) { @@ -191,4 +196,4 @@ public class SelectionCommand extends SimpleCommand { -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockDataCyler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockDataCyler.java index 004dc5bb2..bf6994c11 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockDataCyler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockDataCyler.java @@ -19,11 +19,6 @@ package com.sk89q.worldedit.command.tool; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - import com.google.common.collect.Lists; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalConfiguration; @@ -38,6 +33,11 @@ import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockState; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + /** * A mode that cycles the data values of supported blocks. */ @@ -47,7 +47,7 @@ public class BlockDataCyler implements DoubleActionBlockTool { public boolean canUse(Actor player) { return player.hasPermission("worldedit.tool.data-cycler"); } - + private Map> selectedProperties = new HashMap<>(); private boolean handleCycle(Platform server, LocalConfiguration config, @@ -104,7 +104,8 @@ public class BlockDataCyler implements DoubleActionBlockTool { player.print("Now cycling " + currentProperty.getName()); } } - return true; + + return true; } @Override diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java index 0a7b63e6c..14cee6fe2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java @@ -19,16 +19,20 @@ package com.sk89q.worldedit.command.tool; -import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extent.inventory.BlockBag; +import com.sk89q.worldedit.function.pattern.BlockPattern; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; /** * A mode that replaces one block. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/TreePlanter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/TreePlanter.java index 41353b0ad..e472f728b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/TreePlanter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/TreePlanter.java @@ -49,24 +49,24 @@ public class TreePlanter implements BlockTool { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked) { EditSession editSession = session.createEditSession(player); + try { + boolean successful = false; - try { - boolean successful = false; for (int i = 0; i < 10; i++) { if (treeType.generate(editSession, clicked.add(0, 1, 0).toBlockPoint())) { successful = true; break; } } - - if (!successful) { - player.printError("A tree can't go there."); + + if (!successful) { + player.printError("A tree can't go there."); + } + } catch (MaxChangedBlocksException e) { + player.printError("Max. blocks changed reached."); + } finally { + session.remember(editSession); } - } catch (MaxChangedBlocksException e) { - player.printError("Max. blocks changed reached."); - } finally { - session.remember(editSession); - } return true; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java index cfebeaf17..12a663ed3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java @@ -21,10 +21,10 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BlockTypes; public class CylinderBrush implements Brush { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowCylinderBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowCylinderBrush.java index 54247c107..dbf959e1b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowCylinderBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowCylinderBrush.java @@ -21,9 +21,9 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockTypes; public class HollowCylinderBrush implements Brush { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowSphereBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowSphereBrush.java index 9763a621a..0e89b3c16 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowSphereBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowSphereBrush.java @@ -21,9 +21,9 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockTypes; public class HollowSphereBrush implements Brush { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SphereBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SphereBrush.java index 7c38382de..d8028f2ae 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SphereBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SphereBrush.java @@ -21,9 +21,9 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockTypes; public class SphereBrush implements Brush { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java index 8ecbef23c..eeeb97f06 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java @@ -58,8 +58,13 @@ import com.sk89q.worldedit.util.command.fluent.CommandGraph; import com.sk89q.worldedit.util.command.fluent.DispatcherNode; import com.sk89q.worldedit.util.command.parametric.*; import com.sk89q.worldedit.util.eventbus.Subscribe; +import com.sk89q.worldedit.util.formatting.ColorCodeBuilder; +import com.sk89q.worldedit.util.formatting.component.CommandUsageBox; import com.sk89q.worldedit.util.logging.DynamicStreamHandler; import com.sk89q.worldedit.util.logging.LogFormat; +import com.sk89q.worldedit.world.World; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; @@ -69,10 +74,8 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; import java.util.logging.FileHandler; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; @@ -80,14 +83,15 @@ import static com.sk89q.worldedit.util.command.composition.LegacyCommandAdapter. /** * Handles the registration and invocation of commands. - *

+ * *

This class is primarily for internal usage.

*/ public final class CommandManager { public static final Pattern COMMAND_CLEAN_PATTERN = Pattern.compile("^[/]+"); - private static final Logger log = Logger.getLogger(CommandManager.class.getCanonicalName()); - private static final Logger commandLog = Logger.getLogger(CommandManager.class.getCanonicalName() + ".CommandLog"); + private static final Logger log = LoggerFactory.getLogger(CommandManager.class); + private static final java.util.logging.Logger commandLog = + java.util.logging.Logger.getLogger(CommandManager.class.getCanonicalName() + ".CommandLog"); private static final Pattern numberFormatExceptionPattern = Pattern.compile("^For input string: \"(.*)\"$"); private final WorldEdit worldEdit; @@ -124,6 +128,7 @@ public final class CommandManager { commandLog.addHandler(dynamicHandler); dynamicHandler.setFormatter(new LogFormat()); + // Set up the commands manager builder = new ParametricBuilder(); builder.setAuthorizer(new ActorAuthorizer()); builder.setDefaultCompleter(new UserCommandCompleter(platformManager)); @@ -297,7 +302,7 @@ public final class CommandManager { } public void register(Platform platform) { - log.log(Level.FINE, "Registering commands with " + platform.getClass().getCanonicalName()); + log.info("Registering commands with " + platform.getClass().getCanonicalName()); this.platform = null; try { @@ -318,12 +323,12 @@ public final class CommandManager { File file = new File(config.getWorkingDirectory(), path); commandLog.setLevel(Level.ALL); - log.log(Level.INFO, "Logging WorldEdit commands to " + file.getAbsolutePath()); + log.info("Logging WorldEdit commands to " + file.getAbsolutePath()); try { dynamicHandler.setHandler(new FileHandler(file.getAbsolutePath(), true)); } catch (IOException e) { - log.log(Level.WARNING, "Could not use command log file " + path + ": " + e.getMessage()); + log.warn("Could not use command log file " + path + ": " + e.getMessage()); } } @@ -418,7 +423,8 @@ public final class CommandManager { return handleCommandTask(task, locals, null, null, null, null); } - private Object handleCommandTask(ThrowableSupplier task, CommandLocals locals, @Nullable Actor actor, @Nullable LocalSession session, @Nullable Set failedPermissions, @Nullable FawePlayer fp) { + private Object handleCommandTask(ThrowableSupplier task, CommandLocals locals, @Nullable + Actor actor, @Nullable LocalSession session, @Nullable Set failedPermissions, @Nullable FawePlayer fp) { Request.reset(); if (actor == null) actor = locals.get(Actor.class); if (session == null) session = locals.get(LocalSession.class); @@ -474,8 +480,8 @@ public final class CommandManager { if (message != null) { actor.printError(BBC.getPrefix() + e.getMessage()); } else { - actor.printError(BBC.getPrefix() + "An unknown FAWE error has occurred! Please see console."); - log.log(Level.SEVERE, "An unknown FAWE error occurred", e); + actor.printError("An unknown error has occurred! Please see console."); + log.error("An unknown error occurred", e); } } catch (Throwable e) { Exception faweException = FaweException.get(e); @@ -485,7 +491,7 @@ public final class CommandManager { } else { actor.printError(BBC.getPrefix() + "There was an error handling a FAWE command: [See console]"); actor.printRaw(e.getClass().getName() + ": " + e.getMessage()); - log.log(Level.SEVERE, "An unexpected error occurred while handling a FAWE command", e); + log.error("An unexpected error occurred while handling a FAWE command", e); } } finally { final EditSession editSession = locals.get(EditSession.class); @@ -552,7 +558,7 @@ public final class CommandManager { return dispatcher; } - public static Logger getLogger() { + public static java.util.logging.Logger getLogger() { return commandLog; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformManager.java index 38f4654cd..94caacaca 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformManager.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformManager.java @@ -49,25 +49,25 @@ import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.world.World; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; import static com.google.common.base.Preconditions.checkNotNull; /** * Manages registered {@link Platform}s for WorldEdit. Platforms are * implementations of WorldEdit. - *

+ * *

This class is thread-safe.

*/ public class PlatformManager { - private static final Logger logger = Logger.getLogger(PlatformManager.class.getCanonicalName()); + private static final Logger logger = LoggerFactory.getLogger(PlatformManager.class); private final WorldEdit worldEdit; private final CommandManager commandManager; @@ -99,7 +99,7 @@ public class PlatformManager { public synchronized void register(Platform platform) { checkNotNull(platform); - logger.log(Level.FINE, "Got request to register " + platform.getClass() + " with WorldEdit [" + super.toString() + "]"); + logger.info("Got request to register " + platform.getClass() + " with WorldEdit [" + super.toString() + "]"); // Just add the platform to the list of platforms: we'll pick favorites // once all the platforms have been loaded @@ -108,9 +108,9 @@ public class PlatformManager { // Make sure that versions are in sync if (firstSeenVersion != null) { if (!firstSeenVersion.equals(platform.getVersion())) { - logger.log(Level.WARNING, "Multiple ports of WorldEdit are installed but they report different versions ({0} and {1}). " + + logger.warn("Multiple ports of WorldEdit are installed but they report different versions ({0} and {1}). " + "If these two versions are truly different, then you may run into unexpected crashes and errors.", - new Object[]{firstSeenVersion, platform.getVersion()}); + new Object[]{ firstSeenVersion, platform.getVersion() }); } } else { firstSeenVersion = platform.getVersion(); @@ -119,7 +119,7 @@ public class PlatformManager { /** * Unregister a platform from WorldEdit. - *

+ * *

If the platform has been chosen for any capabilities, then a new * platform will be found.

* @@ -131,7 +131,7 @@ public class PlatformManager { boolean removed = platforms.remove(platform); if (removed) { - logger.log(Level.FINE, "Unregistering " + platform.getClass().getCanonicalName() + " from WorldEdit"); + logger.info("Unregistering " + platform.getClass().getCanonicalName() + " from WorldEdit"); boolean choosePreferred = false; @@ -222,7 +222,7 @@ public class PlatformManager { /** * Get a list of loaded platforms. - *

+ * *

The returned list is a copy of the original and is mutable.

* * @return a list of platforms @@ -497,7 +497,7 @@ public class PlatformManager { return; } - final Tool tool = session.getTool(player); + Tool tool = session.getTool(player); if (tool != null && tool instanceof DoubleActionTraceTool) { if (tool.canUse(player)) { FawePlayer fp = FawePlayer.wrap(player); @@ -532,7 +532,7 @@ public class PlatformManager { return; } - final Tool tool = session.getTool(player); + Tool tool = session.getTool(player); if (tool != null && tool instanceof TraceTool) { if (tool.canUse(player)) { FawePlayer fp = FawePlayer.wrap(player); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormats.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormats.java index e2598b3f8..86961910a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormats.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormats.java @@ -74,7 +74,7 @@ public class ClipboardFormats { ClipboardFormat old = aliasMap.put(lowKey, format); if (old != null) { aliasMap.put(lowKey, old); - WorldEdit.logger.warning(format.getClass().getName() + " cannot override existing alias '" + lowKey + "' used by " + old.getClass().getName()); + WorldEdit.logger.warn(format.getClass().getName() + " cannot override existing alias '" + lowKey + "' used by " + old.getClass().getName()); } } for (String ext : format.getFileExtensions()) { @@ -311,4 +311,4 @@ public class ClipboardFormats { throw new RuntimeException(e); } } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java index 94b67a3db..056bb69ac 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java @@ -46,6 +46,8 @@ import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityTypes; import com.sk89q.worldedit.world.registry.LegacyMapper; import com.sk89q.worldedit.world.storage.NBTConversions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; @@ -53,7 +55,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; -import java.util.logging.Logger; /** * Reads schematic files that are compatible with MCEdit and other editors. @@ -67,7 +68,7 @@ public class MCEditSchematicReader extends NBTSchematicReader { // TODO Add a handler for skulls, flower pots, note blocks, etc. } - private static final Logger log = Logger.getLogger(MCEditSchematicReader.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(MCEditSchematicReader.class); private final NBTInputStream inputStream; /** @@ -231,15 +232,15 @@ public class MCEditSchematicReader extends NBTSchematicReader { clipboard.setBlock(region.getMinimumPoint().add(pt), state); } } else { - log.warning("Unknown block when pasting schematic: " + blocks[index] + ":" + blockData[index] + ". Please report this issue."); + log.warn("Unknown block when pasting schematic: " + blocks[index] + ":" + blockData[index] + ". Please report this issue."); } } catch (WorldEditException e) { switch (failedBlockSets) { case 0: - log.log(Level.WARNING, "Failed to set block on a Clipboard", e); + log.warn("Failed to set block on a Clipboard", e); break; case 1: - log.log(Level.WARNING, "Failed to set block on a Clipboard (again) -- no more messages will be logged", e); + log.warn("Failed to set block on a Clipboard (again) -- no more messages will be logged", e); break; default: } @@ -269,7 +270,7 @@ public class MCEditSchematicReader extends NBTSchematicReader { BaseEntity state = new BaseEntity(entityType, compound); clipboard.createEntity(location, state); } else { - log.warning("Unknown entity when pasting schematic: " + id.toLowerCase()); + log.warn("Unknown entity when pasting schematic: " + id.toLowerCase()); } } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SchematicReader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SchematicReader.java index 489ce802f..e4ac175f9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SchematicReader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SchematicReader.java @@ -26,11 +26,13 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.UUID; -import java.util.logging.Logger; import javax.annotation.Nullable; @@ -41,7 +43,6 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class SchematicReader implements ClipboardReader { - private static final Logger log = Logger.getLogger(SchematicReader.class.getCanonicalName()); private NBTInputStream inputStream; private InputStream rootStream; @@ -109,4 +110,4 @@ public class SchematicReader implements ClipboardReader { public void close() throws IOException { inputStream.close(); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicReader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicReader.java index a7661ed9b..915eb0f9a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicReader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicReader.java @@ -60,6 +60,8 @@ import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityTypes; import net.jpountz.lz4.LZ4BlockInputStream; import net.jpountz.lz4.LZ4BlockOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.DataInputStream; import java.io.IOException; @@ -70,7 +72,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.BiConsumer; -import java.util.logging.Logger; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkNotNull; @@ -86,7 +87,7 @@ public class SpongeSchematicReader extends NBTSchematicReader { // If NBT Compat handlers are needed - add them here. } - private static final Logger log = Logger.getLogger(SpongeSchematicReader.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(SpongeSchematicReader.class); private final NBTInputStream inputStream; /** @@ -257,4 +258,4 @@ public class SpongeSchematicReader extends NBTSchematicReader { public void close() throws IOException { inputStream.close(); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandLoggingHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandLoggingHandler.java index 256f891ec..1fb2dd55d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandLoggingHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandLoggingHandler.java @@ -40,6 +40,8 @@ import java.lang.reflect.Method; import java.util.logging.Handler; import java.util.logging.Logger; +import static com.google.common.base.Preconditions.checkNotNull; + /** * Logs called commands to a logger. */ diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/ReparametrisingInterpolation.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/ReparametrisingInterpolation.java index 29a3ee5ee..23680f2bc 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/ReparametrisingInterpolation.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/ReparametrisingInterpolation.java @@ -21,14 +21,15 @@ package com.sk89q.worldedit.math.interpolation; -import static com.google.common.base.Preconditions.checkNotNull; - import com.sk89q.worldedit.math.Vector3; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; -import java.util.logging.Logger; + +import static com.google.common.base.Preconditions.checkNotNull; /** * Reparametrises another interpolation function by arc length. @@ -38,7 +39,7 @@ import java.util.logging.Logger; */ public class ReparametrisingInterpolation implements Interpolation { - private static final Logger log = Logger.getLogger(ReparametrisingInterpolation.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(ReparametrisingInterpolation.class); private final Interpolation baseInterpolation; private double totalArcLength; @@ -102,7 +103,7 @@ public class ReparametrisingInterpolation implements Interpolation { Entry ceilingEntry = cache.ceilingEntry(arc); if (ceilingEntry == null) { - log.warning("Error in arcToParameter: no ceiling entry for " + arc + " found!"); + log.warn("Error in arcToParameter: no ceiling entry for " + arc + " found!"); return 0; } final double rightArc = ceilingEntry.getKey(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/session/SessionManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/session/SessionManager.java index 5339db01d..2cd2fd352 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/session/SessionManager.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/session/SessionManager.java @@ -27,13 +27,17 @@ import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.ConfigurationLoadEvent; +import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.session.storage.JsonFileSessionStore; import com.sk89q.worldedit.session.storage.SessionStore; import com.sk89q.worldedit.session.storage.VoidStore; import com.sk89q.worldedit.util.concurrency.EvenMoreExecutors; import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.world.gamemode.GameModes; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.lang.ref.Reference; @@ -41,29 +45,26 @@ import java.lang.ref.SoftReference; import java.util.Iterator; import java.util.Map; import java.util.Timer; +import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; /** * Session manager for WorldEdit. - *

+ * *

Get a reference to one from {@link WorldEdit}.

- *

+ * *

While this class is thread-safe, the returned session may not be.

*/ public class SessionManager { - @Deprecated public static int EXPIRATION_GRACE = 600000; private static final ListeningExecutorService executorService = MoreExecutors.listeningDecorator(EvenMoreExecutors.newBoundedCachedThreadPool(0, 1, 5)); - private static final Logger log = Logger.getLogger(SessionManager.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(SessionManager.class); private final Timer timer = new Timer(); private final WorldEdit worldEdit; private final Map sessions = new ConcurrentHashMap<>(8, 0.9f, 1); @@ -179,8 +180,8 @@ public class SessionManager { try { session = store.load(getKey(sessionKey)); session.postLoad(); - } catch (Throwable e) { - log.log(Level.WARNING, "Failed to load saved session", e); + } catch (IOException e) { + log.warn("Failed to load saved session", e); session = new LocalSession(); } @@ -239,7 +240,7 @@ public class SessionManager { } } } catch (IOException e) { - log.log(Level.WARNING, "Failed to write session for UUID " + getKey(key), e); + log.warn("Failed to write session for UUID " + getKey(key), e); } } } @@ -328,4 +329,4 @@ public class SessionManager { -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/session/storage/JsonFileSessionStore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/session/storage/JsonFileSessionStore.java index d7b2a9893..ad8e422bf 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/session/storage/JsonFileSessionStore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/session/storage/JsonFileSessionStore.java @@ -19,8 +19,6 @@ package com.sk89q.worldedit.session.storage; -import static com.google.common.base.Preconditions.checkNotNull; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonIOException; @@ -28,6 +26,8 @@ import com.google.gson.JsonParseException; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.util.gson.GsonUtil; import com.sk89q.worldedit.util.io.Closer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -37,8 +37,8 @@ import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; + +import static com.google.common.base.Preconditions.checkNotNull; /** * Stores sessions as JSON files in a directory. @@ -47,7 +47,7 @@ import java.util.logging.Logger; */ public class JsonFileSessionStore implements SessionStore { - private static final Logger log = Logger.getLogger(JsonFileSessionStore.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(JsonFileSessionStore.class); private final Gson gson; private final File dir; @@ -61,7 +61,7 @@ public class JsonFileSessionStore implements SessionStore { if (!dir.isDirectory()) { if (!dir.mkdirs()) { - log.log(Level.WARNING, "Failed to create directory '" + dir.getPath() + "' for sessions"); + log.warn("Failed to create directory '" + dir.getPath() + "' for sessions"); } } @@ -111,12 +111,12 @@ public class JsonFileSessionStore implements SessionStore { if (finalFile.exists()) { if (!finalFile.delete()) { - log.log(Level.WARNING, "Failed to delete " + finalFile.getPath() + " so the .tmp file can replace it"); + log.warn("Failed to delete " + finalFile.getPath() + " so the .tmp file can replace it"); } } if (!tempFile.renameTo(finalFile)) { - log.log(Level.WARNING, "Failed to rename temporary session file to " + finalFile.getPath()); + log.warn("Failed to rename temporary session file to " + finalFile.getPath()); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/PropertiesConfiguration.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/PropertiesConfiguration.java index 18a8cc806..329dff154 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/PropertiesConfiguration.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/PropertiesConfiguration.java @@ -1,283 +1,284 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -// $Id$ - -package com.sk89q.worldedit.util; - -import com.google.common.collect.Lists; -import com.sk89q.util.StringUtil; -import com.sk89q.worldedit.LocalConfiguration; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.world.block.BlockTypes; -import com.sk89q.worldedit.world.item.ItemTypes; -import com.sk89q.worldedit.world.registry.LegacyMapper; -import com.sk89q.worldedit.world.snapshot.SnapshotRepository; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; - -/** - * Simple LocalConfiguration that loads settings using - * {@code java.util.Properties}. - */ -public class PropertiesConfiguration extends LocalConfiguration { - - private static final Logger log = Logger.getLogger(PropertiesConfiguration.class.getCanonicalName()); - - protected Properties properties; - protected File path; - - /** - * Construct the object. The configuration isn't loaded yet. - * - * @param path the path tot he configuration - */ - public PropertiesConfiguration(File path) { - this.path = path; - - properties = new Properties(); - } - - @Override - public void load() { - try (InputStream stream = new FileInputStream(path)) { - properties.load(stream); - } catch (FileNotFoundException ignored) { - } catch (IOException e) { - log.log(Level.WARNING, "Failed to read configuration", e); - } - - loadExtra(); - - profile = getBool("profile", profile); - - disallowedBlocks = - new HashSet<>(getStringSet("limits.disallowed-blocks", getDefaultDisallowedBlocks())); - allowedDataCycleBlocks = - new HashSet<>(getStringSet("limits.allowed-data-cycle-blocks", null)); - defaultChangeLimit = getInt("default-max-changed-blocks", defaultChangeLimit); - maxChangeLimit = getInt("max-changed-blocks", maxChangeLimit); - defaultMaxPolygonalPoints = getInt("default-max-polygon-points", defaultMaxPolygonalPoints); - maxPolygonalPoints = getInt("max-polygon-points", maxPolygonalPoints); - defaultMaxPolyhedronPoints = getInt("default-max-polyhedron-points", defaultMaxPolyhedronPoints); - maxPolyhedronPoints = getInt("max-polyhedron-points", maxPolyhedronPoints); - shellSaveType = getString("shell-save-type", shellSaveType); - maxRadius = getInt("max-radius", maxRadius); - maxSuperPickaxeSize = getInt("max-super-pickaxe-size", maxSuperPickaxeSize); - maxBrushRadius = getInt("max-brush-radius", maxBrushRadius); - logCommands = getBool("log-commands", logCommands); - logFile = getString("log-file", logFile); - logFormat = getString("log-format", logFormat); - registerHelp = getBool("register-help", registerHelp); - wandItem = getString("wand-item", wandItem); - try { - wandItem = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(wandItem)).getId(); - } catch (Throwable e) {} - superPickaxeDrop = getBool("super-pickaxe-drop-items", superPickaxeDrop); - superPickaxeManyDrop = getBool("super-pickaxe-many-drop-items", superPickaxeManyDrop); - noDoubleSlash = getBool("no-double-slash", noDoubleSlash); - useInventory = getBool("use-inventory", useInventory); - useInventoryOverride = getBool("use-inventory-override", useInventoryOverride); - useInventoryCreativeOverride = getBool("use-inventory-creative-override", useInventoryCreativeOverride); - navigationWand = getString("nav-wand-item", navigationWand); - try { - navigationWand = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(navigationWand)).getId(); - } catch (Throwable e) {} - navigationWandMaxDistance = getInt("nav-wand-distance", navigationWandMaxDistance); - navigationUseGlass = getBool("nav-use-glass", navigationUseGlass); - scriptTimeout = getInt("scripting-timeout", scriptTimeout); - saveDir = getString("schematic-save-dir", saveDir); - scriptsDir = getString("craftscript-dir", scriptsDir); - butcherDefaultRadius = getInt("butcher-default-radius", butcherDefaultRadius); - butcherMaxRadius = getInt("butcher-max-radius", butcherMaxRadius); - allowSymlinks = getBool("allow-symbolic-links", allowSymlinks); - - LocalSession.MAX_HISTORY_SIZE = Math.max(15, getInt("history-size", 15)); - - String snapshotsDir = getString("snapshots-dir", ""); - if (!snapshotsDir.isEmpty()) { - snapshotRepo = new SnapshotRepository(snapshotsDir); - } - - path.getParentFile().mkdirs(); - try (OutputStream output = new FileOutputStream(path)) { - properties.store(output, "Don't put comments; they get removed"); - } catch (IOException e) { - log.log(Level.WARNING, "Failed to write configuration", e); - } - } - - /** - * Called to load extra configuration. - */ - protected void loadExtra() { - } - - /** - * Get a string value. - * - * @param key the key - * @param def the default value - * @return the value - */ - protected String getString(String key, String def) { - if (def == null) { - def = ""; - } - String val = properties.getProperty(key); - if (val == null) { - properties.setProperty(key, def); - return def; - } else { - return val; - } - } - - /** - * Get a boolean value. - * - * @param key the key - * @param def the default value - * @return the value - */ - protected boolean getBool(String key, boolean def) { - String val = properties.getProperty(key); - if (val == null) { - properties.setProperty(key, def ? "true" : "false"); - return def; - } else { - return val.equalsIgnoreCase("true") - || val.equals("1"); - } - } - - /** - * Get an integer value. - * - * @param key the key - * @param def the default value - * @return the value - */ - protected int getInt(String key, int def) { - String val = properties.getProperty(key); - if (val == null) { - properties.setProperty(key, String.valueOf(def)); - return def; - } else { - try { - return Integer.parseInt(val); - } catch (NumberFormatException e) { - properties.setProperty(key, String.valueOf(def)); - return def; - } - } - } - - /** - * Get a double value. - * - * @param key the key - * @param def the default value - * @return the value - */ - protected double getDouble(String key, double def) { - String val = properties.getProperty(key); - if (val == null) { - properties.setProperty(key, String.valueOf(def)); - return def; - } else { - try { - return Double.parseDouble(val); - } catch (NumberFormatException e) { - properties.setProperty(key, String.valueOf(def)); - return def; - } - } - } - - /** - * Get a double value. - * - * @param key the key - * @param def the default value - * @return the value - */ - protected Set getIntSet(String key, int[] def) { - String val = properties.getProperty(key); - if (val == null) { - properties.setProperty(key, StringUtil.joinString(def, ",", 0)); - Set set = new HashSet<>(); - for (int i : def) { - set.add(i); - } - return set; - } else { - Set set = new HashSet<>(); - String[] parts = val.split(","); - for (String part : parts) { - try { - int v = Integer.parseInt(part.trim()); - set.add(v); - } catch (NumberFormatException ignored) { - } - } - return set; - } - } - - /** - * Get a String set. - * - * @param key the key - * @param def the default value - * @return the value - */ - protected Set getStringSet(String key, String[] def) { - String val = properties.getProperty(key); - if (val == null) { - properties.setProperty(key, StringUtil.joinString(def, ",", 0)); - return new HashSet<>(Arrays.asList(def)); - } else { - Set set = new HashSet<>(); - String[] parts = val.split(","); - for (String part : parts) { - try { - String v = part.trim(); - set.add(v); - } catch (NumberFormatException ignored) { - } - } - return set; - } - } - -} \ No newline at end of file +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +// $Id$ + +package com.sk89q.worldedit.util; + +import com.sk89q.util.StringUtil; +import com.sk89q.worldedit.LocalConfiguration; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.util.report.Unreported; +import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.item.ItemTypes; +import com.sk89q.worldedit.world.registry.LegacyMapper; +import com.sk89q.worldedit.world.snapshot.SnapshotRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +/** + * Simple LocalConfiguration that loads settings using + * {@code java.util.Properties}. + */ +public class PropertiesConfiguration extends LocalConfiguration { + + @Unreported private static final Logger log = LoggerFactory.getLogger(PropertiesConfiguration.class); + + @Unreported protected Properties properties; + @Unreported protected File path; + + /** + * Construct the object. The configuration isn't loaded yet. + * + * @param path the path tot he configuration + */ + public PropertiesConfiguration(File path) { + this.path = path; + + properties = new Properties(); + } + + @Override + public void load() { + try (InputStream stream = new FileInputStream(path)) { + properties.load(stream); + } catch (FileNotFoundException ignored) { + } catch (IOException e) { + log.warn("Failed to read configuration", e); + } + + loadExtra(); + + profile = getBool("profile", profile); + + disallowedBlocks = + new HashSet<>(getStringSet("limits.disallowed-blocks", getDefaultDisallowedBlocks())); + allowedDataCycleBlocks = + new HashSet<>(getStringSet("limits.allowed-data-cycle-blocks", null)); + defaultChangeLimit = getInt("default-max-changed-blocks", defaultChangeLimit); + maxChangeLimit = getInt("max-changed-blocks", maxChangeLimit); + defaultMaxPolygonalPoints = getInt("default-max-polygon-points", defaultMaxPolygonalPoints); + maxPolygonalPoints = getInt("max-polygon-points", maxPolygonalPoints); + defaultMaxPolyhedronPoints = getInt("default-max-polyhedron-points", defaultMaxPolyhedronPoints); + maxPolyhedronPoints = getInt("max-polyhedron-points", maxPolyhedronPoints); + shellSaveType = getString("shell-save-type", shellSaveType); + maxRadius = getInt("max-radius", maxRadius); + maxSuperPickaxeSize = getInt("max-super-pickaxe-size", maxSuperPickaxeSize); + maxBrushRadius = getInt("max-brush-radius", maxBrushRadius); + logCommands = getBool("log-commands", logCommands); + logFile = getString("log-file", logFile); + logFormat = getString("log-format", logFormat); + registerHelp = getBool("register-help", registerHelp); + wandItem = getString("wand-item", wandItem); + try { + wandItem = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(wandItem)).getId(); + } catch (Throwable e) { + } + superPickaxeDrop = getBool("super-pickaxe-drop-items", superPickaxeDrop); + superPickaxeManyDrop = getBool("super-pickaxe-many-drop-items", superPickaxeManyDrop); + noDoubleSlash = getBool("no-double-slash", noDoubleSlash); + useInventory = getBool("use-inventory", useInventory); + useInventoryOverride = getBool("use-inventory-override", useInventoryOverride); + useInventoryCreativeOverride = getBool("use-inventory-creative-override", useInventoryCreativeOverride); + navigationWand = getString("nav-wand-item", navigationWand); + try { + navigationWand = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(navigationWand)).getId(); + } catch (Throwable e) { + } + navigationWandMaxDistance = getInt("nav-wand-distance", navigationWandMaxDistance); + navigationUseGlass = getBool("nav-use-glass", navigationUseGlass); + scriptTimeout = getInt("scripting-timeout", scriptTimeout); + saveDir = getString("schematic-save-dir", saveDir); + scriptsDir = getString("craftscript-dir", scriptsDir); + butcherDefaultRadius = getInt("butcher-default-radius", butcherDefaultRadius); + butcherMaxRadius = getInt("butcher-max-radius", butcherMaxRadius); + allowSymlinks = getBool("allow-symbolic-links", allowSymlinks); + + LocalSession.MAX_HISTORY_SIZE = Math.max(15, getInt("history-size", 15)); + + String snapshotsDir = getString("snapshots-dir", ""); + if (!snapshotsDir.isEmpty()) { + snapshotRepo = new SnapshotRepository(snapshotsDir); + } + + path.getParentFile().mkdirs(); + try (OutputStream output = new FileOutputStream(path)) { + properties.store(output, "Don't put comments; they get removed"); + } catch (IOException e) { + log.warn("Failed to write configuration", e); + } + } + + /** + * Called to load extra configuration. + */ + protected void loadExtra() { + } + + /** + * Get a string value. + * + * @param key the key + * @param def the default value + * @return the value + */ + protected String getString(String key, String def) { + if (def == null) { + def = ""; + } + String val = properties.getProperty(key); + if (val == null) { + properties.setProperty(key, def); + return def; + } else { + return val; + } + } + + /** + * Get a boolean value. + * + * @param key the key + * @param def the default value + * @return the value + */ + protected boolean getBool(String key, boolean def) { + String val = properties.getProperty(key); + if (val == null) { + properties.setProperty(key, def ? "true" : "false"); + return def; + } else { + return val.equalsIgnoreCase("true") + || val.equals("1"); + } + } + + /** + * Get an integer value. + * + * @param key the key + * @param def the default value + * @return the value + */ + protected int getInt(String key, int def) { + String val = properties.getProperty(key); + if (val == null) { + properties.setProperty(key, String.valueOf(def)); + return def; + } else { + try { + return Integer.parseInt(val); + } catch (NumberFormatException e) { + properties.setProperty(key, String.valueOf(def)); + return def; + } + } + } + + /** + * Get a double value. + * + * @param key the key + * @param def the default value + * @return the value + */ + protected double getDouble(String key, double def) { + String val = properties.getProperty(key); + if (val == null) { + properties.setProperty(key, String.valueOf(def)); + return def; + } else { + try { + return Double.parseDouble(val); + } catch (NumberFormatException e) { + properties.setProperty(key, String.valueOf(def)); + return def; + } + } + } + + /** + * Get a double value. + * + * @param key the key + * @param def the default value + * @return the value + */ + protected Set getIntSet(String key, int[] def) { + String val = properties.getProperty(key); + if (val == null) { + properties.setProperty(key, StringUtil.joinString(def, ",", 0)); + Set set = new HashSet<>(); + for (int i : def) { + set.add(i); + } + return set; + } else { + Set set = new HashSet<>(); + String[] parts = val.split(","); + for (String part : parts) { + try { + int v = Integer.parseInt(part.trim()); + set.add(v); + } catch (NumberFormatException ignored) { + } + } + return set; + } + } + + /** + * Get a String set. + * + * @param key the key + * @param def the default value + * @return the value + */ + protected Set getStringSet(String key, String[] def) { + String val = properties.getProperty(key); + if (val == null) { + properties.setProperty(key, StringUtil.joinString(def, ",", 0)); + return new HashSet<>(Arrays.asList(def)); + } else { + Set set = new HashSet<>(); + String[] parts = val.split(","); + for (String part : parts) { + try { + String v = part.trim(); + set.add(v); + } catch (NumberFormatException ignored) { + } + } + return set; + } + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/YAMLConfiguration.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/YAMLConfiguration.java index fba4fc67e..0719eeca0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/YAMLConfiguration.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/YAMLConfiguration.java @@ -26,11 +26,10 @@ import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.session.SessionManager; import com.sk89q.worldedit.util.report.Unreported; import com.sk89q.worldedit.world.snapshot.SnapshotRepository; +import org.slf4j.Logger; import java.io.IOException; import java.util.HashSet; -import java.util.logging.Level; -import java.util.logging.Logger; /** * A less simple implementation of {@link LocalConfiguration} @@ -51,7 +50,7 @@ public class YAMLConfiguration extends LocalConfiguration { try { config.load(); } catch (IOException e) { - logger.log(Level.WARNING, "Error loading WorldEdit configuration", e); + logger.warn("Error loading WorldEdit configuration", e); } profile = config.getBoolean("debug", profile); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/EventBus.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/EventBus.java index d8cbe8b20..d97c090ea 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/EventBus.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/EventBus.java @@ -19,13 +19,13 @@ package com.sk89q.worldedit.util.eventbus; -import static com.google.common.base.Preconditions.checkNotNull; - import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; import com.google.common.eventbus.DeadEvent; import com.sk89q.worldedit.internal.annotation.RequiresNewerGuava; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -36,8 +36,8 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; + +import static com.google.common.base.Preconditions.checkNotNull; /** * Dispatches events to listeners, and provides ways for listeners to register @@ -53,7 +53,7 @@ import java.util.logging.Logger; */ public class EventBus { - private final Logger logger = Logger.getLogger(EventBus.class.getCanonicalName()); + private final Logger logger = LoggerFactory.getLogger(EventBus.class); private final SetMultimap, EventHandler> handlersByType = Multimaps.newSetMultimap(new HashMap<>(), this::newHandlerSet); @@ -186,8 +186,7 @@ public class EventBus { try { handler.handleEvent(event); } catch (InvocationTargetException e) { - logger.log(Level.SEVERE, - "Could not dispatch event: " + event + " to handler " + handler, e); + logger.error("Could not dispatch event: " + event + " to handler " + handler, e); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/Closer.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/Closer.java index 26ef6a0f9..1b7aceda3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/Closer.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/Closer.java @@ -19,23 +19,23 @@ package com.sk89q.worldedit.util.io; -import static com.google.common.base.Preconditions.checkNotNull; - import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayDeque; import java.util.Deque; -import java.util.logging.Level; -import java.util.logging.Logger; import java.util.zip.ZipFile; +import static com.google.common.base.Preconditions.checkNotNull; + public final class Closer implements Closeable { - private static final Logger logger = Logger.getLogger(Closer.class.getCanonicalName()); + private static final Logger logger = LoggerFactory.getLogger(Closer.class); /** * The suppressor implementation to use for the current Java version. @@ -218,7 +218,7 @@ public final class Closer implements Closeable { @Override public void suppress(Object closeable, Throwable thrown, Throwable suppressed) { // log to the same place as Closeables - logger.log(Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); + logger.warn("Suppressing exception thrown when closing " + closeable, suppressed); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/logging/WorldEditPrefixHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/logging/WorldEditPrefixHandler.java index f2c8a0754..6922987c4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/logging/WorldEditPrefixHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/logging/WorldEditPrefixHandler.java @@ -53,7 +53,8 @@ public final class WorldEditPrefixHandler extends Handler { * @param name the logger name */ public static void register(String name) { - Logger.getLogger(name).addHandler(new WorldEditPrefixHandler()); + //todo fix this + //Logger.getLogger(name).addHandler(new WorldEditPrefixHandler()); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/ActorCallbackPaste.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/ActorCallbackPaste.java index e87e440bf..b906a5813 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/ActorCallbackPaste.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/ActorCallbackPaste.java @@ -26,14 +26,14 @@ import com.sk89q.worldedit.command.util.AsyncCommandHelper; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.util.command.parametric.ExceptionConverter; import com.sk89q.worldedit.util.task.Supervisor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; public class ActorCallbackPaste { - private static final Logger LOGGER = Logger.getLogger(ActorCallbackPaste.class.getSimpleName()); + private static final Logger LOGGER = LoggerFactory.getLogger(ActorCallbackPaste.class); private ActorCallbackPaste() { } @@ -62,7 +62,7 @@ public static void pastebin(Supervisor supervisor, final Actor sender, String co @Override public void onFailure(Throwable throwable) { - LOGGER.log(Level.WARNING, "Failed to submit pastebin", throwable); + LOGGER.warn("Failed to submit pastebin", throwable); sender.printError("Failed to submit to a pastebin. Please see console for the error."); } }); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ShallowObjectReport.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ShallowObjectReport.java index bb4abb1f3..18085bc0b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ShallowObjectReport.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ShallowObjectReport.java @@ -19,16 +19,17 @@ package com.sk89q.worldedit.util.report; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.util.logging.Level; -import java.util.logging.Logger; import static com.google.common.base.Preconditions.checkNotNull; public class ShallowObjectReport extends DataReport { - private static final Logger log = Logger.getLogger(ShallowObjectReport.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(ShallowObjectReport.class); public ShallowObjectReport(String title, Object object) { super(title); @@ -52,7 +53,7 @@ public class ShallowObjectReport extends DataReport { Object value = field.get(object); append(field.getName(), String.valueOf(value)); } catch (IllegalAccessException e) { - log.log(Level.WARNING, "Failed to get value of '" + field.getName() + "' on " + type); + log.warn("Failed to get value of '" + field.getName() + "' on " + type); } } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk.java index 2710fddd0..8dbb5e737 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk.java @@ -260,7 +260,7 @@ public class AnvilChunk implements Chunk { BlockState state = LegacyMapper.getInstance().getBlockFromLegacy(id, data); if (state == null) { - WorldEdit.logger.warning("Unknown legacy block " + id + ":" + data + " found when loading legacy anvil chunk."); + WorldEdit.logger.warn("Unknown legacy block " + id + ":" + data + " found when loading legacy anvil chunk."); return BlockTypes.AIR.getDefaultState().toBaseBlock(); } if (state.getMaterial().hasContainer()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/OldChunk.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/OldChunk.java index add26e1c0..b4667709d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/OldChunk.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/OldChunk.java @@ -183,7 +183,7 @@ public class OldChunk implements Chunk { BlockState state = LegacyMapper.getInstance().getBlockFromLegacy(id, dataVal); if (state == null) { - WorldEdit.logger.warning("Unknown legacy block " + id + ":" + dataVal + " found when loading legacy anvil chunk."); + WorldEdit.logger.warn("Unknown legacy block " + id + ":" + dataVal + " found when loading legacy anvil chunk."); return BlockTypes.AIR.getDefaultState().toBaseBlock(); } if (state.getBlockType().getMaterial().hasContainer()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockData.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockData.java index 9023fefd5..88b714b10 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockData.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockData.java @@ -24,7 +24,10 @@ import com.google.gson.*; import com.google.gson.reflect.TypeToken; import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.gson.VectorAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.IOException; import java.lang.reflect.Type; import java.net.URL; @@ -32,10 +35,6 @@ import java.nio.charset.Charset; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.annotation.Nullable; /** * Provides block data based on the built-in block database that is bundled @@ -50,7 +49,7 @@ import javax.annotation.Nullable; */ public class BundledBlockData { - private static final Logger log = Logger.getLogger(BundledBlockData.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(BundledBlockData.class); private static BundledBlockData INSTANCE; private final Map idMap = new HashMap<>(); @@ -62,7 +61,7 @@ public class BundledBlockData { try { loadFromResource(); } catch (Throwable e) { - log.log(Level.WARNING, "Failed to load the built-in block registry", e); + log.warn("Failed to load the built-in block registry", e); } } @@ -152,4 +151,4 @@ public class BundledBlockData { public SimpleBlockMaterial material = new SimpleBlockMaterial(); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemData.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemData.java index 2867b2e56..4bdac0c8a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemData.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemData.java @@ -25,17 +25,16 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.gson.VectorAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.annotation.Nullable; /** * Provides item data based on the built-in item database that is bundled @@ -50,7 +49,7 @@ import javax.annotation.Nullable; */ public class BundledItemData { - private static final Logger log = Logger.getLogger(BundledItemData.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(BundledItemData.class); private static BundledItemData INSTANCE; private final Map idMap = new HashMap<>(); @@ -62,7 +61,7 @@ public class BundledItemData { try { loadFromResource(); } catch (Throwable e) { - log.log(Level.WARNING, "Failed to load the built-in item registry", e); + log.warn("Failed to load the built-in item registry", e); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/LegacyMapper.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/LegacyMapper.java index 369578dfa..d0d129101 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/LegacyMapper.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/LegacyMapper.java @@ -40,22 +40,22 @@ import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemTypes; -import com.sk89q.worldedit.extension.input.ParserContext; -import com.sk89q.worldedit.util.gson.VectorAdapter; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; +import java.util.Arrays; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; +import static com.google.common.base.Preconditions.checkNotNull; public class LegacyMapper { - private static final Logger log = Logger.getLogger(LegacyMapper.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(LegacyMapper.class); private static LegacyMapper INSTANCE; private final Int2ObjectArrayMap blockStateToLegacyId4Data = new Int2ObjectArrayMap<>(); @@ -70,8 +70,7 @@ public class LegacyMapper { try { loadFromResource(); } catch (Throwable e) { - e.printStackTrace(); - log.log(Level.WARNING, "Failed to load the built-in legacy id registry", e); + log.warn("Failed to load the built-in legacy id registry", e); } } @@ -110,7 +109,7 @@ public class LegacyMapper { blockStateToLegacyId4Data.put(blockState.getInternalId(), (Integer) combinedId); blockStateToLegacyId4Data.putIfAbsent(blockState.getInternalBlockTypeId(), combinedId); } catch (Exception e) { - log.fine("Unknown block: " + blockEntry.getValue()); + log.warn("Unknown block: " + blockEntry.getValue()); } } for (int id = 0; id < 256; id++) { @@ -127,7 +126,7 @@ public class LegacyMapper { try { itemMap.put(getCombinedId(itemEntry.getKey()), ItemTypes.get(itemEntry.getValue())); } catch (Exception e) { - log.fine("Unknown item: " + itemEntry.getValue()); + log.warn("Unknown item: " + itemEntry.getValue()); } } } @@ -232,7 +231,7 @@ public class LegacyMapper { try { return BlockTypes.get(plotBlock.toString()).getDefaultState().toBaseBlock(); }catch(Throwable failed) { - log.severe("Unable to convert StringPlotBlock " + plotBlock + " to BaseBlock!"); + log.error("Unable to convert StringPlotBlock " + plotBlock + " to BaseBlock!"); failed.printStackTrace(); return null; } @@ -240,12 +239,12 @@ public class LegacyMapper { try { return new BaseBlock(((LegacyPlotBlock)plotBlock).getId(), ((LegacyPlotBlock)plotBlock).getData()); }catch(Throwable failed) { - log.severe("Unable to convert LegacyPlotBlock " + plotBlock + " to BaseBlock!"); + log.error("Unable to convert LegacyPlotBlock " + plotBlock + " to BaseBlock!"); failed.printStackTrace(); return null; } }else { - log.severe("Unable to convert LegacyPlotBlock " + plotBlock + " to BaseBlock!"); + log.error("Unable to convert LegacyPlotBlock " + plotBlock + " to BaseBlock!"); return null; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/Snapshot.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/Snapshot.java index 58525a7d2..0af2b6e18 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/Snapshot.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/Snapshot.java @@ -29,11 +29,12 @@ import com.sk89q.worldedit.world.storage.TrueZipLegacyChunkStore; import com.sk89q.worldedit.world.storage.TrueZipMcRegionChunkStore; import com.sk89q.worldedit.world.storage.ZippedLegacyChunkStore; import com.sk89q.worldedit.world.storage.ZippedMcRegionChunkStore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.Calendar; -import java.util.logging.Logger; import java.util.zip.ZipFile; /** @@ -41,7 +42,7 @@ import java.util.zip.ZipFile; */ public class Snapshot implements Comparable { - protected static Logger logger = Logger.getLogger(Snapshot.class.getCanonicalName()); + protected static Logger logger = LoggerFactory.getLogger(Snapshot.class); protected File file; protected String name; diff --git a/worldedit-core/src/main/resources/com/sk89q/worldedit/world/registry/legacy.json b/worldedit-core/src/main/resources/com/sk89q/worldedit/world/registry/legacy.json index 7a5f42453..cb97197ae 100644 --- a/worldedit-core/src/main/resources/com/sk89q/worldedit/world/registry/legacy.json +++ b/worldedit-core/src/main/resources/com/sk89q/worldedit/world/registry/legacy.json @@ -404,7 +404,6 @@ "61:11": "minecraft:furnace[facing=south,lit=false]", "61:12": "minecraft:furnace[facing=west,lit=false]", "61:13": "minecraft:furnace[facing=east,lit=false]", - "62:0": "minecraft:lit_furnace", "62:2": "minecraft:furnace[facing=north,lit=true]", "62:3": "minecraft:furnace[facing=south,lit=true]", "62:4": "minecraft:furnace[facing=west,lit=true]", @@ -1849,7 +1848,7 @@ "48:0": "minecraft:mossy_cobblestone", "49:0": "minecraft:obsidian", "50:0": "minecraft:torch", - "52:0": "minecraft:mob_spawner", + "52:0": "minecraft:spawner", "53:0": "minecraft:oak_stairs", "54:0": "minecraft:chest", "56:0": "minecraft:diamond_ore", @@ -2393,4 +2392,4 @@ "2266:0": "minecraft:music_disc_11", "2267:0": "minecraft:music_disc_wait" } -} \ No newline at end of file +} diff --git a/worldedit-core/src/test/java/com/sk89q/minecraft/util/commands/CommandContextTest.java b/worldedit-core/src/test/java/com/sk89q/minecraft/util/commands/CommandContextTest.java index 025981e6e..555c83889 100644 --- a/worldedit-core/src/test/java/com/sk89q/minecraft/util/commands/CommandContextTest.java +++ b/worldedit-core/src/test/java/com/sk89q/minecraft/util/commands/CommandContextTest.java @@ -21,17 +21,21 @@ package com.sk89q.minecraft.util.commands; import org.junit.Before; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashSet; -import java.util.logging.Level; -import java.util.logging.Logger; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; public class CommandContextTest { - private static final Logger log = Logger.getLogger(CommandContextTest.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(CommandContextTest.class); private static final String firstCmdString = "herpderp -opw testers \"mani world\" 'another thing' because something"; CommandContext firstCommand; @@ -40,7 +44,7 @@ public class CommandContextTest { try { firstCommand = new CommandContext(firstCmdString, new HashSet<>(Arrays.asList('o', 'w'))); } catch (CommandException e) { - log.log(Level.WARNING, "Error", e); + log.warn("Error", e); fail("Unexpected exception when creating CommandContext"); } } @@ -79,7 +83,7 @@ public class CommandContextTest { new CommandContext(cmd); new CommandContext(cmd2); } catch (CommandException e) { - log.log(Level.WARNING, "Error", e); + log.warn("Error", e); fail("Error creating CommandContext"); } } @@ -90,7 +94,7 @@ public class CommandContextTest { try { new CommandContext(cmd); } catch (CommandException e) { - log.log(Level.WARNING, "Error", e); + log.warn("Error", e); fail("Error creating CommandContext"); } } @@ -101,7 +105,7 @@ public class CommandContextTest { try { new CommandContext(cmd); } catch (CommandException e) { - log.log(Level.WARNING, "Error", e); + log.warn("Error", e); fail("Error creating CommandContext"); } } @@ -115,7 +119,7 @@ public class CommandContextTest { CommandContext context2 = new CommandContext("r hello -f world"); assertTrue(context2.hasFlag('f')); } catch (CommandException e) { - log.log(Level.WARNING, "Error", e); + log.warn("Error", e); fail("Error creating CommandContext"); } } @@ -131,7 +135,7 @@ public class CommandContextTest { CommandContext context2 = new CommandContext("pm name \"hello world\" foo bar"); assertEquals("\"hello world\" foo bar", context2.getJoinedStrings(1)); } catch (CommandException e) { - log.log(Level.WARNING, "Error", e); + log.warn("Error", e); fail("Error creating CommandContext"); } } @@ -143,7 +147,7 @@ public class CommandContextTest { assertArrayEquals(new String[] { "foo", "bar", "baz" }, context.getSlice(0)); } catch (CommandException e) { - log.log(Level.WARNING, "Error", e); + log.warn("Error", e); fail("Error creating CommandContext"); } } @@ -154,7 +158,7 @@ public class CommandContextTest { CommandContext context = new CommandContext("region flag xmas blocked-cmds \"\""); assertEquals(context.argsLength(), 3); } catch (CommandException e) { - log.log(Level.WARNING, "Error", e); + log.warn("Error", e); fail("Error creating CommandContext"); } } diff --git a/worldedit-forge/build.gradle b/worldedit-forge/build.gradle index f5c6e0f7d..cdbd5ce60 100644 --- a/worldedit-forge/build.gradle +++ b/worldedit-forge/build.gradle @@ -16,6 +16,7 @@ apply plugin: 'net.minecraftforge.gradle.forge' dependencies { compile project(':worldedit-core') + compile 'org.apache.logging.log4j:log4j-slf4j-impl:2.11.2' compile 'org.spongepowered:spongeapi:6.0.0-SNAPSHOT' testCompile group: 'org.mockito', name: 'mockito-core', version: '1.9.0-rc1' } diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplLoader.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplLoader.java index dac72425e..7f5bb0f84 100644 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplLoader.java +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplLoader.java @@ -21,6 +21,8 @@ package com.sk89q.worldedit.sponge.adapter; import com.google.common.collect.Lists; import com.sk89q.worldedit.util.io.Closer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; @@ -30,15 +32,13 @@ import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; -import java.util.logging.Level; -import java.util.logging.Logger; /** * Loads Sponge implementation adapters. */ public class SpongeImplLoader { - private static final Logger log = Logger.getLogger(SpongeImplLoader.class.getCanonicalName()); + private static final Logger log = LoggerFactory.getLogger(SpongeImplLoader.class); private final List adapterCandidates = new ArrayList<>(); private String customCandidate; @@ -71,7 +71,7 @@ public class SpongeImplLoader { if (className != null) { customCandidate = className; adapterCandidates.add(className); - log.log(Level.INFO, "-Dworldedit.sponge.adapter used to add " + className + " to the list of available Sponge adapters"); + log.info("-Dworldedit.sponge.adapter used to add " + className + " to the list of available Sponge adapters"); } } @@ -157,18 +157,18 @@ public class SpongeImplLoader { if (SpongeImplAdapter.class.isAssignableFrom(cls)) { suitableAdapters.add((SpongeImplAdapter) cls.newInstance()); } else { - log.log(Level.WARNING, "Failed to load the Sponge adapter class '" + className + + log.warn("Failed to load the Sponge adapter class '" + className + "' because it does not implement " + SpongeImplAdapter.class.getCanonicalName()); } } catch (ClassNotFoundException e) { - log.log(Level.WARNING, "Failed to load the Sponge adapter class '" + className + + log.warn("Failed to load the Sponge adapter class '" + className + "' that is not supposed to be missing", e); } catch (IllegalAccessException e) { - log.log(Level.WARNING, "Failed to load the Sponge adapter class '" + className + + log.warn("Failed to load the Sponge adapter class '" + className + "' that is not supposed to be raising this error", e); } catch (Throwable e) { if (className.equals(customCandidate)) { - log.log(Level.WARNING, "Failed to load the Sponge adapter class '" + className + "'", e); + log.warn("Failed to load the Sponge adapter class '" + className + "'", e); } } }