Refactoring

This commit is contained in:
BuildTools
2020-09-22 15:04:08 +01:00
parent 8861ebc5ae
commit b0593dbd08
27 changed files with 335 additions and 1024 deletions

View File

@@ -62,6 +62,11 @@
<pattern>org.apache.maven</pattern>
<shadedPattern>com.willfp.ecoenchants.shaded.maven</shadedPattern>
</relocation>
<relocation>
<pattern>org.bstats</pattern>
<!-- Replace this with your package! -->
<shadedPattern>com.willfp.ecoenchants.shaded.bstats</shadedPattern>
</relocation>
</relocations>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
@@ -232,5 +237,11 @@
<version>2.18.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.7</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@@ -3,7 +3,7 @@ package com.willfp.ecoenchants.anvil;
import com.willfp.ecoenchants.config.ConfigManager;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EnchantmentTarget;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentTarget;
import com.willfp.ecoenchants.util.Pair;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
@@ -42,7 +42,7 @@ public class AnvilMerge {
if(left.getEnchantments().containsKey(EcoEnchants.PERMANENCE_CURSE)) return new Pair<>(null, null);
if(!EnchantmentTarget.ALL.contains(left.getType()) || right == null || !EnchantmentTarget.ALL.contains(right.getType())) {
if(!EnchantmentTarget.ALL.getMaterials().contains(left.getType()) || right == null || !EnchantmentTarget.ALL.getMaterials().contains(right.getType())) {
ItemStack out = left.clone();
ItemMeta outMeta = out.getItemMeta();
outMeta.setDisplayName(name);

View File

@@ -1,727 +0,0 @@
package com.willfp.ecoenchants.bstats;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {
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 final 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;
// The plugin id
private final int pluginId;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
* @param pluginId The id of the plugin.
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/
public Metrics(Plugin plugin, int pluginId) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
this.pluginId = pluginId;
// 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(Metrics.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 = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName); // Append the name of the plugin
data.addProperty("id", pluginId); // Append the id of the plugin
data.addProperty("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.add("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JsonObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName();
// 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);
data.addProperty("playerAmount", playerAmount);
data.addProperty("onlineMode", onlineMode);
data.addProperty("bukkitVersion", bukkitVersion);
data.addProperty("bukkitName", bukkitName);
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();
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 {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility
try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object);
}
} catch (ClassNotFoundException e) {
// minecraft version 1.14+
if (logFailedRequests) {
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
}
}
}
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
} catch (NoSuchFieldException ignored) {
}
}
data.add("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);
}
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);
}
StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
}
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder);
}
}
/**
* 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();
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public abstract static 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.addProperty("chartId", chartId);
try {
JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.add("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<String> 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<String> 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.addProperty("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> 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<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> 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<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObject value = new JsonObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.add(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> 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<Integer> 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.addProperty("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> 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<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> 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<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> 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<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> 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(new JsonPrimitive(categoryValue));
}
values.add(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
}

View File

@@ -5,8 +5,8 @@ import com.willfp.ecoenchants.command.AbstractCommand;
import com.willfp.ecoenchants.config.ConfigManager;
import com.willfp.ecoenchants.display.EnchantDisplay;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EnchantmentRarity;
import com.willfp.ecoenchants.enchantments.EnchantmentTarget;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentRarity;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentTarget;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;

View File

@@ -1,52 +0,0 @@
package com.willfp.ecoenchants.config;
import com.willfp.ecoenchants.EcoEnchantsPlugin;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public abstract class RootConfig extends AbstractConfig {
protected RootConfig(String name) {
super(name, EcoEnchantsPlugin.getInstance().getDataFolder(), EcoEnchantsPlugin.class, ConfigManager.configVersions.get(name));
}
public int getInt(String path) {
return config.getInt(path);
}
public int getInt(String path, int def) {
return config.getInt(path, def);
}
public List<Integer> getInts(String path) {
return config.getIntegerList(path);
}
public boolean getBool(String path) {
return config.getBoolean(path);
}
public List<Boolean> getBools(String path) {
return config.getBooleanList(path);
}
public String getString(String path) {
return config.getString(path);
}
public List<String> getStrings(String path) {
return config.getStringList(path);
}
public double getDouble(String path) {
return config.getDouble(path);
}
public List<Double> getDoubles(String path) {
return config.getDoubleList(path);
}
public ItemStack getItemStack(String path) {
return config.getItemStack(path);
}
}

View File

@@ -5,75 +5,41 @@ import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public abstract class AbstractConfig {
private static AbstractConfig instance;
public abstract class YamlConfig {
private final String name;
private final File directory;
private final double latestVersion;
private final EcoEnchantsPlugin PLUGIN = EcoEnchantsPlugin.getInstance();
private final Class<?> sourceClass;
public YamlConfiguration config;
private File configFile;
protected final File configFile;
protected final YamlConfiguration config;
protected AbstractConfig(String name, File directory, Class<?> sourceClass, double latestVersion) {
public YamlConfig(String name) {
this.name = name;
this.directory = directory;
this.sourceClass = sourceClass;
this.latestVersion = latestVersion;
if(!directory.exists()) directory.mkdirs();
init();
}
this.configFile = new File(directory, name + ".yml");
if(!this.configFile.exists()) {
private void init() {
if (!new File(EcoEnchantsPlugin.getInstance().getDataFolder(), name + ".yml").exists()) {
createFile();
}
this.configFile = new File(EcoEnchantsPlugin.getInstance().getDataFolder(), name + ".yml");
this.config = YamlConfiguration.loadConfiguration(configFile);
instance = this;
checkVersion();
}
private void saveResource(boolean replace) {
String resourcePath = configFile.getPath().replace(PLUGIN.getDataFolder().getPath(), "");
InputStream in = sourceClass.getResourceAsStream(resourcePath);
File outFile = new File(PLUGIN.getDataFolder(), resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(PLUGIN.getDataFolder(), resourcePath.substring(0, Math.max(lastIndex, 0)));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
}
} catch (IOException ignored) {}
}
private void createFile() {
saveResource(false);
EcoEnchantsPlugin.getInstance().saveResource(name + ".yml", false);
}
private void replaceFile() {
saveResource(true);
EcoEnchantsPlugin.getInstance().saveResource(name + ".yml", true);
}
public void reload() {
@@ -86,6 +52,7 @@ public abstract class AbstractConfig {
}
private void checkVersion() {
double latestVersion = ConfigManager.configVersions.get(this.name);
if (latestVersion != config.getDouble("config-version")) {
Bukkit.getLogger().warning("EcoEnchants detected an older or invalid " + name + ".yml. Replacing it with the default config...");
Bukkit.getLogger().warning("If you've edited the config, copy over your changes!");
@@ -99,11 +66,11 @@ public abstract class AbstractConfig {
LocalDateTime now = LocalDateTime.now();
String dateTime = dtf.format(now);
try {
File backupDir = new File(PLUGIN.getDataFolder(), "backup/");
File backupDir = new File(EcoEnchantsPlugin.getInstance().getDataFolder(), "backup/");
if(!backupDir.exists()) backupDir.mkdirs();
File oldConf = new File(backupDir, name + "_" + dateTime + ".yml");
oldConf.createNewFile();
FileInputStream fis = new FileInputStream(directory + "/" + name + ".yml");
FileInputStream fis = new FileInputStream(EcoEnchantsPlugin.getInstance().getDataFolder() + "/" + name + ".yml");
FileOutputStream fos = new FileOutputStream(oldConf);
byte[] buffer = new byte[1024];
int length;
@@ -118,8 +85,4 @@ public abstract class AbstractConfig {
Bukkit.getLogger().severe("§cCould not update config. Try reinstalling EcoEnchants");
}
}
public static AbstractConfig getInstance() {
return instance;
}
}

View File

@@ -1,12 +1,55 @@
package com.willfp.ecoenchants.config.configs;
import com.willfp.ecoenchants.config.RootConfig;
import com.willfp.ecoenchants.config.YamlConfig;
import org.bukkit.inventory.ItemStack;
import java.util.List;
/**
* Wrapper for config.yml
*/
public class Config extends RootConfig {
public class Config extends YamlConfig {
public Config() {
super("config");
}
public int getInt(String path) {
return config.getInt(path);
}
public int getInt(String path, int def) {
return config.getInt(path, def);
}
public List<Integer> getInts(String path) {
return config.getIntegerList(path);
}
public boolean getBool(String path) {
return config.getBoolean(path);
}
public List<Boolean> getBools(String path) {
return config.getBooleanList(path);
}
public String getString(String path) {
return config.getString(path);
}
public List<String> getStrings(String path) {
return config.getStringList(path);
}
public double getDouble(String path) {
return config.getDouble(path);
}
public List<Double> getDoubles(String path) {
return config.getDoubleList(path);
}
public ItemStack getItemStack(String path) {
return config.getItemStack(path);
}
}

View File

@@ -3,8 +3,8 @@ package com.willfp.ecoenchants.config.configs;
import com.willfp.ecoenchants.config.EnchantmentYamlConfig;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EnchantmentRarity;
import com.willfp.ecoenchants.enchantments.EnchantmentTarget;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentRarity;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentTarget;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;

View File

@@ -1,16 +1,26 @@
package com.willfp.ecoenchants.config.configs;
import com.willfp.ecoenchants.config.RootConfig;
import com.willfp.ecoenchants.config.YamlConfig;
import org.bukkit.ChatColor;
import java.util.List;
/**
* Wrapper for lang.yml
*/
public class Lang extends RootConfig {
public class Lang extends YamlConfig {
public Lang() {
super("lang");
}
public String getString(String path) {
return config.getString(path);
}
public List<String> getStrings(String path) {
return config.getStringList(path);
}
public String getPrefix() {
return ChatColor.translateAlternateColorCodes('&', config.getString("messages.prefix"));

View File

@@ -1,13 +1,14 @@
package com.willfp.ecoenchants.config.configs;
import com.willfp.ecoenchants.config.RootConfig;
import com.willfp.ecoenchants.config.YamlConfig;
import java.util.List;
import java.util.Set;
/**
* Wrapper for config.yml
*/
public class Rarity extends RootConfig {
public class Rarity extends YamlConfig {
public Rarity() {
super("rarity");
}
@@ -15,4 +16,40 @@ public class Rarity extends RootConfig {
public Set<String> getRarities() {
return config.getConfigurationSection("rarities").getKeys(false);
}
public int getInt(String path) {
return config.getInt(path);
}
public int getInt(String path, int def) {
return config.getInt(path, def);
}
public List<Integer> getInts(String path) {
return config.getIntegerList(path);
}
public boolean getBool(String path) {
return config.getBoolean(path);
}
public List<Boolean> getBools(String path) {
return config.getBooleanList(path);
}
public String getString(String path) {
return config.getString(path);
}
public List<String> getStrings(String path) {
return config.getStringList(path);
}
public double getDouble(String path) {
return config.getDouble(path);
}
public List<Double> getDoubles(String path) {
return config.getDoubleList(path);
}
}

View File

@@ -1,6 +1,6 @@
package com.willfp.ecoenchants.config.configs;
import com.willfp.ecoenchants.config.RootConfig;
import com.willfp.ecoenchants.config.YamlConfig;
import org.bukkit.Material;
import java.util.HashSet;
@@ -9,7 +9,7 @@ import java.util.Set;
/**
* Wrapper for config.yml
*/
public class Target extends RootConfig {
public class Target extends YamlConfig {
public Target() {
super("target");
}

View File

@@ -5,11 +5,10 @@ import com.willfp.ecoenchants.EcoEnchantsPlugin;
import com.willfp.ecoenchants.config.ConfigManager;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EnchantmentRarity;
import com.willfp.ecoenchants.enchantments.EnchantmentTarget;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentRarity;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentTarget;
import com.willfp.ecoenchants.util.NumberUtils;
import org.apache.commons.lang.WordUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
@@ -109,7 +108,7 @@ public final class EnchantDisplay {
* @return The item, updated
*/
public static ItemStack revertDisplay(ItemStack item) {
if(item == null || !EnchantmentTarget.ALL.contains(item.getType()) || item.getItemMeta() == null) return item;
if(item == null || !EnchantmentTarget.ALL.getMaterials().contains(item.getType()) || item.getItemMeta() == null) return item;
ItemMeta meta = item.getItemMeta();
List<String> itemLore;
@@ -147,7 +146,7 @@ public final class EnchantDisplay {
* @return The item, updated
*/
public static ItemStack displayEnchantments(ItemStack item) {
if(item == null || item.getItemMeta() == null || !EnchantmentTarget.ALL.contains(item.getType()) || item.getItemMeta().getPersistentDataContainer().has(KEY_SKIP, PersistentDataType.INTEGER))
if(item == null || item.getItemMeta() == null || !EnchantmentTarget.ALL.getMaterials().contains(item.getType()) || item.getItemMeta().getPersistentDataContainer().has(KEY_SKIP, PersistentDataType.INTEGER))
return item;
item = revertDisplay(item);

View File

@@ -2,6 +2,8 @@ package com.willfp.ecoenchants.enchantments;
import com.willfp.ecoenchants.config.ConfigManager;
import com.willfp.ecoenchants.config.configs.EnchantmentConfig;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentRarity;
import com.willfp.ecoenchants.util.Registerable;
import net.md_5.bungee.api.ChatColor;
import org.apache.commons.lang.WordUtils;
import org.bukkit.Material;
@@ -15,7 +17,7 @@ import java.lang.reflect.Field;
import java.util.*;
@SuppressWarnings("unchecked")
public abstract class EcoEnchant extends Enchantment implements Listener {
public abstract class EcoEnchant extends Enchantment implements Listener, Registerable {
private String name;
private String description;
private final String permissionName;
@@ -31,7 +33,7 @@ public abstract class EcoEnchant extends Enchantment implements Listener {
private int maxLvl;
private Set<Enchantment> conflicts;
private EnchantmentRarity rarity;
private Set<Material> target = new HashSet<>();
private final Set<Material> target = new HashSet<>();
private boolean enabled;
@@ -72,7 +74,12 @@ public abstract class EcoEnchant extends Enchantment implements Listener {
this.register();
}
private void register() {
/**
* Register the enchantment with spigot
* Only used internally
*/
@Override
public void register() {
try {
Field byIdField = Enchantment.class.getDeclaredField("byKey");
Field byNameField = Enchantment.class.getDeclaredField("byName");

View File

@@ -4,7 +4,7 @@ import com.willfp.ecoenchants.EcoEnchantsPlugin;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchantBuilder;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EcoRunnable;
import com.willfp.ecoenchants.util.EcoRunnable;
import com.willfp.ecoenchants.enchantments.util.checks.EnchantChecks;
import com.willfp.ecoenchants.util.VectorUtils;
import org.bukkit.entity.Entity;

View File

@@ -4,7 +4,7 @@ import com.willfp.ecoenchants.EcoEnchantsPlugin;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchantBuilder;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EcoRunnable;
import com.willfp.ecoenchants.util.EcoRunnable;
import com.willfp.ecoenchants.enchantments.util.checks.EnchantChecks;
import com.willfp.ecoenchants.util.ItemDurability;
import org.bukkit.inventory.ItemStack;

View File

@@ -4,7 +4,7 @@ import com.willfp.ecoenchants.EcoEnchantsPlugin;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchantBuilder;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EcoRunnable;
import com.willfp.ecoenchants.util.EcoRunnable;
import com.willfp.ecoenchants.enchantments.util.checks.EnchantChecks;
import com.willfp.ecoenchants.util.NumberUtils;
import org.bukkit.entity.Entity;

View File

@@ -4,7 +4,7 @@ import com.willfp.ecoenchants.EcoEnchantsPlugin;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchantBuilder;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EcoRunnable;
import com.willfp.ecoenchants.util.EcoRunnable;
import com.willfp.ecoenchants.enchantments.util.checks.EnchantChecks;
import com.willfp.ecoenchants.util.VectorUtils;
import org.bukkit.entity.Entity;

View File

@@ -4,7 +4,7 @@ import com.willfp.ecoenchants.EcoEnchantsPlugin;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchantBuilder;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EcoRunnable;
import com.willfp.ecoenchants.util.EcoRunnable;
import com.willfp.ecoenchants.enchantments.util.checks.EnchantChecks;
import com.willfp.ecoenchants.util.ItemDurability;
import org.bukkit.inventory.ItemStack;

View File

@@ -1,6 +1,7 @@
package com.willfp.ecoenchants.enchantments;
package com.willfp.ecoenchants.enchantments.meta;
import com.willfp.ecoenchants.config.ConfigManager;
import com.willfp.ecoenchants.util.Registerable;
import org.bukkit.ChatColor;
import java.util.HashSet;
@@ -10,7 +11,7 @@ import java.util.Set;
/**
* Class for storing all enchantment rarities
*/
public class EnchantmentRarity {
public class EnchantmentRarity implements Registerable {
private static final Set<EnchantmentRarity> rarities = new HashSet<>();
private final String name;
@@ -30,15 +31,18 @@ public class EnchantmentRarity {
* @param customColor The custom display color, or null if not enabled
*/
public EnchantmentRarity(String name, double probability, int minimumLevel, double villagerProbability, double lootProbability, String customColor) {
Optional<EnchantmentRarity> matching = rarities.stream().filter(rarity -> rarity.getName().equalsIgnoreCase(name)).findFirst();
matching.ifPresent(rarities::remove);
this.name = name;
this.probability = probability;
this.minimumLevel = minimumLevel;
this.villagerProbability = villagerProbability;
this.lootProbability = lootProbability;
this.customColor = customColor;
}
@Override
public void register() {
Optional<EnchantmentRarity> matching = rarities.stream().filter(rarity -> rarity.getName().equalsIgnoreCase(name)).findFirst();
matching.ifPresent(rarities::remove);
rarities.add(this);
}
@@ -126,7 +130,7 @@ public class EnchantmentRarity {
customColor = ChatColor.translateAlternateColorCodes('&', ConfigManager.getRarity().getString("rarities." + rarity + ".custom-color.color"));
}
new EnchantmentRarity(name, probability, minimumLevel, villagerProbability, lootProbability, customColor);
new EnchantmentRarity(name, probability, minimumLevel, villagerProbability, lootProbability, customColor).register();
});
}

View File

@@ -1,6 +1,8 @@
package com.willfp.ecoenchants.enchantments;
package com.willfp.ecoenchants.enchantments.meta;
import com.google.common.collect.ImmutableSet;
import com.willfp.ecoenchants.config.ConfigManager;
import com.willfp.ecoenchants.util.Registerable;
import org.bukkit.Material;
import java.util.HashSet;
@@ -10,9 +12,13 @@ import java.util.Set;
/**
* Class for storing all enchantment rarities
*/
public class EnchantmentTarget {
public class EnchantmentTarget implements Registerable {
private static final Set<EnchantmentTarget> targets = new HashSet<>();
public static final Set<Material> ALL = new HashSet<>();
public static final EnchantmentTarget ALL = new EnchantmentTarget("all", new HashSet<>());
static {
ALL.register();
}
private final String name;
private final Set<Material> materials;
@@ -23,27 +29,17 @@ public class EnchantmentTarget {
* @param materials The items for the target
*/
public EnchantmentTarget(String name, Set<Material> materials) {
this(name, materials, false);
}
/**
* Create new EnchantmentRarity
* @param name The name of the rarity
* @param materials The items for the target
* @param noRegister Dont register internally
*/
public EnchantmentTarget(String name, Set<Material> materials, boolean noRegister) {
Optional<EnchantmentTarget> matching = targets.stream().filter(rarity -> rarity.getName().equalsIgnoreCase(name)).findFirst();
matching.ifPresent(targets::remove);
matching.ifPresent(enchantmentTarget -> ALL.removeAll(enchantmentTarget.getMaterials()));
this.name = name;
this.materials = materials;
}
if(!noRegister) {
targets.add(this);
ALL.addAll(materials);
}
@Override
public void register() {
Optional<EnchantmentTarget> matching = targets.stream().filter(rarity -> rarity.getName().equalsIgnoreCase(name)).findFirst();
matching.ifPresent(targets::remove);
matching.ifPresent(enchantmentTarget -> ALL.materials.removeAll(enchantmentTarget.getMaterials()));
targets.add(this);
ALL.materials.addAll(this.getMaterials());
}
/**
@@ -59,7 +55,7 @@ public class EnchantmentTarget {
* @return The materials
*/
public Set<Material> getMaterials() {
return this.materials;
return ImmutableSet.copyOf(this.materials);
}
/**
@@ -68,8 +64,6 @@ public class EnchantmentTarget {
* @return The matching EnchantmentTarget, or null if not found
*/
public static EnchantmentTarget getByName(String name) {
if(name.equalsIgnoreCase("all")) return new EnchantmentTarget("all", EnchantmentTarget.ALL, true);
Optional<EnchantmentTarget> matching = targets.stream().filter(rarity -> rarity.getName().equalsIgnoreCase(name)).findFirst();
return matching.orElse(null);
}
@@ -80,11 +74,10 @@ public class EnchantmentTarget {
*/
public static void update() {
Set<String> targetNames = ConfigManager.getTarget().getTargets();
targetNames.forEach((target) -> {
String name = target;
Set<Material> materials = ConfigManager.getTarget().getTargetMaterials(target);
new EnchantmentTarget(name, materials);
ALL.getMaterials().clear();
targetNames.forEach((name) -> {
Set<Material> materials = ConfigManager.getTarget().getTargetMaterials(name);
new EnchantmentTarget(name, materials).register();
});
}

View File

@@ -3,7 +3,7 @@ package com.willfp.ecoenchants.listeners;
import com.willfp.ecoenchants.config.ConfigManager;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EnchantmentTarget;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentTarget;
import com.willfp.ecoenchants.util.NumberUtils;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
@@ -85,7 +85,7 @@ public class VillagerListeners implements Listener {
@EventHandler
public void onVillagerGainItemTrade(VillagerAcquireTradeEvent event) {
if(!EnchantmentTarget.ALL.contains(event.getRecipe().getResult().getType()))
if(!EnchantmentTarget.ALL.getMaterials().contains(event.getRecipe().getResult().getType()))
return;
if(event.getRecipe().getResult().getType().equals(Material.BOOK)) return;

View File

@@ -3,7 +3,6 @@ package com.willfp.ecoenchants.loader;
import com.comphenix.protocol.ProtocolLibrary;
import com.willfp.ecoenchants.EcoEnchantsPlugin;
import com.willfp.ecoenchants.anvil.AnvilListeners;
import com.willfp.ecoenchants.bstats.Metrics;
import com.willfp.ecoenchants.command.commands.CommandEcodebug;
import com.willfp.ecoenchants.command.commands.CommandEcoreload;
import com.willfp.ecoenchants.command.commands.CommandEcoskip;
@@ -14,7 +13,11 @@ import com.willfp.ecoenchants.display.packets.PacketOpenWindowMerchant;
import com.willfp.ecoenchants.display.packets.PacketSetCreativeSlot;
import com.willfp.ecoenchants.display.packets.PacketSetSlot;
import com.willfp.ecoenchants.display.packets.PacketWindowItems;
import com.willfp.ecoenchants.enchantments.*;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.util.EcoRunnable;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentRarity;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentTarget;
import com.willfp.ecoenchants.events.armorequip.ArmorListener;
import com.willfp.ecoenchants.events.armorequip.DispenserArmorListener;
import com.willfp.ecoenchants.events.entitydeathbyentity.EntityDeathByEntityListeners;
@@ -36,8 +39,10 @@ import com.willfp.ecoenchants.naturalloot.LootPopulator;
import com.willfp.ecoenchants.nms.BlockBreak;
import com.willfp.ecoenchants.nms.Cooldown;
import com.willfp.ecoenchants.nms.TridentStack;
import com.willfp.ecoenchants.util.Logger;
import com.willfp.ecoenchants.util.UpdateChecker;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.generator.BlockPopulator;
@@ -54,12 +59,12 @@ public class Loader {
* Called by {@link EcoEnchantsPlugin#onEnable()}
*/
public static void load() {
Bukkit.getLogger().info("==========================================");
Bukkit.getLogger().info("");
Bukkit.getLogger().info("Loading §aEcoEnchants");
Bukkit.getLogger().info("Made by §aAuxilor§f - willfp.com");
Bukkit.getLogger().info("");
Bukkit.getLogger().info("==========================================");
Logger.info("==========================================");
Logger.info("");
Logger.info("Loading §aEcoEnchants");
Logger.info("Made by §aAuxilor§f - willfp.com");
Logger.info("");
Logger.info("==========================================");
/*
Check for paper
@@ -72,16 +77,16 @@ public class Loader {
if (!isPapermc) {
Bukkit.getScheduler().runTaskLater(EcoEnchantsPlugin.getInstance(), () -> {
Bukkit.getLogger().info("");
Bukkit.getLogger().info("----------------------------");
Bukkit.getLogger().info("");
Bukkit.getLogger().severe("You don't seem to be running paper!");
Bukkit.getLogger().severe("Paper is strongly recommended for all servers,");
Bukkit.getLogger().severe("and enchantments like Drill may not function properly without it");
Bukkit.getLogger().severe("Download Paper from §fhttps://papermc.io");
Bukkit.getLogger().info("");
Bukkit.getLogger().info("----------------------------");
Bukkit.getLogger().info("");
Logger.info("");
Logger.info("----------------------------");
Logger.info("");
Logger.error("You don't seem to be running paper!");
Logger.error("Paper is strongly recommended for all servers,");
Logger.error("and enchantments like Drill may not function properly without it");
Logger.error("Download Paper from §fhttps://papermc.io");
Logger.info("");
Logger.info("----------------------------");
Logger.info("");
}, 1);
}
@@ -89,15 +94,15 @@ public class Loader {
Load Configs
*/
Bukkit.getLogger().info("Loading Configs...");
Logger.info("Loading Configs...");
ConfigManager.updateConfigs();
Bukkit.getLogger().info("");
Logger.info("");
/*
Load ProtocolLib
*/
Bukkit.getLogger().info("Loading ProtocolLib...");
Logger.info("Loading ProtocolLib...");
EcoEnchantsPlugin.getInstance().protocolManager = ProtocolLibrary.getProtocolManager();
new PacketOpenWindowMerchant().register();
new PacketSetCreativeSlot().register();
@@ -108,125 +113,125 @@ public class Loader {
Load land management support
*/
Bukkit.getLogger().info("Scheduling Integration Loading...");
Logger.info("Scheduling Integration Loading...");
Bukkit.getScheduler().runTaskLater(EcoEnchantsPlugin.getInstance(), () -> {
Bukkit.getLogger().info("Loading Integrations...");
Logger.info("Loading Integrations...");
if(Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) {
AntigriefManager.registerAntigrief(new AntigriefWorldGuard());
Bukkit.getLogger().info("WorldGuard: §aENABLED");
Logger.info("WorldGuard: §aENABLED");
} else {
Bukkit.getLogger().info("WorldGuard: §9DISABLED");
Logger.info("WorldGuard: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("GriefPrevention")) {
AntigriefManager.registerAntigrief(new AntigriefGriefPrevention());
Bukkit.getLogger().info("GriefPrevention: §aENABLED");
Logger.info("GriefPrevention: §aENABLED");
} else {
Bukkit.getLogger().info("GriefPrevention: §9DISABLED");
Logger.info("GriefPrevention: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("FactionsUUID")) {
AntigriefManager.registerAntigrief(new AntigriefFactionsUUID());
Bukkit.getLogger().info("FactionsUUID: §aENABLED");
Logger.info("FactionsUUID: §aENABLED");
} else {
Bukkit.getLogger().info("FactionsUUID: §9DISABLED");
Logger.info("FactionsUUID: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("Towny")) {
AntigriefManager.registerAntigrief(new AntigriefTowny());
Bukkit.getLogger().info("Towny: §aENABLED");
Logger.info("Towny: §aENABLED");
} else {
Bukkit.getLogger().info("Towny: §9DISABLED");
Logger.info("Towny: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("Lands")) {
AntigriefManager.registerAntigrief(new AntigriefLands());
Bukkit.getLogger().info("Lands: §aENABLED");
Logger.info("Lands: §aENABLED");
} else {
Bukkit.getLogger().info("Lands: §9DISABLED");
Logger.info("Lands: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("Essentials")) {
EssentialsManager.registerAntigrief(new IntegrationEssentials());
Bukkit.getLogger().info("Essentials: §aENABLED");
Logger.info("Essentials: §aENABLED");
} else {
Bukkit.getLogger().info("Essentials: §9DISABLED");
Logger.info("Essentials: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("AAC")) {
AnticheatManager.registerAnticheat(new AnticheatAAC());
Bukkit.getLogger().info("AAC: §aENABLED");
Logger.info("AAC: §aENABLED");
} else {
Bukkit.getLogger().info("AAC: §9DISABLED");
Logger.info("AAC: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("Matrix")) {
AnticheatManager.registerAnticheat(new AnticheatMatrix());
Bukkit.getLogger().info("Matrix: §aENABLED");
Logger.info("Matrix: §aENABLED");
} else {
Bukkit.getLogger().info("Matrix: §9DISABLED");
Logger.info("Matrix: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("NoCheatPlus")) {
AnticheatManager.registerAnticheat(new AnticheatAAC());
Bukkit.getLogger().info("NCP: §aENABLED");
Logger.info("NCP: §aENABLED");
} else {
Bukkit.getLogger().info("NCP: §9DISABLED");
Logger.info("NCP: §9DISABLED");
}
if(Bukkit.getPluginManager().isPluginEnabled("Spartan")) {
AnticheatManager.registerAnticheat(new AnticheatAAC());
Bukkit.getLogger().info("Spartan: §aENABLED");
Logger.info("Spartan: §aENABLED");
} else {
Bukkit.getLogger().info("Spartan: §9DISABLED");
Logger.info("Spartan: §9DISABLED");
}
Bukkit.getLogger().info("");
Logger.info("");
}, 1);
Bukkit.getLogger().info("");
Logger.info("");
/*
Load NMS
*/
Bukkit.getLogger().info("Loading NMS APIs...");
Logger.info("Loading NMS APIs...");
if(Cooldown.init()) {
Bukkit.getLogger().info("Cooldown: §aSUCCESS");
Logger.info("Cooldown: §aSUCCESS");
} else {
Bukkit.getLogger().info("Cooldown: §cFAILURE");
Bukkit.getLogger().severe("§cAborting...");
Logger.info("Cooldown: §cFAILURE");
Logger.error("§cAborting...");
Bukkit.getPluginManager().disablePlugin(EcoEnchantsPlugin.getInstance());
}
if(TridentStack.init()) {
Bukkit.getLogger().info("Trident API: §aSUCCESS");
Logger.info("Trident API: §aSUCCESS");
} else {
Bukkit.getLogger().info("Trident API: §cFAILURE");
Bukkit.getLogger().severe("§cAborting...");
Logger.info("Trident API: §cFAILURE");
Logger.error("§cAborting...");
Bukkit.getPluginManager().disablePlugin(EcoEnchantsPlugin.getInstance());
}
if(BlockBreak.init()) {
Bukkit.getLogger().info("Block Break: §aSUCCESS");
Logger.info("Block Break: §aSUCCESS");
} else {
Bukkit.getLogger().info("Block Break: §cFAILURE");
Bukkit.getLogger().severe("§cAborting...");
Logger.info("Block Break: §cFAILURE");
Logger.error("§cAborting...");
Bukkit.getPluginManager().disablePlugin(EcoEnchantsPlugin.getInstance());
}
Bukkit.getLogger().info("");
Logger.info("");
/*
Register Events
*/
Bukkit.getLogger().info("Registering Events...");
Logger.info("Registering Events...");
Bukkit.getPluginManager().registerEvents(new ArmorListener(), EcoEnchantsPlugin.getInstance());
Bukkit.getPluginManager().registerEvents(new DispenserArmorListener(), EcoEnchantsPlugin.getInstance());
Bukkit.getPluginManager().registerEvents(new PlayerJoinListener(), EcoEnchantsPlugin.getInstance());
@@ -237,162 +242,149 @@ public class Loader {
Bukkit.getPluginManager().registerEvents(new NaturalExpGainListeners(), EcoEnchantsPlugin.getInstance());
Bukkit.getPluginManager().registerEvents(new VillagerListeners(), EcoEnchantsPlugin.getInstance());
Bukkit.getPluginManager().registerEvents(new ArrowListeners(), EcoEnchantsPlugin.getInstance());
Bukkit.getLogger().info("");
Logger.info("");
/*
Add Block Populators
*/
Bukkit.getLogger().info("Scheduling Adding Block Populators...");
Logger.info("Scheduling Adding Block Populators...");
Bukkit.getScheduler().runTaskLater(EcoEnchantsPlugin.getInstance(), () -> {
Bukkit.getServer().getWorlds().forEach((world -> {
world.getPopulators().add(new LootPopulator());
}));
}, 1);
Bukkit.getLogger().info("");
Logger.info("");
/*
Load Extensions
*/
Bukkit.getLogger().info("Loading Extensions...");
Logger.info("Loading Extensions...");
ExtensionManager.loadExtensions();
if(ExtensionManager.getLoadedExtensions().isEmpty()) {
Bukkit.getLogger().info("§cNo extensions found");
Logger.info("§cNo extensions found");
} else {
Bukkit.getLogger().info("Extensions Loaded:");
Logger.info("Extensions Loaded:");
ExtensionManager.getLoadedExtensions().forEach((extension, name) -> {
Bukkit.getLogger().info("- " + name);
Logger.info("- " + name);
});
}
Bukkit.getLogger().info("");
Logger.info("");
/*
Create enchantment config files (for first time use)
*/
Bukkit.getLogger().info("Creating Enchantment Configs...");
Logger.info("Creating Enchantment Configs...");
ConfigManager.updateEnchantmentConfigs();
Bukkit.getLogger().info("");
Logger.info("");
/*
Load all enchantments, rarities, and targets
*/
Bukkit.getLogger().info("Adding Enchantments to API...");
Logger.info("Adding Enchantments to API...");
EnchantmentRarity.update();
EnchantmentTarget.update();
if(EnchantmentRarity.getAll().size() == 0 || EnchantmentTarget.getAll().size() == 0) {
Bukkit.getLogger().severe("§cError loading rarities or targets! Aborting...");
Logger.error("§cError loading rarities or targets! Aborting...");
Bukkit.getPluginManager().disablePlugin(EcoEnchantsPlugin.getInstance());
return;
} else {
Bukkit.getLogger().info(EnchantmentRarity.getAll().size() + " Rarities Loaded:");
Logger.info(EnchantmentRarity.getAll().size() + " Rarities Loaded:");
EnchantmentRarity.getAll().forEach((rarity -> {
Bukkit.getLogger().info("- " + rarity.getName() + ": Table Probability=" + rarity.getProbability() + ", Minimum Level=" + rarity.getMinimumLevel() + ", Villager Probability=" + rarity.getVillagerProbability() + ", Loot Probability=" + rarity.getLootProbability() + ", Has Custom Color=" + rarity.hasCustomColor());
Logger.info("- " + rarity.getName() + ": Table Probability=" + rarity.getProbability() + ", Minimum Level=" + rarity.getMinimumLevel() + ", Villager Probability=" + rarity.getVillagerProbability() + ", Loot Probability=" + rarity.getLootProbability() + ", Has Custom Color=" + rarity.hasCustomColor());
}));
Bukkit.getLogger().info("");
Logger.info("");
Bukkit.getLogger().info(EnchantmentTarget.getAll().size() + " Targets Loaded:");
Logger.info(EnchantmentTarget.getAll().size() + " Targets Loaded:");
EnchantmentTarget.getAll().forEach((target) -> {
Bukkit.getLogger().info("- " + target.getName() + ": Materials=" + target.getMaterials().toString());
Logger.info("- " + target.getName() + ": Materials=" + target.getMaterials().toString());
});
}
Bukkit.getLogger().info("");
Logger.info("");
if (EcoEnchants.getAll().size() == 0) {
Bukkit.getLogger().severe("§cError adding enchantments! Aborting...");
Logger.error("§cError adding enchantments! Aborting...");
Bukkit.getPluginManager().disablePlugin(EcoEnchantsPlugin.getInstance());
return;
} else {
Bukkit.getLogger().info(EcoEnchants.getAll().size() + " Enchantments Loaded:");
Logger.info(EcoEnchants.getAll().size() + " Enchantments Loaded:");
EcoEnchants.getAll().forEach((ecoEnchant -> {
if(ecoEnchant.getType().equals(EcoEnchant.EnchantmentType.SPECIAL)) {
Bukkit.getLogger().info(ChatColor.translateAlternateColorCodes('&', ConfigManager.getLang().getString("special-color")) + "- " + ecoEnchant.getName() + ": " + ecoEnchant.getKey().toString());
Logger.info(ChatColor.translateAlternateColorCodes('&', ConfigManager.getLang().getString("special-color")) + "- " + ecoEnchant.getName() + ": " + ecoEnchant.getKey().toString());
} else if(ecoEnchant.getType().equals(EcoEnchant.EnchantmentType.ARTIFACT)) {
Bukkit.getLogger().info(ChatColor.translateAlternateColorCodes('&', ConfigManager.getLang().getString("artifact-color")) + "- " + ecoEnchant.getName() + ": " + ecoEnchant.getKey().toString());
Logger.info(ChatColor.translateAlternateColorCodes('&', ConfigManager.getLang().getString("artifact-color")) + "- " + ecoEnchant.getName() + ": " + ecoEnchant.getKey().toString());
} else {
Bukkit.getLogger().info("- " + ecoEnchant.getName() + ": " + ecoEnchant.getKey().toString());
Logger.info("- " + ecoEnchant.getName() + ": " + ecoEnchant.getKey().toString());
}
}));
}
Bukkit.getLogger().info("");
Logger.info("");
/*
Load enchantment configs
*/
Bukkit.getLogger().info("Loading Enchantment Configs...");
Logger.info("Loading Enchantment Configs...");
ConfigManager.updateEnchantmentConfigs();
Bukkit.getLogger().info("");
/*
Plugin Conflicts
*/
Bukkit.getLogger().info("Checking Plugin Conflicts...");
if(Bukkit.getPluginManager().getPlugin("EnchantmentNumbers") != null) {
Bukkit.getPluginManager().disablePlugin(Bukkit.getPluginManager().getPlugin("EnchantmentNumbers"));
Bukkit.getLogger().severe("EnchantmentNumbers conflicts with EcoEnchants");
Bukkit.getLogger().severe("It has been disabled. Please uninstall it!");
}
Bukkit.getLogger().info("");
Logger.info("");
/*
Register Enchantments
*/
Bukkit.getLogger().info("Registering Enchantments...");
Logger.info("Registering Enchantments...");
EcoEnchants.update();
EnchantDisplay.update();
Bukkit.getLogger().info("");
Logger.info("");
/*
Register Enchantment Listeners
*/
Bukkit.getLogger().info("Registering Enchantment Listeners...");
Logger.info("Registering Enchantment Listeners...");
EcoEnchants.getAll().forEach((ecoEnchant -> {
if(ecoEnchant.isEnabled()) {
Bukkit.getPluginManager().registerEvents(ecoEnchant, EcoEnchantsPlugin.getInstance());
}
}));
Bukkit.getLogger().info("");
Logger.info("");
/*
Register Enchantment Tasks
*/
Bukkit.getLogger().info("Registering Enchantment Tasks...");
Logger.info("Registering Enchantment Tasks...");
EcoEnchants.getAll().forEach((ecoEnchant -> {
if(ecoEnchant instanceof EcoRunnable) {
Bukkit.getScheduler().scheduleSyncRepeatingTask(EcoEnchantsPlugin.getInstance(), (Runnable) ecoEnchant, 5, ((EcoRunnable) ecoEnchant).getTime());
}
}));
Bukkit.getLogger().info("");
Logger.info("");
/*
Load Commands
*/
Bukkit.getLogger().info("Loading Commands...");
Logger.info("Loading Commands...");
Bukkit.getPluginCommand("ecoreload").setExecutor(new CommandEcoreload());
Bukkit.getPluginCommand("ecodebug").setExecutor(new CommandEcodebug());
Bukkit.getPluginCommand("enchantinfo").setExecutor(new CommandEnchantinfo());
Bukkit.getPluginCommand("ecoskip").setExecutor(new CommandEcoskip());
Bukkit.getLogger().info("");
Logger.info("");
/*
Start bStats
*/
Bukkit.getLogger().info("Hooking into bStats...");
Logger.info("Hooking into bStats...");
new Metrics(EcoEnchantsPlugin.getInstance(), 7666);
Bukkit.getLogger().info("");
Logger.info("");
/*
Start update checker
@@ -402,39 +394,39 @@ public class Loader {
new UpdateChecker(EcoEnchantsPlugin.getInstance(), 79573).getVersion((version) -> {
DefaultArtifactVersion currentVersion = new DefaultArtifactVersion(EcoEnchantsPlugin.getInstance().getDescription().getVersion());
DefaultArtifactVersion mostRecentVersion = new DefaultArtifactVersion(version);
Bukkit.getLogger().info("----------------------------");
Bukkit.getLogger().info("");
Bukkit.getLogger().info("EcoEnchants Updater");
Bukkit.getLogger().info("");
Logger.info("----------------------------");
Logger.info("");
Logger.info("EcoEnchants Updater");
Logger.info("");
if (currentVersion.compareTo(mostRecentVersion) > 0 || currentVersion.equals(mostRecentVersion)) {
Bukkit.getLogger().info("§aEcoEnchants is up to date! (Version " + EcoEnchantsPlugin.getInstance().getDescription().getVersion() + ")");
Logger.info("§aEcoEnchants is up to date! (Version " + EcoEnchantsPlugin.getInstance().getDescription().getVersion() + ")");
} else {
EcoEnchantsPlugin.outdated = true;
EcoEnchantsPlugin.newVersion = version;
Bukkit.getScheduler().runTaskTimer(EcoEnchantsPlugin.getInstance(), () -> {
Bukkit.getLogger().info("§6EcoEnchants is out of date! (Version " + EcoEnchantsPlugin.getInstance().getDescription().getVersion() + ")");
Bukkit.getLogger().info("§6The newest version is §f" + version);
Bukkit.getLogger().info("§6Download the new version here: §fhttps://www.spigotmc.org/resources/ecoenchants.79573/");
Logger.info("§6EcoEnchants is out of date! (Version " + EcoEnchantsPlugin.getInstance().getDescription().getVersion() + ")");
Logger.info("§6The newest version is §f" + version);
Logger.info("§6Download the new version here: §fhttps://www.spigotmc.org/resources/ecoenchants.79573/");
}, 0, 36000);
}
Bukkit.getLogger().info("");
Bukkit.getLogger().info("----------------------------");
Logger.info("");
Logger.info("----------------------------");
});
/*
Finish
*/
Bukkit.getLogger().info("Loaded §aEcoEnchants!");
Logger.info("Loaded §aEcoEnchants!");
}
/**
* Called by {@link EcoEnchantsPlugin#onDisable()}
*/
public static void unload() {
Bukkit.getLogger().info("§cDisabling EcoEnchants...");
Bukkit.getLogger().info("Removing Block Populators...");
Logger.info("§cDisabling EcoEnchants...");
Logger.info("Removing Block Populators...");
Bukkit.getServer().getWorlds().forEach((world -> {
List<BlockPopulator> populators = new ArrayList<>(world.getPopulators());
populators.forEach((blockPopulator -> {
@@ -443,9 +435,9 @@ public class Loader {
}
}));
}));
Bukkit.getLogger().info("");
Bukkit.getLogger().info("§cUnloading Extensions...");
Logger.info("");
Logger.info("§cUnloading Extensions...");
ExtensionManager.unloadExtensions();
Bukkit.getLogger().info("§fBye! :)");
Logger.info("§fBye! :)");
}
}

View File

@@ -3,7 +3,7 @@ package com.willfp.ecoenchants.naturalloot;
import com.willfp.ecoenchants.config.ConfigManager;
import com.willfp.ecoenchants.enchantments.EcoEnchant;
import com.willfp.ecoenchants.enchantments.EcoEnchants;
import com.willfp.ecoenchants.enchantments.EnchantmentTarget;
import com.willfp.ecoenchants.enchantments.meta.EnchantmentTarget;
import com.willfp.ecoenchants.util.NumberUtils;
import org.bukkit.Chunk;
import org.bukkit.Material;
@@ -39,7 +39,7 @@ public class LootPopulator extends BlockPopulator {
for(ItemStack item : inventory) {
if(item == null) continue;
if(!EnchantmentTarget.ALL.contains(item.getType())) continue;
if(!EnchantmentTarget.ALL.getMaterials().contains(item.getType())) continue;
if(item.getType().equals(Material.BOOK)) continue;
HashMap<Enchantment, Integer> toAdd = new HashMap<>();

View File

@@ -1,4 +1,4 @@
package com.willfp.ecoenchants.enchantments;
package com.willfp.ecoenchants.util;
/**
* Interface for Enchantments with tasks

View File

@@ -0,0 +1,17 @@
package com.willfp.ecoenchants.util;
import com.willfp.ecoenchants.EcoEnchantsPlugin;
public class Logger {
public static void info(String message) {
EcoEnchantsPlugin.getInstance().getLogger().info(StringUtils.translate(message));
}
public static void warn(String message) {
EcoEnchantsPlugin.getInstance().getLogger().warning(StringUtils.translate(message));
}
public static void error(String message) {
EcoEnchantsPlugin.getInstance().getLogger().severe(StringUtils.translate(message));
}
}

View File

@@ -0,0 +1,5 @@
package com.willfp.ecoenchants.util;
public interface Registerable {
void register();
}

View File

@@ -0,0 +1,9 @@
package com.willfp.ecoenchants.util;
import net.md_5.bungee.api.ChatColor;
public class StringUtils {
public static String translate(String message){
return ChatColor.translateAlternateColorCodes('&', message);
}
}