From 86ce7629827ee239bacb8c88965b10b1c5a34963 Mon Sep 17 00:00:00 2001 From: matt <4009945+MattBDev@users.noreply.github.com> Date: Mon, 1 Apr 2019 20:42:10 -0400 Subject: [PATCH] Minor performance tweaks and cleaning of metrics Why were metrics so messed up in the first place? --- .../voxelsniper/brush/OverlayBrush.java | 8 +- .../voxelsniper/brush/SnowConeBrush.java | 21 +- .../java/com/boydti/fawe/bukkit/BStats.java | 704 ++++++++++++++++++ .../com/boydti/fawe/bukkit/FaweBukkit.java | 98 +-- .../java/com/boydti/fawe/bukkit/Metrics.java | 584 --------------- .../fawe/bukkit/v0/BukkitChunk_All.java | 151 ++-- .../fawe/bukkit/wrapper/AsyncBlock.java | 7 +- .../src/main/java/com/boydti/fawe/Fawe.java | 3 - .../fawe/jnbt/anvil/HeightMapMCADrawer.java | 17 +- .../jnbt/anvil/HeightMapMCAGenerator.java | 46 +- .../fawe/jnbt/anvil/generator/CavesGen.java | 9 +- .../com/boydti/fawe/util/metrics/BStats.java | 419 ----------- .../java/com/sk89q/worldedit/EditSession.java | 23 +- 13 files changed, 854 insertions(+), 1236 deletions(-) create mode 100644 worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BStats.java delete mode 100644 worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/Metrics.java delete mode 100644 worldedit-core/src/main/java/com/boydti/fawe/util/metrics/BStats.java diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/OverlayBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/OverlayBrush.java index 2287b0dc9..e8a3b9ea7 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/OverlayBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/OverlayBrush.java @@ -70,11 +70,9 @@ public class OverlayBrush extends PerformBrush { @SuppressWarnings("deprecation") private boolean isIgnoredBlock(int materialId) { BlockType type = BlockTypes.get(materialId); - switch (type.getResource().toUpperCase()) { - case "WATER": - case "LAVA": - case "CACTUS": - return true; + String s = type.getResource().toUpperCase(); + if (type == BlockTypes.WATER || type == BlockTypes.LAVA || type == BlockTypes.CACTUS) { + return true; } BlockMaterial mat = type.getMaterial(); return mat.isTranslucent(); diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SnowConeBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SnowConeBrush.java index 72f9abc6c..056184209 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SnowConeBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SnowConeBrush.java @@ -2,6 +2,7 @@ package com.thevoxelbox.voxelsniper.brush; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.thevoxelbox.voxelsniper.Message; import com.thevoxelbox.voxelsniper.SnipeData; @@ -95,19 +96,15 @@ public class SnowConeBrush extends Brush if (snowData > snowconeData[x][z]) { - switch (BlockTypes.get(snowcone[x][z]).getResource().toUpperCase()) - { - case "AIR": - case "CAVE_AIR": - case "VOID_AIR": - snowconeData[x][z] = snowData; - snowcone[x][z] = BlockTypes.SNOW.getInternalId(); - case "SNOW_BLOCK": - snowconeData[x][z] = snowData; - break; - default: - break; + BlockType blockType = + BlockTypes.get(snowcone[x][z]); + if (blockType.getMaterial().isAir()) { + snowconeData[x][z] = snowData; + snowcone[x][z] = BlockTypes.SNOW.getInternalId(); + snowconeData[x][z] = snowData; + } else if (blockType == BlockTypes.SNOW_BLOCK) { + snowconeData[x][z] = snowData; } } else if (yOffset[x][z] > 0 && snowcone[x][z] == BlockTypes.SNOW.getInternalId()) diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BStats.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BStats.java new file mode 100644 index 000000000..1bcc86214 --- /dev/null +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BStats.java @@ -0,0 +1,704 @@ +package org.bstats.bukkit; + +import com.boydti.fawe.Fawe; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) public class BStats { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System + .getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', + 'k', 'i', 't'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class + .getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException( + "bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public BStats(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)").copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { + } + } + // Register our service + Bukkit.getServicesManager() + .register(BStats.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = + new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JSONObject getPluginData() { + JSONObject data = new JSONObject(); + + String pluginName = "FastAsyncWorldEdit"; + String pluginVersion = Fawe.get().getVersion() + ""; + + data.put("pluginName", pluginName); // Append the name of the plugin + data.put("pluginVersion", pluginVersion); // Append the version of the plugin + JSONArray customCharts = new JSONArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JSONObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.put("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JSONObject getServerData() { + // Minecraft specific data + int playerAmount = getPlayerCount(); + int onlineMode = Fawe.imp().isOnlineMode() ? 1 : 0; + String serverVersion = Fawe.imp().getPlatformVersion(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JSONObject data = new JSONObject(); + + data.put("serverUUID", serverUUID); + + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", serverVersion); + + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + + return data; + } + + public int getPlayerCount() { + return Fawe.imp() == null ? 1 : Fawe.imp().getPlayerCount(); + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JSONObject data = getServerData(); + + JSONArray pluginData = new JSONArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager() + .getRegistrations(service)) { + try { + pluginData.add(provider.getService().getMethod("getPluginData") + .invoke(provider.getProvider())); + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } + } + } catch (NoSuchFieldException ignored) { + } + } + + data.put("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(() -> { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger() + .log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), + e); + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException( + "This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data.toString()); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", + "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + outputStream.flush(); + } + + StringBuilder builder; + try (InputStream inputStream = connection.getInputStream(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(inputStream))) { + + builder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + plugin.getLogger() + .info("Sent data to bStats and received response: " + builder.toString()); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JSONObject getRequestJsonObject() { + JSONObject chart = new JSONObject(); + chart.put("chartId", chartId); + try { + JSONObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.put("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, + "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JSONObject getChartData() throws Exception; + + } + + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + } + + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override public JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JSONObject value = new JSONObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()) + .entrySet()) { + value.put(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.put(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + + } + + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + data.put("values", values); + return data; + } + + } + + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JSONArray categoryValues = new JSONArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.put(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java index 88e819630..550a1fe8e 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java @@ -24,13 +24,11 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.regions.FaweMaskManager; import com.boydti.fawe.util.Jars; import com.boydti.fawe.util.MainUtil; -import com.boydti.fawe.util.ReflectionUtils; import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.cui.CUI; import com.boydti.fawe.util.image.ImageViewer; -import com.boydti.fawe.util.metrics.BStats; -import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.world.World; +import org.bstats.bukkit.BStats; import org.bukkit.Bukkit; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.PluginCommand; @@ -41,7 +39,6 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.Vector; @@ -74,8 +71,6 @@ public class FaweBukkit implements IFawe, Listener { return this.vault; } - private List locations = Arrays.asList(new Vector(0, 5, 0)); - public FaweBukkit(Plugin plugin) { this.plugin = plugin; try { @@ -110,28 +105,25 @@ public class FaweBukkit implements IFawe, Listener { } // Registered delayed Event Listeners - TaskManager.IMP.task(new Runnable() { - @Override - public void run() { - // This class - Bukkit.getPluginManager().registerEvents(FaweBukkit.this, FaweBukkit.this.plugin); + TaskManager.IMP.task(() -> { + // This class + Bukkit.getPluginManager().registerEvents(FaweBukkit.this, FaweBukkit.this.plugin); - // The tick limiter - try { - Class.forName("sun.misc.SharedSecrets"); - new ChunkListener_8(); - } catch (ClassNotFoundException e) { - new ChunkListener_9(); - } - - /*try { - Class.forName("com.destroystokyo.paper.event.server.AsyncTabCompleteEvent"); - new AsyncTabCompleteListener(WorldEditPlugin.getInstance()); - } catch (Throwable ignore) - { - Bukkit.getPluginManager().registerEvents(new SyncTabCompleteListener(WorldEditPlugin.getInstance()), plugin); - }*/ + // The tick limiter + try { + Class.forName("sun.misc.SharedSecrets"); + new ChunkListener_8(); + } catch (ClassNotFoundException e) { + new ChunkListener_9(); } + + /*try { + Class.forName("com.destroystokyo.paper.event.server.AsyncTabCompleteEvent"); + new AsyncTabCompleteListener(WorldEditPlugin.getInstance()); + } catch (Throwable ignore) + { + Bukkit.getPluginManager().registerEvents(new SyncTabCompleteListener(WorldEditPlugin.getInstance()), plugin); + }*/ }); } @@ -265,42 +257,8 @@ public class FaweBukkit implements IFawe, Listener { } } - @Override - public void startMetrics() { - Metrics metrics = new Metrics(plugin); - metrics.start(); - TaskManager.IMP.task(new Runnable() { - @Override - public void run() { - ArrayList> services = new ArrayList(Bukkit.getServicesManager().getKnownServices()); - services.forEach(service -> { - try { - service.getField("B_STATS_VERSION"); - ArrayList> providers = new ArrayList(Bukkit.getServicesManager().getRegistrations(service)); - for (RegisteredServiceProvider provider : providers) { - Object instance = provider.getProvider(); - - // Link it to FAWE's metrics instead - BStats.linkMetrics(instance); - - // Disable the other metrics - Bukkit.getServicesManager().unregister(service, instance); - try { - Class clazz = instance.getClass(); - Field logFailedRequests = ReflectionUtils.findField(clazz, boolean.class); - logFailedRequests.set(null, false); - Field url = null; - try { url = clazz.getDeclaredField("URL"); } catch (NoSuchFieldException ignore) { - for (Field field : clazz.getDeclaredFields()) if (ReflectionUtils.setAccessible(field).get(null).toString().startsWith("http")) { url = field; break; } - } - if (url != null) ReflectionUtils.setFailsafeFieldValue(url, null, null); - } catch (NoSuchFieldError | IllegalAccessException ignore) {} - catch (Throwable e) {} - } - } catch (NoSuchFieldException ignored) { } - }); - } - }); + @Override public void startMetrics() { + BStats bStats = new BStats(plugin); } public ItemUtil getItemUtil() { @@ -387,12 +345,8 @@ public class FaweBukkit implements IFawe, Listener { debug("======================================="); ignore.printStackTrace(); debug("======================================="); - TaskManager.IMP.laterAsync(new Runnable() { - @Override - public void run() { - MainUtil.sendAdmin("&cNo NMS placer found, see console!"); - } - }, 1); + TaskManager.IMP.laterAsync( + () -> MainUtil.sendAdmin("&cNo NMS placer found, see console!"), 1); hasNMS = false; } return new BukkitQueue_All(world); @@ -443,12 +397,8 @@ public class FaweBukkit implements IFawe, Listener { debug("======================================="); error.printStackTrace(); debug("======================================="); - TaskManager.IMP.laterAsync(new Runnable() { - @Override - public void run() { - MainUtil.sendAdmin("&cNo NMS placer found, see console!"); - } - }, 1); + TaskManager.IMP.laterAsync( + () -> MainUtil.sendAdmin("&cNo NMS placer found, see console!"), 1); hasNMS = false; } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/Metrics.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/Metrics.java deleted file mode 100644 index cd3269238..000000000 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/Metrics.java +++ /dev/null @@ -1,584 +0,0 @@ -package com.boydti.fawe.bukkit; - -import com.boydti.fawe.Fawe; -import com.boydti.fawe.object.io.FastByteArrayOutputStream; -import com.boydti.fawe.object.io.PGZIPOutputStream; -import com.boydti.fawe.util.MainUtil; -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.*; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.scheduler.BukkitTask; - -public class Metrics { - - /** - * The current revision number. - */ - private static final int REVISION = 7; - /** - * The base url of the metrics domain. - */ - private static final String BASE_URL = "http://report.mcstats.org"; - /** - * The url used to report a server's status. - */ - private static final String REPORT_URL = "/plugin/%s"; - /** - * Interval of time to ping (in minutes). - */ - private static final int PING_INTERVAL = 15; - /** - * The plugin this metrics submits for. - */ - private final Plugin plugin; - /** - * All of the custom graphs to submit to metrics. - */ - private final Set graphs = Collections.synchronizedSet(new HashSet<>()); - /** - * Unique server id. - */ - private final String guid; - /** - * Debug mode. - */ - private final boolean debug; - /** - * The scheduled task. - */ - private volatile BukkitTask task = null; - - public Metrics(Plugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - this.plugin = plugin; - this.guid = UUID.randomUUID().toString(); - this.debug = false; - } - - /** - * GZip compress a string of bytes. - * - * @param input - * - * @return byte[] the file as a byte array - */ - public static byte[] gzip(String input) { - FastByteArrayOutputStream baos = new FastByteArrayOutputStream(); - PGZIPOutputStream gzos = null; - try { - gzos = new PGZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } catch (IOException e) { - MainUtil.handleError(e); - } finally { - if (gzos != null) { - try { - gzos.close(); - } catch (IOException ignore) { - } - } - } - return baos.toByteArray(); - } - - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * - */ - private static void appendJSONPair(StringBuilder json, String key, String value) { - boolean isValueNumeric = false; - try { - if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; - } - } catch (NumberFormatException e) { - isValueNumeric = false; - } - if (json.charAt(json.length() - 1) != '{') { - json.append(','); - } - json.append(escapeJSON(key)); - json.append(':'); - if (isValueNumeric) { - json.append(value); - } else { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * - * @return String - */ - private static String escapeJSON(String text) { - StringBuilder builder = new StringBuilder(); - builder.append('"'); - for (int index = 0; index < text.length(); index++) { - char chr = text.charAt(index); - switch (chr) { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } else { - builder.append(chr); - } - break; - } - } - builder.append('"'); - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text the text to encode - * - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics - * website. Plotters can be added to the graph object returned. - * - * @param name The name of the graph - * - * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given - */ - public Graph createGraph(String name) { - if (name == null) { - throw new IllegalArgumentException("Graph name cannot be null"); - } - // Construct the graph object - Graph graph = new Graph(name); - // Now we can add our graph - this.graphs.add(graph); - // and return back - return graph; - } - - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend - * - * @param graph The name of the graph - */ - public void addGraph(Graph graph) { - if (graph == null) { - throw new IllegalArgumentException("Graph cannot be null"); - } - this.graphs.add(graph); - } - - /** - * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the - * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 - * ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() { - // Is metrics already running? - if (this.task != null) { - return true; - } - // Begin hitting the server with glorious data - this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { - private boolean firstPost = true; - - @Override - public void run() { - try { - postPlugin(!this.firstPost); - // After the first post we set firstPost to - // false - // Each post thereafter will be a ping - this.firstPost = false; - } catch (IOException e) { - MainUtil.handleError(e); - if (Metrics.this.debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - return true; - } - - /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. - * - * @throws IOException - */ - public void enable() { - // Enable Task, if it is not running - if (this.task == null) { - start(); - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - */ - public void disable() { - // Disable Task, if it is running - if (this.task != null) { - this.task.cancel(); - this.task = null; - } - } - - /** - * Gets the File object of the config file that should be used to store - * data such as the GUID and opt-out status. - * - * @return the File object for the config file - */ - public File getConfigFile() { - // I believe the easiest way to get the base folder (e.g craftbukkit set - // via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = this.plugin.getDataFolder().getParentFile(); - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } - - /** - * Generic method that posts a plugin to the metrics website. - */ - private void postPlugin(boolean isPing) throws IOException { - // Server software specific section - PluginDescriptionFile description = this.plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - int playersOnline = 0; - try { - if (Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).getReturnType() == Collection.class) { - playersOnline = ((Collection) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null)).size(); - } else { - playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null)).length; - } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { - ex.printStackTrace(); - } - // END server software specific section -- all code below does not use - // any code outside of this class / Java - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - // The plugin's description file containing all of the plugin data such as name, version, author, etc - appendJSONPair(json, "guid", this.guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - // If we're pinging, append it - if (isPing) { - appendJSONPair(json, "ping", "1"); - } - if (!this.graphs.isEmpty()) { - synchronized (this.graphs) { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - boolean firstGraph = true; - for (Graph graph : this.graphs) { - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - for (Plotter plotter : graph.getPlotters()) { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - graphJson.append('}'); - if (!firstGraph) { - json.append(','); - } - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - firstGraph = false; - } - json.append('}'); - } - } - // close json - json.append('}'); - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - // Connect to the website - URLConnection connection; - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } else { - connection = url.openConnection(); - } - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.setDoOutput(true); - if (this.debug) { - Fawe.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); - } - try { - try (OutputStream os = connection.getOutputStream()) { - os.write(compressed); - os.flush(); - } - String response; - try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - response = reader.readLine(); - if (this.debug) { - Fawe.debug("[Metrics] Response for " + pluginName + ": " + response); - } - } - if (response == null || response.startsWith("ERR") || response.startsWith("7")) { - if (response == null) { - response = "null"; - } else if (response.startsWith("7")) { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - throw new IOException(response); - } else { - // Is this the first update this hour? - if ("1".equals(response) || response.contains("This is your first update this hour")) { - synchronized (this.graphs) { - for (Graph graph : this.graphs) { - for (Plotter plotter : graph.getPlotters()) { - plotter.reset(); - } - } - } - } - } - } catch (Exception e) { - if (this.debug) { - MainUtil.handleError(e); - } - } - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - - /** - * Represents a custom graph on the website - */ - public static class Graph { - - /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is - * rejected - */ - private final String name; - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet<>(); - - private Graph(String name) { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() { - return this.name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter the plotter to add to the graph - */ - public void addPlotter(Plotter plotter) { - this.plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter the plotter to remove from the graph - */ - public void removePlotter(Plotter plotter) { - this.plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link Set} of the plotter objects - */ - public Set getPlotters() { - return Collections.unmodifiableSet(this.plotters); - } - - @Override - public int hashCode() { - return this.name.hashCode(); - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof Graph)) { - return false; - } - Graph graph = (Graph) object; - return graph.name.equals(this.name); - } - - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() { - } - } - - /** - * Interface used to collect custom data for a plugin - */ - public abstract static class Plotter { - - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name the name of the plotter to use, which will show up on the website - */ - public Plotter(String name) { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may - * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called - * from any thread so care should be taken when accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() { - return this.name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() { - } - - @Override - public int hashCode() { - return getColumnName().hashCode(); - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof Plotter)) { - return false; - } - Plotter plotter = (Plotter) object; - return plotter.name.equals(this.name) && plotter.getValue() == getValue(); - } - } -} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitChunk_All.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitChunk_All.java index d17db69f8..cb727178e 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitChunk_All.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitChunk_All.java @@ -235,41 +235,38 @@ public class BukkitChunk_All extends IntFaweChunk { BlockType type = BlockTypes.getFromStateId(combined); if (type == BlockTypes.__RESERVED__) continue; - switch (type.getResource().toUpperCase()) { - case "AIR": - case "CAVE_AIR": - case "VOID_AIR": - if (!place) { - mutableLoc.setX(xx); - mutableLoc.setY(yy); - mutableLoc.setZ(zz); + String s = type.getResource().toUpperCase(); + if (type.getMaterial().isAir()) { + if (!place) { + mutableLoc.setX(xx); + mutableLoc.setY(yy); + mutableLoc.setZ(zz); + setBlock(adapter, chunk, mutableLoc, combined, update); + } + continue; + } + if (place) { + if (type.getMaterial().hasContainer() && adapter != null) { + CompoundTag nbt = getTile(x, yy, z); + if (nbt != null) { + synchronized (BukkitChunk_All.this) { + BaseBlock state = + BaseBlock.getFromInternalId(combined, nbt); + adapter.setBlock(chunk, xx, yy, zz, state, update); + } + continue; + } + } + if (type.getMaterial().isTicksRandomly()) { + synchronized (BukkitChunk_All.this) { setBlock(adapter, chunk, mutableLoc, combined, update); } - continue; - default: - if (place) { - if (type.getMaterial().hasContainer() && adapter != null) { - CompoundTag nbt = getTile(x, yy, z); - if (nbt != null) { - synchronized (BukkitChunk_All.this) { - BaseBlock state = BaseBlock.getFromInternalId(combined, nbt); - adapter.setBlock(chunk, xx, yy, zz, state, update); - } - continue; - } - } - if (type.getMaterial().isTicksRandomly()) { - synchronized (BukkitChunk_All.this) { - setBlock(adapter, chunk, mutableLoc, combined, update); - } - } else { - mutableLoc.setX(xx); - mutableLoc.setY(yy); - mutableLoc.setZ(zz); - setBlock(adapter, chunk, mutableLoc, combined, update); - } - } - continue; + } else { + mutableLoc.setX(xx); + mutableLoc.setY(yy); + mutableLoc.setZ(zz); + setBlock(adapter, chunk, mutableLoc, combined, update); + } } } } @@ -280,63 +277,59 @@ public class BukkitChunk_All extends IntFaweChunk { int combined = newArray[j]; BlockType type = BlockTypes.getFromStateId(combined); if (type == BlockTypes.__RESERVED__) continue; - switch (type.getResource().toUpperCase()) { - case "AIR": - case "CAVE_AIR": - case "VOID_AIR": - if (!place) { - int x = cacheX[j]; - int z = cacheZ[j]; - int y = cacheY[j]; - mutableLoc.setX(bx + x); - mutableLoc.setY(y); - mutableLoc.setZ(bz + z); - setBlock(adapter, chunk, mutableLoc, combined, update); - } - break; - default: - boolean light = type.getMaterial().getLightValue() > 0; - if (light) { - if (place) { - continue; - } - light = light && getParent().getSettings().LIGHTING.MODE != 0; - if (light) { - parent.enableLighting(disableResult); - } - } else if (!place) { - continue; - } + if (type.getMaterial().isAir()) { + if (!place) { int x = cacheX[j]; int z = cacheZ[j]; int y = cacheY[j]; - if (type.getMaterial().hasContainer() && adapter != null) { - CompoundTag tile = getTile(x, y, z); - if (tile != null) { - synchronized (BukkitChunk_All.this) { - BaseBlock state = BaseBlock.getFromInternalId(combined, tile); - adapter.setBlock(chunk, bx + x, y, bz + z, state, update); - } - break; - } + mutableLoc.setX(bx + x); + mutableLoc.setY(y); + mutableLoc.setZ(bz + z); + setBlock(adapter, chunk, mutableLoc, combined, update); + } + continue; + } else { + boolean light = type.getMaterial().getLightValue() > 0; + if (light) { + if (place) { + continue; } - if (type.getMaterial().isTicksRandomly()) { + light = light && getParent().getSettings().LIGHTING.MODE != 0; + if (light) { + parent.enableLighting(disableResult); + } + } else if (!place) { + continue; + } + int x = cacheX[j]; + int z = cacheZ[j]; + int y = cacheY[j]; + if (type.getMaterial().hasContainer() && adapter != null) { + CompoundTag tile = getTile(x, y, z); + if (tile != null) { synchronized (BukkitChunk_All.this) { - mutableLoc.setX(bx + x); - mutableLoc.setY(y); - mutableLoc.setZ(bz + z); - setBlock(adapter, chunk, mutableLoc, combined, update); + BaseBlock state = BaseBlock.getFromInternalId(combined, tile); + adapter.setBlock(chunk, bx + x, y, bz + z, state, update); } - } else { + break; + } + } + if (type.getMaterial().isTicksRandomly()) { + synchronized (BukkitChunk_All.this) { mutableLoc.setX(bx + x); mutableLoc.setY(y); mutableLoc.setZ(bz + z); setBlock(adapter, chunk, mutableLoc, combined, update); } - if (light) { - parent.disableLighting(disableResult); - } - break; + } else { + mutableLoc.setX(bx + x); + mutableLoc.setY(y); + mutableLoc.setZ(bz + z); + setBlock(adapter, chunk, mutableLoc, combined, update); + } + if (light) { + parent.disableLighting(disableResult); + } } if (System.currentTimeMillis() - start > recommended) { index++; diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncBlock.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncBlock.java index 276c89396..f9e588f1f 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncBlock.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncBlock.java @@ -217,10 +217,9 @@ public class AsyncBlock implements Block { public AsyncBlockState getState() { int combined = queue.getCombinedId4Data(x, y, z, 0); BlockType type = BlockTypes.getFromStateId(combined); - switch (type.getResource().toUpperCase()) { - case "SIGN": - case "WALL_SIGN": - return new AsyncSign(this, combined); + String s = type.getResource().toUpperCase(); + if (type == BlockTypes.SIGN || type == BlockTypes.WALL_SIGN) { + return new AsyncSign(this, combined); } return new AsyncBlockState(this, combined); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java index ad22f754e..5bba05f4a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java @@ -10,7 +10,6 @@ import com.boydti.fawe.util.*; import com.boydti.fawe.util.chat.ChatManager; import com.boydti.fawe.util.chat.PlainChatManager; import com.boydti.fawe.util.cui.CUI; -import com.boydti.fawe.util.metrics.BStats; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.factory.DefaultTransformParser; import com.sk89q.worldedit.extension.platform.Actor; @@ -18,9 +17,7 @@ import com.sk89q.worldedit.session.request.Request; import javax.annotation.Nullable; import javax.management.InstanceAlreadyExistsException; -import javax.management.Notification; import javax.management.NotificationEmitter; -import javax.management.NotificationListener; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCADrawer.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCADrawer.java index b85e64926..4e79230d7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCADrawer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCADrawer.java @@ -82,16 +82,13 @@ public final class HeightMapMCADrawer { int waterId = gen.primtives.waterId; int waterColor = 0; BlockType waterType = BlockTypes.get(waterId); - switch (waterType.getResource().toUpperCase()) { - case "WATER": - color = tu.averageColor((0x11 << 16) + (0x66 << 8) + (0xCC), color); - break; - case "LAVA": - color = (0xCC << 16) + (0x33 << 8) + (0); - break; - default: - color = tu.getColor(waterType); - break; + String s = waterType.getResource().toUpperCase(); + if (waterType == BlockTypes.WATER) { + color = tu.averageColor((0x11 << 16) + (0x66 << 8) + (0xCC), color); + } else if (waterType == BlockTypes.LAVA) { + color = (0xCC << 16) + (0x33 << 8) + (0); + } else { + color = tu.getColor(waterType); } } raw[index] = color; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java index 96f7478cd..b47a8400b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java @@ -445,20 +445,17 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr private final void setLayerHeight(int index, int blockHeight, int layerHeight) { int floorState = floor.get()[index]; - switch (BlockTypes.getFromStateId(floorState).getResource().toUpperCase()) { - case "SNOW": - case "SNOW_BLOCK": - if (layerHeight != 0) { - this.heights.setByte(index, (byte) (blockHeight + 1)); - this.floor.setInt(index, (BlockTypes.SNOW.getInternalId() + layerHeight)); - } else { - this.heights.setByte(index, (byte) (blockHeight)); - this.floor.setInt(index, (BlockTypes.SNOW_BLOCK.getInternalId())); - } - break; - default: + BlockType type = BlockTypes.getFromStateId(floorState); + if (type == BlockTypes.SNOW || type == BlockTypes.SNOW_BLOCK) { + if (layerHeight != 0) { + this.heights.setByte(index, (byte) (blockHeight + 1)); + this.floor.setInt(index, (BlockTypes.SNOW.getInternalId() + layerHeight)); + } else { this.heights.setByte(index, (byte) (blockHeight)); - break; + this.floor.setInt(index, (BlockTypes.SNOW_BLOCK.getInternalId())); + } + } else { + this.heights.setByte(index, (byte) (blockHeight)); } } @@ -470,20 +467,17 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr private final void setLayerHeightRaw(int index, int blockHeight, int layerHeight) { int floorState = floor.get()[index]; - switch (BlockTypes.getFromStateId(floorState).getResource().toUpperCase()) { - case "SNOW": - case "SNOW_BLOCK": - if (layerHeight != 0) { - this.heights.getByteArray()[index] = (byte) (blockHeight + 1); - this.floor.getIntArray()[index] = (BlockTypes.SNOW.getInternalId() + layerHeight); - } else { - this.heights.getByteArray()[index] = (byte) (blockHeight); - this.floor.getIntArray()[index] = (BlockTypes.SNOW_BLOCK.getInternalId()); - } - break; - default: + BlockType type = BlockTypes.getFromStateId(floorState); + if (type == BlockTypes.SNOW || type == BlockTypes.SNOW_BLOCK) { + if (layerHeight != 0) { + this.heights.getByteArray()[index] = (byte) (blockHeight + 1); + this.floor.getIntArray()[index] = (BlockTypes.SNOW.getInternalId() + layerHeight); + } else { this.heights.getByteArray()[index] = (byte) (blockHeight); - break; + this.floor.getIntArray()[index] = (BlockTypes.SNOW_BLOCK.getInternalId()); + } + } else { + this.heights.getByteArray()[index] = (byte) (blockHeight); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java index 10776e886..3d87e2f07 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java @@ -6,6 +6,7 @@ import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import java.util.concurrent.ThreadLocalRandom; @@ -174,11 +175,9 @@ public class CavesGen extends GenBase { if ((d11 > -0.7D) && (d9 * d9 + d11 * d11 + d10 * d10 < 1.0D)) { BlockStateHolder material = chunk.getLazyBlock(bx + local_x, local_y, bz + local_z); BlockStateHolder materialAbove = chunk.getLazyBlock(bx + local_x, local_y + 1, bz + local_z); - switch (material.getBlockType().getResource().toUpperCase()) { - case "GRASS": - case "MYCELIUM": - grassFound = true; - break; + BlockType blockType = material.getBlockType(); + if (blockType == BlockTypes.MYCELIUM || blockType == BlockTypes.GRASS) { + grassFound = true; } if (this.isSuitableBlock(material, materialAbove)) { if (local_y - 1 < 10) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/metrics/BStats.java b/worldedit-core/src/main/java/com/boydti/fawe/util/metrics/BStats.java deleted file mode 100644 index 3c90dd46b..000000000 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/metrics/BStats.java +++ /dev/null @@ -1,419 +0,0 @@ -package com.boydti.fawe.util.metrics; - -import com.boydti.fawe.Fawe; -import com.boydti.fawe.FaweVersion; -import com.boydti.fawe.configuration.file.YamlConfiguration; -import com.boydti.fawe.object.RunnableVal; -import com.boydti.fawe.object.io.PGZIPOutputStream; -import com.boydti.fawe.util.TaskManager; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Path; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; -import javax.net.ssl.HttpsURLConnection; - -/** - * bStats collects some data for plugin authors. - * - * Check out https://bStats.org/ to learn more about bStats! - */ -public class BStats implements Closeable { - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private final String url; - - // The plugin - private final String plugin; - private final String platform; - private final boolean online; - private final String serverVersion; - private final String pluginVersion; - private Timer timer; - private Gson gson = new Gson(); - - // Is bStats enabled on this server? - private volatile boolean enabled; - - // The uuid of the server - private UUID serverUUID; - - // Should failed requests be logged? - private boolean logFailedRequests = false; - - // A list with all known metrics class objects including this one - private static Class usedMetricsClass; - private static final ConcurrentLinkedQueue knownMetricsInstances = new ConcurrentLinkedQueue<>(); - - public BStats() { - this("FastAsyncWorldEdit", Fawe.get().getVersion(), Fawe.imp().getPlatformVersion(), Fawe.imp().getPlatform(), Fawe.imp().isOnlineMode()); - } - - public int getPlayerCount() { - return Fawe.imp() == null ? 1 : Fawe.imp().getPlayerCount(); - } - - private BStats(String plugin, FaweVersion faweVersion, String serverVersion, String platform, boolean online) { - this.url = "https://bStats.org/submitData/" + platform; - this.plugin = plugin; - this.pluginVersion = "" + faweVersion; - this.serverVersion = serverVersion; - this.platform = platform; - this.online = online; - - File configFile = new File(getJarFile().getParentFile(), "bStats" + File.separator + "config.yml"); - if (!configFile.exists()) { - configFile.getParentFile().mkdirs(); - try { - configFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - if (config.isSet("serverUuid")) { - try { - serverUUID = UUID.fromString(config.getString("serverUuid")); - } catch (IllegalArgumentException ignore) {} - } - // Check if the config file exists - if (serverUUID == null) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", (serverUUID = UUID.randomUUID()).toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - - if (usedMetricsClass != null) { - // Already an instance of this class - linkMetrics(this); - return; - } - this.usedMetricsClass = getFirstBStatsClass(); - if (usedMetricsClass == null) { - // Failed to get first metrics class - return; - } - if (usedMetricsClass == getClass()) { - // We are the first! :) - linkMetrics(this); - enabled = true; - } else { - // We aren't the first so we link to the first metrics class - try { - usedMetricsClass.getMethod("linkMetrics", Object.class).invoke(null,this); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - if (logFailedRequests) { - System.out.println("Failed to link to first metrics class " + usedMetricsClass.getName() + "!"); - } - } - } - } - - public void start() { - if (enabled) { - startSubmitting(); - } - } - - /** - * Links an other metrics class with this class. - * This method is called using Reflection. - * - * @param metrics An object of the metrics class to link. - */ - public static void linkMetrics(Object metrics) { - if (!knownMetricsInstances.contains(metrics)) knownMetricsInstances.add(metrics); - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() { - JsonObject data = new JsonObject(); - - data.addProperty("pluginName", plugin); - data.addProperty("pluginVersion", pluginVersion); - - JsonArray customCharts = new JsonArray(); - data.add("customCharts", customCharts); - - return data; - } - - private void startSubmitting() { - this.timer = new Timer(true); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!enabled) { - timer.cancel(); - return; - } - submitData(); - } - // No 2m delay, as this is only started after the server is loaded - }, 0, 1000*60*30); - } - - @Override - protected void finalize() throws Throwable { - close(); - super.finalize(); - } - - @Override - public void close() { - enabled = false; - if (timer != null) { - timer.cancel(); - } - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() { - int playerAmount = getPlayerCount(); - int onlineMode = online ? 1 : 0; - - int managedServers = 1; - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JsonObject data = new JsonObject(); - - data.addProperty("serverUUID", serverUUID.toString()); - - data.addProperty("playerAmount", playerAmount); - data.addProperty("managedServers", managedServers); - data.addProperty("onlineMode", onlineMode); - data.addProperty(platform + "Version", serverVersion); - - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JsonObject data = getServerData(); - - final JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Object metrics : knownMetricsInstances) { - Object plugin = TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object value) { - try { - this.value = metrics.getClass().getMethod("getPluginData").invoke(metrics); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NullPointerException | JsonSyntaxException ignored) {} - } - }); - if (plugin != null) { - if (plugin instanceof JsonObject) { - pluginData.add((JsonObject) plugin); - } else { - pluginData.add(gson.fromJson(plugin.toString(), JsonObject.class)); - } - } - } - - data.add("plugins", pluginData); - - try { - // Send the data - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - System.err.println("Could not submit plugin stats!"); - } - } - } - - /** - * Gets the first bStat Metrics class. - * - * @return The first bStats metrics class. - */ - private Class getFirstBStatsClass() { - Path configPath = getJarFile().toPath().getParent().resolve("bStats"); - configPath.toFile().mkdirs(); - File tempFile = new File(configPath.toFile(), "temp.txt"); - - try { - String className = readFile(tempFile); - if (className != null) { - try { - // Let's check if a class with the given name exists. - return Class.forName(className); - } catch (ClassNotFoundException ignored) { } - } - writeFile(tempFile, getClass().getName()); - return getClass(); - } catch (IOException e) { - if (logFailedRequests) { - System.err.println("Failed to get first bStats class!"); - } - return null; - } - } - - private File getJarFile() { - try { - URL url = BStats.class.getProtectionDomain().getCodeSource().getLocation(); - return new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath()); - } catch (MalformedURLException | URISyntaxException | SecurityException e) { - return new File(".", "plugins"); - } - } - - /** - * Reads the first line of the file. - * - * @param file The file to read. Cannot be null. - * @return The first line of the file or null if the file does not exist or is empty. - * @throws IOException If something did not work :( - */ - private String readFile(File file) throws IOException { - if (!file.exists()) { - return null; - } - try ( - FileReader fileReader = new FileReader(file); - BufferedReader bufferedReader = new BufferedReader(fileReader); - ) { - return bufferedReader.readLine(); - } - } - - /** - * Writes a String to a file. It also adds a note for the user, - * - * @param file The file to write to. Cannot be null. - * @param lines The lines to write. - * @throws IOException If something did not work :( - */ - private void writeFile(File file, String... lines) throws IOException { - if (!file.exists()) { - file.createNewFile(); - } - try ( - FileWriter fileWriter = new FileWriter(file); - BufferedWriter bufferedWriter = new BufferedWriter(fileWriter) - ) { - for (String line : lines) { - bufferedWriter.write(line); - bufferedWriter.newLine(); - } - } - } - - /** - * Sends the data to the bStats server. - * - * @param data The data to send. - * @throws Exception If the request failed. - */ - private void sendData(JsonObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null"); - } - - HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - connection.getInputStream().close(); // We don't care about the response - Just send our data :) - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PGZIPOutputStream gzip = new PGZIPOutputStream(outputStream); - gzip.write(str.getBytes("UTF-8")); - gzip.close(); - return outputStream.toByteArray(); - } - -} \ No newline at end of file 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 cb04267d4..452fbe70d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java @@ -2718,21 +2718,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, this.changes++; for (int y = basePosition.getBlockY(); y >= (basePosition.getBlockY() - 10); --y) { BlockType type = getBlockType(x, y, z); - switch (type.getResource().toUpperCase()) { - case "GRASS": - case "DIRT": - treeType.generate(this, BlockVector3.at(x, y + 1, z)); - this.changes++; - break; - case "SNOW": - setBlock(BlockVector3.at(x, y, z), BlockTypes.AIR.getDefaultState()); - break; - case "AIR": - case "CAVE_AIR": - case "VOID_AIR": - continue; - default: - break; + String s = type.getResource().toUpperCase(); + if (type == BlockTypes.GRASS || type == BlockTypes.DIRT) { + treeType.generate(this, BlockVector3.at(x, y + 1, z)); + this.changes++; + } else if (type == BlockTypes.SNOW) { + setBlock(BlockVector3.at(x, y, z), BlockTypes.AIR.getDefaultState()); + } else if (type.getMaterial().isAir()) { + continue; } // public int makeForest(BlockVector3 basePosition, int size, double density, TreeGenerator.TreeType treeType) throws MaxChangedBlocksException { // int affected = 0;