mirror of
https://github.com/songoda/SongodaCore.git
synced 2024-11-30 05:53:35 +01:00
refactor: Refactors a couple of classes by applying our code style
This commit is contained in:
parent
8c06a740d5
commit
dce7adf81f
@ -20,7 +20,7 @@ public final class CoreLogger extends Logger {
|
|||||||
LogManager.getLogManager().addLogger(this);
|
LogManager.getLogManager().addLogger(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void setPlugin(Plugin plugin) {
|
void setPlugin(Plugin plugin) {
|
||||||
this.pluginPrefix = "[" + plugin.getName() + "] ";
|
this.pluginPrefix = "[" + plugin.getName() + "] ";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -224,7 +224,7 @@ public class SongodaCore {
|
|||||||
this.loginListener = null;
|
this.loginListener = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ArrayList<BukkitTask> tasks = new ArrayList<>();
|
private final ArrayList<BukkitTask> tasks = new ArrayList<>();
|
||||||
|
|
||||||
private void register(JavaPlugin plugin, int pluginID, String icon, String libraryVersion) {
|
private void register(JavaPlugin plugin, int pluginID, String icon, String libraryVersion) {
|
||||||
getLogger().info(getPrefix() + "Hooked " + plugin.getName() + ".");
|
getLogger().info(getPrefix() + "Hooked " + plugin.getName() + ".");
|
||||||
|
@ -71,7 +71,7 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
|||||||
public abstract List<Config> getExtraConfig();
|
public abstract List<Config> getExtraConfig();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public FileConfiguration getConfig() {
|
public @NotNull FileConfiguration getConfig() {
|
||||||
return this.config.getFileConfig();
|
return this.config.getFileConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -172,7 +172,6 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start Metrics
|
|
||||||
Metrics.start(this);
|
Metrics.start(this);
|
||||||
} catch (Throwable th) {
|
} catch (Throwable th) {
|
||||||
criticalErrorOnPluginStartup(th);
|
criticalErrorOnPluginStartup(th);
|
||||||
@ -225,7 +224,6 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
|||||||
* @param localeName locale to use, eg "en_US"
|
* @param localeName locale to use, eg "en_US"
|
||||||
* @param reload optionally reload the loaded locale if the locale didn't
|
* @param reload optionally reload the loaded locale if the locale didn't
|
||||||
* change
|
* change
|
||||||
*
|
|
||||||
* @return true if the locale exists and was loaded successfully
|
* @return true if the locale exists and was loaded successfully
|
||||||
*/
|
*/
|
||||||
public boolean setLocale(String localeName, boolean reload) {
|
public boolean setLocale(String localeName, boolean reload) {
|
||||||
@ -233,9 +231,9 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
|||||||
return !reload || this.locale.reloadMessages();
|
return !reload || this.locale.reloadMessages();
|
||||||
}
|
}
|
||||||
|
|
||||||
Locale l = Locale.loadLocale(this, localeName);
|
Locale loadedLocale = Locale.loadLocale(this, localeName);
|
||||||
if (l != null) {
|
if (loadedLocale != null) {
|
||||||
this.locale = l;
|
this.locale = loadedLocale;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -249,23 +247,23 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs one or multiple errors that occurred during plugin startup and calls {@link #emergencyStop()} afterwards
|
* Logs one or multiple errors that occurred during plugin startup and calls {@link #emergencyStop()} afterward
|
||||||
*
|
*
|
||||||
* @param th The error(s) that occurred
|
* @param throwable The error(s) that occurred
|
||||||
*/
|
*/
|
||||||
protected void criticalErrorOnPluginStartup(Throwable th) {
|
protected void criticalErrorOnPluginStartup(Throwable throwable) {
|
||||||
Bukkit.getLogger().log(Level.SEVERE,
|
Bukkit.getLogger().log(Level.SEVERE,
|
||||||
String.format(
|
String.format(
|
||||||
"Unexpected error while loading %s v%s (core v%s): Disabling plugin!",
|
"Unexpected error while loading %s v%s (core v%s): Disabling plugin!",
|
||||||
getDescription().getName(),
|
getDescription().getName(),
|
||||||
getDescription().getVersion(),
|
getDescription().getVersion(),
|
||||||
SongodaCore.getVersion()
|
SongodaCore.getVersion()
|
||||||
), th);
|
), throwable);
|
||||||
|
|
||||||
emergencyStop();
|
emergencyStop();
|
||||||
}
|
}
|
||||||
|
|
||||||
//New database stuff
|
// New database stuff
|
||||||
public Config getDatabaseConfig() {
|
public Config getDatabaseConfig() {
|
||||||
File databaseFile = new File(getDataFolder(), "database.yml");
|
File databaseFile = new File(getDataFolder(), "database.yml");
|
||||||
if (!databaseFile.exists()) {
|
if (!databaseFile.exists()) {
|
||||||
@ -316,13 +314,13 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (this.dataManager.getDatabaseConnector().isInitialized()) {
|
if (this.dataManager.getDatabaseConnector().isInitialized()) {
|
||||||
//Check if the type is SQLite
|
// Check if the type is SQLite
|
||||||
if (this.dataManager.getDatabaseConnector().getType() == DatabaseType.SQLITE) {
|
if (this.dataManager.getDatabaseConnector().getType() == DatabaseType.SQLITE) {
|
||||||
//Let's convert it to H2
|
// Let's convert it to H2
|
||||||
try {
|
try {
|
||||||
DataManager newDataManager = DataMigration.convert(this, DatabaseType.H2);
|
DataManager newDataManager = DataMigration.convert(this, DatabaseType.H2);
|
||||||
if (newDataManager != null && newDataManager.getDatabaseConnector().isInitialized()) {
|
if (newDataManager != null && newDataManager.getDatabaseConnector().isInitialized()) {
|
||||||
//Set the new data manager
|
// Set the new data manager
|
||||||
setDataManager(newDataManager);
|
setDataManager(newDataManager);
|
||||||
}
|
}
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
|
@ -23,30 +23,31 @@ import java.util.LinkedList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class AdventureUtils {
|
public class AdventureUtils {
|
||||||
|
|
||||||
private static Method displayNameMethod = null;
|
private static Method displayNameMethod = null;
|
||||||
private static Method loreMethod = null;
|
private static Method loreMethod = null;
|
||||||
private static Class<?> componentClass;
|
|
||||||
private static Object gsonComponentSerializer;
|
private static Object gsonComponentSerializer;
|
||||||
private static Method gsonDeserializeMethod;
|
private static Method gsonDeserializeMethod;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
if (ServerProject.isServer(ServerProject.PAPER) && ServerVersion.isServerVersionAtLeast(ServerVersion.V1_18)) {
|
if (ServerProject.isServer(ServerProject.PAPER) && ServerVersion.isServerVersionAtLeast(ServerVersion.V1_18)) {
|
||||||
try {
|
try {
|
||||||
componentClass = Class.forName("net;kyori;adventure;text;Component".replace(";", "."));
|
Class<?> componentClass = Class.forName("net;kyori;adventure;text;Component".replace(";", "."));
|
||||||
displayNameMethod = ItemMeta.class.getDeclaredMethod("displayName", componentClass);
|
displayNameMethod = ItemMeta.class.getDeclaredMethod("displayName", componentClass);
|
||||||
loreMethod = ItemMeta.class.getDeclaredMethod("lore", List.class);
|
loreMethod = ItemMeta.class.getDeclaredMethod("lore", List.class);
|
||||||
gsonComponentSerializer = Class.forName("net;kyori;adventure;text;serializer;gson;GsonComponentSerializer".replace(";", ".")).getDeclaredMethod("gson").invoke(null);
|
gsonComponentSerializer = Class.forName("net;kyori;adventure;text;serializer;gson;GsonComponentSerializer".replace(";", ".")).getDeclaredMethod("gson").invoke(null);
|
||||||
gsonDeserializeMethod = gsonComponentSerializer.getClass().getDeclaredMethod("deserialize", String.class);
|
gsonDeserializeMethod = gsonComponentSerializer.getClass().getDeclaredMethod("deserialize", String.class);
|
||||||
gsonDeserializeMethod.setAccessible(true);
|
gsonDeserializeMethod.setAccessible(true);
|
||||||
|
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a shaded component to a json string
|
* Convert a shaded component to a json string
|
||||||
|
*
|
||||||
* @param component The shaded Component to convert
|
* @param component The shaded Component to convert
|
||||||
|
*
|
||||||
* @return Json string
|
* @return Json string
|
||||||
*/
|
*/
|
||||||
public static String convertToJson(Component component) {
|
public static String convertToJson(Component component) {
|
||||||
@ -56,14 +57,16 @@ public class AdventureUtils {
|
|||||||
/**
|
/**
|
||||||
* Convert a json string to the non-shaded component
|
* Convert a json string to the non-shaded component
|
||||||
* Cast it to the correct type
|
* Cast it to the correct type
|
||||||
|
*
|
||||||
* @param json Json string
|
* @param json Json string
|
||||||
|
*
|
||||||
* @return Non-shaded component
|
* @return Non-shaded component
|
||||||
*/
|
*/
|
||||||
public static Object convertToOriginalComponent(String json) {
|
public static Object convertToOriginalComponent(String json) {
|
||||||
try {
|
try {
|
||||||
return gsonDeserializeMethod.invoke(gsonComponentSerializer, json);
|
return gsonDeserializeMethod.invoke(gsonComponentSerializer, json);
|
||||||
} catch (Exception e) {
|
} catch (Exception ex) {
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -71,14 +74,16 @@ public class AdventureUtils {
|
|||||||
/**
|
/**
|
||||||
* Convert the shaded Component to the original one
|
* Convert the shaded Component to the original one
|
||||||
* Cast it to the correct type
|
* Cast it to the correct type
|
||||||
|
*
|
||||||
* @param component Shaded component
|
* @param component Shaded component
|
||||||
|
*
|
||||||
* @return Original component
|
* @return Original component
|
||||||
*/
|
*/
|
||||||
public static Object convertToOriginalComponent(Component component) {
|
public static Object convertToOriginalComponent(Component component) {
|
||||||
try {
|
try {
|
||||||
return gsonDeserializeMethod.invoke(gsonComponentSerializer, convertToJson(component));
|
return gsonDeserializeMethod.invoke(gsonComponentSerializer, convertToJson(component));
|
||||||
} catch (Exception e) {
|
} catch (Exception ex) {
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -86,18 +91,20 @@ public class AdventureUtils {
|
|||||||
/**
|
/**
|
||||||
* Convert a list of shaded components to a list of original components
|
* Convert a list of shaded components to a list of original components
|
||||||
* Cast it to the correct type
|
* Cast it to the correct type
|
||||||
* @param component List of shaded components
|
*
|
||||||
|
* @param components List of shaded components
|
||||||
|
*
|
||||||
* @return List of original components
|
* @return List of original components
|
||||||
*/
|
*/
|
||||||
public static Object convertToOriginalComponent(List<Component> component) {
|
public static Object convertToOriginalComponent(List<Component> components) {
|
||||||
try {
|
try {
|
||||||
LinkedList<Object> list = new LinkedList<>();
|
LinkedList<Object> list = new LinkedList<>();
|
||||||
for (Component c : component) {
|
for (Component component : components) {
|
||||||
list.add(convertToOriginalComponent(c));
|
list.add(convertToOriginalComponent(component));
|
||||||
}
|
}
|
||||||
return list;
|
return list;
|
||||||
} catch (Exception e) {
|
} catch (Exception ex) {
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -105,18 +112,20 @@ public class AdventureUtils {
|
|||||||
/**
|
/**
|
||||||
* Convert a list of shaded components to a list of original components
|
* Convert a list of shaded components to a list of original components
|
||||||
* Cast it to the correct type
|
* Cast it to the correct type
|
||||||
* @param component List of shaded components
|
*
|
||||||
|
* @param components List of shaded components
|
||||||
|
*
|
||||||
* @return List of original components
|
* @return List of original components
|
||||||
*/
|
*/
|
||||||
public static Object convertToOriginalComponent(Component... component) {
|
public static Object convertToOriginalComponent(Component... components) {
|
||||||
try {
|
try {
|
||||||
LinkedList<Object> list = new LinkedList<>();
|
LinkedList<Object> list = new LinkedList<>();
|
||||||
for (Component c : component) {
|
for (Component component : components) {
|
||||||
list.add(convertToOriginalComponent(c));
|
list.add(convertToOriginalComponent(component));
|
||||||
}
|
}
|
||||||
return list;
|
return list;
|
||||||
} catch (Exception e) {
|
} catch (Exception ex) {
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -160,14 +169,18 @@ public class AdventureUtils {
|
|||||||
|
|
||||||
private static void setItemName(ItemStack item, Component name) {
|
private static void setItemName(ItemStack item, Component name) {
|
||||||
ItemMeta meta = item.getItemMeta();
|
ItemMeta meta = item.getItemMeta();
|
||||||
if (meta == null) return;
|
if (meta == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (isMiniMessageEnabled()) {
|
if (isMiniMessageEnabled()) {
|
||||||
//Set name as component
|
//Set name as a component
|
||||||
try {
|
try {
|
||||||
displayNameMethod.invoke(meta, convertToOriginalComponent(name));
|
displayNameMethod.invoke(meta, convertToOriginalComponent(name));
|
||||||
item.setItemMeta(meta);
|
item.setItemMeta(meta);
|
||||||
return;
|
return;
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
meta.setDisplayName(toLegacy(name));
|
meta.setDisplayName(toLegacy(name));
|
||||||
item.setItemMeta(meta);
|
item.setItemMeta(meta);
|
||||||
@ -176,19 +189,21 @@ public class AdventureUtils {
|
|||||||
private static void setItemLore(ItemStack item, Component... lore) {
|
private static void setItemLore(ItemStack item, Component... lore) {
|
||||||
ItemMeta meta = item.getItemMeta();
|
ItemMeta meta = item.getItemMeta();
|
||||||
if (meta == null) return;
|
if (meta == null) return;
|
||||||
|
|
||||||
if (isMiniMessageEnabled()) {
|
if (isMiniMessageEnabled()) {
|
||||||
//Set lore as component
|
//Set lore as component
|
||||||
try {
|
try {
|
||||||
loreMethod.invoke(meta, convertToOriginalComponent(lore));
|
loreMethod.invoke(meta, convertToOriginalComponent(lore));
|
||||||
item.setItemMeta(meta);
|
item.setItemMeta(meta);
|
||||||
return;
|
return;
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
meta.setLore(toLegacy(lore));
|
meta.setLore(toLegacy(lore));
|
||||||
item.setItemMeta(meta);
|
item.setItemMeta(meta);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Formatting stuff
|
// Formatting stuff
|
||||||
public static Component formatComponent(String text) {
|
public static Component formatComponent(String text) {
|
||||||
MiniMessage miniMessage = MiniMessage.builder().build();
|
MiniMessage miniMessage = MiniMessage.builder().build();
|
||||||
Component component = MiniMessage.miniMessage().deserialize(replaceLegacy(text));
|
Component component = MiniMessage.miniMessage().deserialize(replaceLegacy(text));
|
||||||
@ -198,7 +213,7 @@ public class AdventureUtils {
|
|||||||
return component;
|
return component;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Component formatComponent(String text, MiniMessagePlaceholder...placeholders) {
|
public static Component formatComponent(String text, MiniMessagePlaceholder... placeholders) {
|
||||||
MiniMessage miniMessage = MiniMessage.builder().editTags(builder -> {
|
MiniMessage miniMessage = MiniMessage.builder().editTags(builder -> {
|
||||||
Arrays.stream(placeholders).forEach(placeholder ->
|
Arrays.stream(placeholders).forEach(placeholder ->
|
||||||
builder.resolver(Placeholder.parsed(placeholder.getPlaceholder(), placeholder.getValue()))
|
builder.resolver(Placeholder.parsed(placeholder.getPlaceholder(), placeholder.getValue()))
|
||||||
@ -223,7 +238,7 @@ public class AdventureUtils {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<Component> formatComponent(String...list) {
|
public static List<Component> formatComponent(String... list) {
|
||||||
List<Component> result = new ArrayList<>();
|
List<Component> result = new ArrayList<>();
|
||||||
for (String line : list) {
|
for (String line : list) {
|
||||||
result.add(formatComponent(line));
|
result.add(formatComponent(line));
|
||||||
@ -320,7 +335,10 @@ public class AdventureUtils {
|
|||||||
|
|
||||||
public static String getColor(char c) {
|
public static String getColor(char c) {
|
||||||
ChatColor color = ChatColor.getByChar(c);
|
ChatColor color = ChatColor.getByChar(c);
|
||||||
if (color == null) return null;
|
if (color == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
switch (c) {
|
switch (c) {
|
||||||
case '0':
|
case '0':
|
||||||
return "<black>";
|
return "<black>";
|
||||||
@ -372,8 +390,8 @@ public class AdventureUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static String clear(String msg) {
|
public static String clear(String msg) {
|
||||||
msg = msg.replaceAll("&[0-9kabcdefklmnor]", "");
|
msg = msg.replaceAll("&[0-9abcdefklmnor]", "");
|
||||||
msg = msg.replaceAll("§[0-9kabcdefklmnor]", "");
|
msg = msg.replaceAll("§[0-9abcdefklmnor]", "");
|
||||||
msg = msg.replaceAll("&#[0-9a-fA-F]{6}", "");
|
msg = msg.replaceAll("&#[0-9a-fA-F]{6}", "");
|
||||||
return PlainTextComponentSerializer.plainText().serialize(MiniMessage.miniMessage().deserialize(msg));
|
return PlainTextComponentSerializer.plainText().serialize(MiniMessage.miniMessage().deserialize(msg));
|
||||||
}
|
}
|
||||||
|
@ -23,11 +23,11 @@ import java.util.regex.Matcher;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
public class ChatMessage {
|
public class ChatMessage {
|
||||||
private static final Gson gson = new GsonBuilder().create();
|
private static final Gson GSON = new GsonBuilder().create();
|
||||||
private final List<JsonObject> textList = new ArrayList<>();
|
private final List<JsonObject> textList = new ArrayList<>();
|
||||||
|
|
||||||
public void clear() {
|
public void clear() {
|
||||||
textList.clear();
|
this.textList.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
public ChatMessage fromText(String text) {
|
public ChatMessage fromText(String text) {
|
||||||
@ -44,7 +44,7 @@ public class ChatMessage {
|
|||||||
ColorContainer color = null;
|
ColorContainer color = null;
|
||||||
String match1 = matcher.group(1);
|
String match1 = matcher.group(1);
|
||||||
|
|
||||||
if (matcher.groupCount() == 0 || match1.length() == 0) {
|
if (matcher.groupCount() == 0 || match1.isEmpty()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -69,7 +69,9 @@ public class ChatMessage {
|
|||||||
List<ColorCode> stackedCodes = new ArrayList<>();
|
List<ColorCode> stackedCodes = new ArrayList<>();
|
||||||
while (subMatcher.find()) {
|
while (subMatcher.find()) {
|
||||||
String match2 = subMatcher.group(1);
|
String match2 = subMatcher.group(1);
|
||||||
if (match2.length() == 0) continue;
|
if (match2.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
ColorCode code = ColorCode.getByChar(Character.toLowerCase(match2.charAt(0)));
|
ColorCode code = ColorCode.getByChar(Character.toLowerCase(match2.charAt(0)));
|
||||||
|
|
||||||
@ -81,7 +83,7 @@ public class ChatMessage {
|
|||||||
match2 = match2.substring(1);
|
match2 = match2.substring(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (match2.length() != 0) {
|
if (!match2.isEmpty()) {
|
||||||
addMessage(match2, color, stackedCodes);
|
addMessage(match2, color, stackedCodes);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -97,7 +99,7 @@ public class ChatMessage {
|
|||||||
public String toText(boolean noHex) {
|
public String toText(boolean noHex) {
|
||||||
StringBuilder text = new StringBuilder();
|
StringBuilder text = new StringBuilder();
|
||||||
|
|
||||||
for (JsonObject object : textList) {
|
for (JsonObject object : this.textList) {
|
||||||
if (object.has("color")) {
|
if (object.has("color")) {
|
||||||
String color = object.get("color").getAsString();
|
String color = object.get("color").getAsString();
|
||||||
text.append("&");
|
text.append("&");
|
||||||
@ -110,7 +112,9 @@ public class ChatMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (ColorCode code : ColorCode.values()) {
|
for (ColorCode code : ColorCode.values()) {
|
||||||
if (code.isColor()) continue;
|
if (code.isColor()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
String c = code.name().toLowerCase();
|
String c = code.name().toLowerCase();
|
||||||
if (object.has(c) && object.get(c).getAsBoolean()) {
|
if (object.has(c) && object.get(c).getAsBoolean()) {
|
||||||
@ -128,7 +132,7 @@ public class ChatMessage {
|
|||||||
JsonObject txt = new JsonObject();
|
JsonObject txt = new JsonObject();
|
||||||
txt.addProperty("text", s);
|
txt.addProperty("text", s);
|
||||||
|
|
||||||
textList.add(txt);
|
this.textList.add(txt);
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@ -151,7 +155,7 @@ public class ChatMessage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
textList.add(txt);
|
this.textList.add(txt);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -169,7 +173,7 @@ public class ChatMessage {
|
|||||||
click.addProperty("value", cmd);
|
click.addProperty("value", cmd);
|
||||||
txt.add("clickEvent", click);
|
txt.add("clickEvent", click);
|
||||||
|
|
||||||
textList.add(txt);
|
this.textList.add(txt);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -187,7 +191,7 @@ public class ChatMessage {
|
|||||||
click.addProperty("value", cmd);
|
click.addProperty("value", cmd);
|
||||||
txt.add("clickEvent", click);
|
txt.add("clickEvent", click);
|
||||||
|
|
||||||
textList.add(txt);
|
this.textList.add(txt);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -205,13 +209,13 @@ public class ChatMessage {
|
|||||||
click.addProperty("value", url);
|
click.addProperty("value", url);
|
||||||
txt.add("clickEvent", hover);
|
txt.add("clickEvent", hover);
|
||||||
|
|
||||||
textList.add(txt);
|
this.textList.add(txt);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return gson.toJson(textList);
|
return GSON.toJson(this.textList);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void sendTo(CommandSender sender) {
|
public void sendTo(CommandSender sender) {
|
||||||
@ -226,14 +230,14 @@ public class ChatMessage {
|
|||||||
|
|
||||||
Object packet;
|
Object packet;
|
||||||
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_19)) {
|
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_19)) {
|
||||||
packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList)), mc_PacketPlayOutChat_new_1_19_0 ? 1 : false);
|
packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, GSON.toJson(textList)), mc_PacketPlayOutChat_new_1_19_0 ? 1 : false);
|
||||||
} else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_16)) {
|
} else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_16)) {
|
||||||
packet = mc_PacketPlayOutChat_new.newInstance(
|
packet = mc_PacketPlayOutChat_new.newInstance(
|
||||||
mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList)),
|
mc_IChatBaseComponent_ChatSerializer_a.invoke(null, GSON.toJson(textList)),
|
||||||
mc_chatMessageType_Chat.get(null),
|
mc_chatMessageType_Chat.get(null),
|
||||||
((Player) sender).getUniqueId());
|
((Player) sender).getUniqueId());
|
||||||
} else {
|
} else {
|
||||||
packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList)));
|
packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, GSON.toJson(textList)));
|
||||||
}
|
}
|
||||||
|
|
||||||
Nms.getImplementations().getPlayer().sendPacket((Player) sender, packet);
|
Nms.getImplementations().getPlayer().sendPacket((Player) sender, packet);
|
||||||
@ -250,10 +254,9 @@ public class ChatMessage {
|
|||||||
|
|
||||||
private static boolean enabled = ServerVersion.isServerVersionAtLeast(ServerVersion.V1_8);
|
private static boolean enabled = ServerVersion.isServerVersionAtLeast(ServerVersion.V1_8);
|
||||||
|
|
||||||
private static Class<?> mc_ChatMessageType;
|
private static Method mc_IChatBaseComponent_ChatSerializer_a;
|
||||||
private static Method mc_IChatBaseComponent_ChatSerializer_a, cb_craftPlayer_getHandle;
|
private static Constructor<?> mc_PacketPlayOutChat_new;
|
||||||
private static Constructor mc_PacketPlayOutChat_new;
|
private static Field mc_chatMessageType_Chat;
|
||||||
private static Field mc_entityPlayer_playerConnection, mc_chatMessageType_Chat;
|
|
||||||
private static boolean mc_PacketPlayOutChat_new_1_19_0 = false;
|
private static boolean mc_PacketPlayOutChat_new_1_19_0 = false;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
@ -263,14 +266,8 @@ public class ChatMessage {
|
|||||||
static void init() {
|
static void init() {
|
||||||
if (enabled) {
|
if (enabled) {
|
||||||
try {
|
try {
|
||||||
final String version = ServerVersion.getServerVersionString();
|
Class<?> mc_IChatBaseComponent, mc_IChatBaseComponent_ChatSerializer, mc_PacketPlayOutChat;
|
||||||
Class<?> cb_craftPlayerClazz, mc_entityPlayerClazz,
|
|
||||||
mc_IChatBaseComponent, mc_IChatBaseComponent_ChatSerializer, mc_PacketPlayOutChat;
|
|
||||||
|
|
||||||
cb_craftPlayerClazz = ClassMapping.CRAFT_PLAYER.getClazz();
|
|
||||||
cb_craftPlayer_getHandle = cb_craftPlayerClazz.getDeclaredMethod("getHandle");
|
|
||||||
mc_entityPlayerClazz = ClassMapping.ENTITY_PLAYER.getClazz();
|
|
||||||
mc_entityPlayer_playerConnection = mc_entityPlayerClazz.getDeclaredField(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_17) ? "b" : "playerConnection");
|
|
||||||
mc_IChatBaseComponent = ClassMapping.I_CHAT_BASE_COMPONENT.getClazz();
|
mc_IChatBaseComponent = ClassMapping.I_CHAT_BASE_COMPONENT.getClazz();
|
||||||
mc_IChatBaseComponent_ChatSerializer = ClassMapping.I_CHAT_BASE_COMPONENT.getClazz("ChatSerializer");
|
mc_IChatBaseComponent_ChatSerializer = ClassMapping.I_CHAT_BASE_COMPONENT.getClazz("ChatSerializer");
|
||||||
mc_IChatBaseComponent_ChatSerializer_a = mc_IChatBaseComponent_ChatSerializer.getMethod("a", String.class);
|
mc_IChatBaseComponent_ChatSerializer_a = mc_IChatBaseComponent_ChatSerializer.getMethod("a", String.class);
|
||||||
@ -284,7 +281,7 @@ public class ChatMessage {
|
|||||||
mc_PacketPlayOutChat_new_1_19_0 = true;
|
mc_PacketPlayOutChat_new_1_19_0 = true;
|
||||||
}
|
}
|
||||||
} else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_16)) {
|
} else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_16)) {
|
||||||
mc_ChatMessageType = ClassMapping.CHAT_MESSAGE_TYPE.getClazz();
|
Class<?> mc_ChatMessageType = ClassMapping.CHAT_MESSAGE_TYPE.getClazz();
|
||||||
mc_chatMessageType_Chat = mc_ChatMessageType.getField(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_17) ? "a" : "CHAT");
|
mc_chatMessageType_Chat = mc_ChatMessageType.getField(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_17) ? "a" : "CHAT");
|
||||||
mc_PacketPlayOutChat_new = mc_PacketPlayOutChat.getConstructor(mc_IChatBaseComponent, mc_ChatMessageType, UUID.class);
|
mc_PacketPlayOutChat_new = mc_PacketPlayOutChat.getConstructor(mc_IChatBaseComponent, mc_ChatMessageType, UUID.class);
|
||||||
} else {
|
} else {
|
||||||
@ -298,7 +295,7 @@ public class ChatMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ChatMessage replaceAll(String toReplace, String replaceWith) {
|
public ChatMessage replaceAll(String toReplace, String replaceWith) {
|
||||||
for (JsonObject object : textList) {
|
for (JsonObject object : this.textList) {
|
||||||
String text = object.get("text").getAsString().replaceAll(toReplace, replaceWith);
|
String text = object.get("text").getAsString().replaceAll(toReplace, replaceWith);
|
||||||
|
|
||||||
object.remove("text");
|
object.remove("text");
|
||||||
|
@ -52,11 +52,11 @@ public enum ColorCode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public char getCode() {
|
public char getCode() {
|
||||||
return code;
|
return this.code;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ChatColor getChatColor() {
|
public ChatColor getChatColor() {
|
||||||
return chatColor;
|
return this.chatColor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isColor() {
|
public boolean isColor() {
|
||||||
|
@ -10,10 +10,10 @@ public class MiniMessagePlaceholder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getPlaceholder() {
|
public String getPlaceholder() {
|
||||||
return placeholder;
|
return this.placeholder;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getValue() {
|
public String getValue() {
|
||||||
return value;
|
return this.value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -39,11 +39,11 @@ public abstract class AbstractCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public final List<String> getCommands() {
|
public final List<String> getCommands() {
|
||||||
return Collections.unmodifiableList(_handledCommands);
|
return Collections.unmodifiableList(this._handledCommands);
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void addSubCommand(String command) {
|
public final void addSubCommand(String command) {
|
||||||
_handledCommands.add(command);
|
this._handledCommands.add(command);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected abstract ReturnType runCommand(CommandSender sender, String... args);
|
protected abstract ReturnType runCommand(CommandSender sender, String... args);
|
||||||
@ -57,11 +57,11 @@ public abstract class AbstractCommand {
|
|||||||
public abstract String getDescription();
|
public abstract String getDescription();
|
||||||
|
|
||||||
public boolean hasArgs() {
|
public boolean hasArgs() {
|
||||||
return _hasArgs;
|
return this._hasArgs;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isNoConsole() {
|
public boolean isNoConsole() {
|
||||||
return _cmdType == CommandType.PLAYER_ONLY;
|
return this._cmdType == CommandType.PLAYER_ONLY;
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum ReturnType {SUCCESS, NEEDS_PLAYER, FAILURE, SYNTAX_ERROR}
|
public enum ReturnType {SUCCESS, NEEDS_PLAYER, FAILURE, SYNTAX_ERROR}
|
||||||
|
@ -13,6 +13,7 @@ import org.bukkit.command.TabCompleter;
|
|||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.plugin.Plugin;
|
import org.bukkit.plugin.Plugin;
|
||||||
import org.bukkit.plugin.java.JavaPlugin;
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.lang.reflect.Constructor;
|
import java.lang.reflect.Constructor;
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
@ -62,11 +63,11 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Set<String> getCommands() {
|
public Set<String> getCommands() {
|
||||||
return Collections.unmodifiableSet(commands.keySet());
|
return Collections.unmodifiableSet(this.commands.keySet());
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getSubCommands(String command) {
|
public List<String> getSubCommands(String command) {
|
||||||
SimpleNestedCommand nested = command == null ? null : commands.get(command.toLowerCase());
|
SimpleNestedCommand nested = command == null ? null : this.commands.get(command.toLowerCase());
|
||||||
|
|
||||||
if (nested == null) {
|
if (nested == null) {
|
||||||
return Collections.emptyList();
|
return Collections.emptyList();
|
||||||
@ -78,13 +79,15 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
public Set<AbstractCommand> getAllCommands() {
|
public Set<AbstractCommand> getAllCommands() {
|
||||||
HashSet<AbstractCommand> all = new HashSet<>();
|
HashSet<AbstractCommand> all = new HashSet<>();
|
||||||
|
|
||||||
commands.values().stream()
|
this.commands.values()
|
||||||
.filter(c -> c.parent != null && !all.contains(c.parent))
|
.stream()
|
||||||
.forEach(c -> {
|
.filter(cmd -> cmd.parent != null && !all.contains(cmd.parent))
|
||||||
all.add(c.parent);
|
.forEach(cmd -> {
|
||||||
|
all.add(cmd.parent);
|
||||||
|
|
||||||
c.children.values().stream()
|
cmd.children.values()
|
||||||
.filter(s -> !all.contains(s))
|
.stream()
|
||||||
|
.filter(child -> !all.contains(child))
|
||||||
.forEach(all::add);
|
.forEach(all::add);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -92,7 +95,7 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public CommandManager registerCommandDynamically(String command) {
|
public CommandManager registerCommandDynamically(String command) {
|
||||||
CommandManager.registerCommandDynamically(plugin, command, this, this);
|
CommandManager.registerCommandDynamically(this.plugin, command, this, this);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -100,15 +103,15 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
SimpleNestedCommand nested = new SimpleNestedCommand(abstractCommand);
|
SimpleNestedCommand nested = new SimpleNestedCommand(abstractCommand);
|
||||||
|
|
||||||
abstractCommand.getCommands().forEach(cmd -> {
|
abstractCommand.getCommands().forEach(cmd -> {
|
||||||
CommandManager.registerCommandDynamically(plugin, cmd, this, this);
|
CommandManager.registerCommandDynamically(this.plugin, cmd, this, this);
|
||||||
commands.put(cmd.toLowerCase(), nested);
|
this.commands.put(cmd.toLowerCase(), nested);
|
||||||
PluginCommand pcmd = plugin.getCommand(cmd);
|
PluginCommand pcmd = this.plugin.getCommand(cmd);
|
||||||
|
|
||||||
if (pcmd != null) {
|
if (pcmd != null) {
|
||||||
pcmd.setExecutor(this);
|
pcmd.setExecutor(this);
|
||||||
pcmd.setTabCompleter(this);
|
pcmd.setTabCompleter(this);
|
||||||
} else {
|
} else {
|
||||||
plugin.getLogger().warning("Failed to register command: /" + cmd);
|
this.plugin.getLogger().warning("Failed to register command: /" + cmd);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -119,38 +122,38 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
SimpleNestedCommand nested = new SimpleNestedCommand(abstractCommand);
|
SimpleNestedCommand nested = new SimpleNestedCommand(abstractCommand);
|
||||||
|
|
||||||
abstractCommand.getCommands().forEach(cmd -> {
|
abstractCommand.getCommands().forEach(cmd -> {
|
||||||
commands.put(cmd.toLowerCase(), nested);
|
this.commands.put(cmd.toLowerCase(), nested);
|
||||||
PluginCommand pcmd = plugin.getCommand(cmd);
|
PluginCommand pluginCommand = this.plugin.getCommand(cmd);
|
||||||
|
|
||||||
if (pcmd == null) {
|
if (pluginCommand == null) {
|
||||||
plugin.getLogger().warning("Failed to register command: /" + cmd);
|
this.plugin.getLogger().warning("Failed to register command: /" + cmd);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
pcmd.setExecutor(this);
|
pluginCommand.setExecutor(this);
|
||||||
pcmd.setTabCompleter(this);
|
pluginCommand.setTabCompleter(this);
|
||||||
});
|
});
|
||||||
|
|
||||||
return nested;
|
return nested;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MainCommand addMainCommand(String command) {
|
public MainCommand addMainCommand(String command) {
|
||||||
MainCommand nested = new MainCommand(plugin, command);
|
MainCommand nested = new MainCommand(this.plugin, command);
|
||||||
commands.put(command.toLowerCase(), nested.nestedCommands);
|
this.commands.put(command.toLowerCase(), nested.nestedCommands);
|
||||||
|
|
||||||
PluginCommand pcmd = plugin.getCommand(command);
|
PluginCommand pluginCommand = this.plugin.getCommand(command);
|
||||||
if (pcmd != null) {
|
if (pluginCommand != null) {
|
||||||
pcmd.setExecutor(this);
|
pluginCommand.setExecutor(this);
|
||||||
pcmd.setTabCompleter(this);
|
pluginCommand.setTabCompleter(this);
|
||||||
} else {
|
} else {
|
||||||
plugin.getLogger().warning("Failed to register command: /" + command);
|
this.plugin.getLogger().warning("Failed to register command: /" + command);
|
||||||
}
|
}
|
||||||
|
|
||||||
return nested;
|
return nested;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MainCommand getMainCommand(String command) {
|
public MainCommand getMainCommand(String command) {
|
||||||
SimpleNestedCommand nested = command == null ? null : commands.get(command.toLowerCase());
|
SimpleNestedCommand nested = command == null ? null : this.commands.get(command.toLowerCase());
|
||||||
|
|
||||||
if (nested != null && nested.parent instanceof MainCommand) {
|
if (nested != null && nested.parent instanceof MainCommand) {
|
||||||
return (MainCommand) nested.parent;
|
return (MainCommand) nested.parent;
|
||||||
@ -168,26 +171,26 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public CommandManager setExecutor(String command) {
|
public CommandManager setExecutor(String command) {
|
||||||
PluginCommand pcmd = command == null ? null : plugin.getCommand(command);
|
PluginCommand pluginCommand = command == null ? null : this.plugin.getCommand(command);
|
||||||
|
|
||||||
if (pcmd != null) {
|
if (pluginCommand != null) {
|
||||||
pcmd.setExecutor(this);
|
pluginCommand.setExecutor(this);
|
||||||
} else {
|
} else {
|
||||||
plugin.getLogger().warning("Failed to register command: /" + command);
|
this.plugin.getLogger().warning("Failed to register command: /" + command);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public CommandManager setUseClosestCommand(boolean bool) {
|
public CommandManager setUseClosestCommand(boolean allowLooseCommands) {
|
||||||
allowLooseCommands = bool;
|
this.allowLooseCommands = allowLooseCommands;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) {
|
public boolean onCommand(@NotNull CommandSender sender, Command command, @NotNull String label, String[] args) {
|
||||||
// grab the specific command that's being called
|
// grab the specific command that's being called
|
||||||
SimpleNestedCommand nested = commands.get(command.getName().toLowerCase());
|
SimpleNestedCommand nested = this.commands.get(command.getName().toLowerCase());
|
||||||
|
|
||||||
if (nested != null) {
|
if (nested != null) {
|
||||||
// check to see if we're trying to call a sub-command
|
// check to see if we're trying to call a sub-command
|
||||||
@ -204,19 +207,19 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
System.arraycopy(args, i, newArgs, 0, newArgs.length);
|
System.arraycopy(args, i, newArgs, 0, newArgs.length);
|
||||||
|
|
||||||
// now process the command
|
// now process the command
|
||||||
processRequirements(sub, commandSender, newArgs);
|
processRequirements(sub, sender, newArgs);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// if we've gotten this far, then just use the command we have
|
// if we've gotten this far, then just use the command we have
|
||||||
if (nested.parent != null) {
|
if (nested.parent != null) {
|
||||||
processRequirements(nested.parent, commandSender, args);
|
processRequirements(nested.parent, sender, args);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
commandSender.sendMessage(msg_noCommand);
|
sender.sendMessage(this.msg_noCommand);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -227,7 +230,7 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String match = null;
|
String match = null;
|
||||||
// support for mulit-argument subcommands
|
// support for multi-argument subcommands
|
||||||
if (args.length >= 2 && nested.children.keySet().stream().anyMatch(k -> k.indexOf(' ') != -1)) {
|
if (args.length >= 2 && nested.children.keySet().stream().anyMatch(k -> k.indexOf(' ') != -1)) {
|
||||||
for (int len = args.length; len > 1; --len) {
|
for (int len = args.length; len > 1; --len) {
|
||||||
String cmd2 = String.join(" ", Arrays.copyOf(args, len)).toLowerCase();
|
String cmd2 = String.join(" ", Arrays.copyOf(args, len)).toLowerCase();
|
||||||
@ -238,12 +241,12 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// if we don't have a subcommand, should we search for one?
|
// if we don't have a subcommand, should we search for one?
|
||||||
if (allowLooseCommands) {
|
if (this.allowLooseCommands) {
|
||||||
// do a "closest match"
|
// do a "closest match"
|
||||||
int count = 0;
|
int count = 0;
|
||||||
for (String c : nested.children.keySet()) {
|
for (String child : nested.children.keySet()) {
|
||||||
if (c.startsWith(cmd)) {
|
if (child.startsWith(cmd)) {
|
||||||
match = c;
|
match = child;
|
||||||
if (++count > 1) {
|
if (++count > 1) {
|
||||||
// there can only be one!
|
// there can only be one!
|
||||||
match = null;
|
match = null;
|
||||||
@ -258,7 +261,7 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
|
|
||||||
private void processRequirements(AbstractCommand command, CommandSender sender, String[] args) {
|
private void processRequirements(AbstractCommand command, CommandSender sender, String[] args) {
|
||||||
if (!(sender instanceof Player) && command.isNoConsole()) {
|
if (!(sender instanceof Player) && command.isNoConsole()) {
|
||||||
sender.sendMessage(msg_noConsole);
|
sender.sendMessage(this.msg_noConsole);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -266,12 +269,12 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
AbstractCommand.ReturnType returnType = command.runCommand(sender, args);
|
AbstractCommand.ReturnType returnType = command.runCommand(sender, args);
|
||||||
|
|
||||||
if (returnType == AbstractCommand.ReturnType.NEEDS_PLAYER) {
|
if (returnType == AbstractCommand.ReturnType.NEEDS_PLAYER) {
|
||||||
sender.sendMessage(msg_noConsole);
|
sender.sendMessage(this.msg_noConsole);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) {
|
if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) {
|
||||||
for (String s : msg_syntaxError) {
|
for (String s : this.msg_syntaxError) {
|
||||||
sender.sendMessage(s.replace("%syntax%", command.getSyntax()));
|
sender.sendMessage(s.replace("%syntax%", command.getSyntax()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -279,13 +282,13 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
sender.sendMessage(msg_noPerms);
|
sender.sendMessage(this.msg_noPerms);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
public List<String> onTabComplete(@NotNull CommandSender sender, Command command, @NotNull String alias, String[] args) {
|
||||||
// grab the specific command that's being called
|
// grab the specific command that's being called
|
||||||
SimpleNestedCommand nested = commands.get(command.getName().toLowerCase());
|
SimpleNestedCommand nested = this.commands.get(command.getName().toLowerCase());
|
||||||
|
|
||||||
if (nested != null) {
|
if (nested != null) {
|
||||||
if (args.length == 0 || nested.children.isEmpty()) {
|
if (args.length == 0 || nested.children.isEmpty()) {
|
||||||
@ -332,7 +335,7 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
if (args.length != 0) {
|
if (args.length != 0) {
|
||||||
String str = args[args.length - 1];
|
String str = args[args.length - 1];
|
||||||
|
|
||||||
if (list != null && str != null && str.length() >= 1) {
|
if (list != null && str != null && !str.isEmpty()) {
|
||||||
try {
|
try {
|
||||||
list.removeIf(s -> !s.toLowerCase().startsWith(str.toLowerCase()));
|
list.removeIf(s -> !s.toLowerCase().startsWith(str.toLowerCase()));
|
||||||
} catch (UnsupportedOperationException ignore) {
|
} catch (UnsupportedOperationException ignore) {
|
||||||
@ -381,12 +384,4 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
|||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
private class DCommand extends PluginCommand {
|
|
||||||
|
|
||||||
protected DCommand(@NotNull String name, @NotNull Plugin owner) {
|
|
||||||
super(name, owner);
|
|
||||||
}
|
|
||||||
} */
|
|
||||||
}
|
}
|
||||||
|
@ -44,12 +44,12 @@ public class MainCommand extends AbstractCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public MainCommand addSubCommand(AbstractCommand command) {
|
public MainCommand addSubCommand(AbstractCommand command) {
|
||||||
nestedCommands.addSubCommand(command);
|
this.nestedCommands.addSubCommand(command);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MainCommand addSubCommands(AbstractCommand... commands) {
|
public MainCommand addSubCommands(AbstractCommand... commands) {
|
||||||
nestedCommands.addSubCommands(commands);
|
this.nestedCommands.addSubCommands(commands);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,38 +57,38 @@ public class MainCommand extends AbstractCommand {
|
|||||||
protected ReturnType runCommand(CommandSender sender, String... args) {
|
protected ReturnType runCommand(CommandSender sender, String... args) {
|
||||||
sender.sendMessage("");
|
sender.sendMessage("");
|
||||||
|
|
||||||
if (header != null) {
|
if (this.header != null) {
|
||||||
sender.sendMessage(header);
|
sender.sendMessage(this.header);
|
||||||
} else {
|
} else {
|
||||||
new ChatMessage().fromText(String.format("#ff8080&l%s &8» &7Version %s Created with <3 by #ec4e74&l&oS#fa5b65&l&oo#ff6c55&l&on#ff7f44&l&og#ff9432&l&oo#ffaa1e&l&od#f4c009&l&oa",
|
new ChatMessage().fromText(String.format("#ff8080&l%s &8» &7Version %s Created with <3 by #ec4e74&l&oS#fa5b65&l&oo#ff6c55&l&on#ff7f44&l&og#ff9432&l&oo#ffaa1e&l&od#f4c009&l&oa",
|
||||||
plugin.getDescription().getName(), plugin.getDescription().getVersion()), sender instanceof ConsoleCommandSender)
|
this.plugin.getDescription().getName(), this.plugin.getDescription().getVersion()), sender instanceof ConsoleCommandSender)
|
||||||
.sendTo(sender);
|
.sendTo(sender);
|
||||||
}
|
}
|
||||||
|
|
||||||
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + "/songoda" + ChatColor.GRAY + " - Opens the Songoda plugin GUI");
|
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + "/songoda" + ChatColor.GRAY + " - Opens the Songoda plugin GUI");
|
||||||
sender.sendMessage("");
|
sender.sendMessage("");
|
||||||
|
|
||||||
if (nestedCommands != null) {
|
if (this.nestedCommands != null) {
|
||||||
List<String> commands = nestedCommands.children.values().stream().distinct().map(c -> c.getCommands().get(0)).collect(Collectors.toList());
|
List<String> commands = this.nestedCommands.children.values().stream().distinct().map(c -> c.getCommands().get(0)).collect(Collectors.toList());
|
||||||
|
|
||||||
if (sortHelp) {
|
if (this.sortHelp) {
|
||||||
Collections.sort(commands);
|
Collections.sort(commands);
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isPlayer = sender instanceof Player;
|
boolean isPlayer = sender instanceof Player;
|
||||||
// todo? pagation if commands.size is too large? (player-only)
|
// todo? pagination if commands.size is too large? (player-only)
|
||||||
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + getSyntax() + ChatColor.GRAY + " - " + getDescription());
|
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + getSyntax() + ChatColor.GRAY + " - " + getDescription());
|
||||||
|
|
||||||
for (String cmdStr : commands) {
|
for (String cmdStr : commands) {
|
||||||
final AbstractCommand cmd = nestedCommands.children.get(cmdStr);
|
final AbstractCommand cmd = this.nestedCommands.children.get(cmdStr);
|
||||||
if (cmd == null) continue;
|
if (cmd == null) continue;
|
||||||
if (!isPlayer) {
|
if (!isPlayer) {
|
||||||
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + cmd.getSyntax() + ChatColor.GRAY + " - " + cmd.getDescription());
|
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + cmd.getSyntax() + ChatColor.GRAY + " - " + cmd.getDescription());
|
||||||
} else if (cmd.getPermissionNode() == null || sender.hasPermission(cmd.getPermissionNode())) {
|
} else if (cmd.getPermissionNode() == null || sender.hasPermission(cmd.getPermissionNode())) {
|
||||||
ChatMessage chatMessage = new ChatMessage();
|
ChatMessage chatMessage = new ChatMessage();
|
||||||
final String c = "/" + command + " ";
|
final String command = "/" + this.command + " ";
|
||||||
chatMessage.addMessage(ChatColor.DARK_GRAY + "- ")
|
chatMessage.addMessage(ChatColor.DARK_GRAY + "- ")
|
||||||
.addPromptCommand(ChatColor.YELLOW + c + cmd.getSyntax(), ChatColor.YELLOW + c + cmdStr, c + cmdStr)
|
.addPromptCommand(ChatColor.YELLOW + command + cmd.getSyntax(), ChatColor.YELLOW + command + cmdStr, command + cmdStr)
|
||||||
.addMessage(ChatColor.GRAY + " - " + cmd.getDescription());
|
.addMessage(ChatColor.GRAY + " - " + cmd.getDescription());
|
||||||
chatMessage.sendTo(sender);
|
chatMessage.sendTo(sender);
|
||||||
}
|
}
|
||||||
@ -114,11 +114,11 @@ public class MainCommand extends AbstractCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getSyntax() {
|
public String getSyntax() {
|
||||||
return "/" + command;
|
return "/" + this.command;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription() {
|
||||||
return description;
|
return this.description;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -38,20 +38,20 @@ public class SelectorArguments {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Matcher m = selectorPattern.matcher(argument);
|
Matcher matcher = selectorPattern.matcher(argument);
|
||||||
if (!m.find()) {
|
if (!matcher.find()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
SelectorType type = SelectorType.getType(m.group(1));
|
SelectorType type = SelectorType.getType(matcher.group(1));
|
||||||
if (type == null) {
|
if (type == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
SelectorArguments selector = new SelectorArguments(sender, type);
|
SelectorArguments selector = new SelectorArguments(sender, type);
|
||||||
|
|
||||||
if (m.group(3) != null) {
|
if (matcher.group(3) != null) {
|
||||||
selector.parseArguments(m.group(3));
|
selector.parseArguments(matcher.group(3));
|
||||||
}
|
}
|
||||||
|
|
||||||
return selector;
|
return selector;
|
||||||
@ -82,17 +82,17 @@ public class SelectorArguments {
|
|||||||
Matcher distGroup = selectorRangePattern.matcher(v[1]);
|
Matcher distGroup = selectorRangePattern.matcher(v[1]);
|
||||||
if (distGroup.find()) {
|
if (distGroup.find()) {
|
||||||
if (distGroup.group(1) != null) {
|
if (distGroup.group(1) != null) {
|
||||||
rangeMin = Double.parseDouble(distGroup.group(1));
|
this.rangeMin = Double.parseDouble(distGroup.group(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (distGroup.group(3) == null) {
|
if (distGroup.group(3) == null) {
|
||||||
rangeMax = rangeMin;
|
this.rangeMax = this.rangeMin;
|
||||||
} else if (distGroup.group(4) != null) {
|
} else if (distGroup.group(4) != null) {
|
||||||
rangeMax = Double.parseDouble(distGroup.group(4));
|
this.rangeMax = Double.parseDouble(distGroup.group(4));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (v[0].equals("type")) {
|
} else if (v[0].equals("type")) {
|
||||||
entityType = EntityNamespace.minecraftToBukkit(v[1]);
|
this.entityType = EntityNamespace.minecraftToBukkit(v[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// more arguments can be parsed here (TODO)
|
// more arguments can be parsed here (TODO)
|
||||||
@ -126,7 +126,7 @@ public class SelectorArguments {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Collection<Entity> getSelection() {
|
public Collection<Entity> getSelection() {
|
||||||
final Location location = sender instanceof Player ? ((Player) sender).getLocation() : ((BlockCommandSender) sender).getBlock().getLocation();
|
final Location location = this.sender instanceof Player ? ((Player) this.sender).getLocation() : ((BlockCommandSender) this.sender).getBlock().getLocation();
|
||||||
Collection<Entity> list = preSelect(location);
|
Collection<Entity> list = preSelect(location);
|
||||||
|
|
||||||
if (list.isEmpty()) {
|
if (list.isEmpty()) {
|
||||||
@ -139,7 +139,7 @@ public class SelectorArguments {
|
|||||||
return list2;
|
return list2;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (selector) {
|
switch (this.selector) {
|
||||||
case PLAYER:
|
case PLAYER:
|
||||||
list2.sort((o1, o2) -> (int) (o1.getLocation().distanceSquared(location) - o2.getLocation().distanceSquared(location)));
|
list2.sort((o1, o2) -> (int) (o1.getLocation().distanceSquared(location) - o2.getLocation().distanceSquared(location)));
|
||||||
|
|
||||||
@ -157,22 +157,22 @@ public class SelectorArguments {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected Collection<Entity> preSelect(Location location) {
|
protected Collection<Entity> preSelect(Location location) {
|
||||||
switch (selector) {
|
switch (this.selector) {
|
||||||
case PLAYER:
|
case PLAYER:
|
||||||
case RANDOM_PLAYER:
|
case RANDOM_PLAYER:
|
||||||
case ALL_PLAYER:
|
case ALL_PLAYER:
|
||||||
return rangeMax == Double.POSITIVE_INFINITY
|
return this.rangeMax == Double.POSITIVE_INFINITY
|
||||||
? location.getWorld().getEntitiesByClasses(Player.class)
|
? location.getWorld().getEntitiesByClasses(Player.class)
|
||||||
: location.getWorld().getNearbyEntities(location, rangeMax * 2, rangeMax * 2, rangeMax * 2).stream()
|
: location.getWorld().getNearbyEntities(location, this.rangeMax * 2, this.rangeMax * 2, this.rangeMax * 2).stream()
|
||||||
.filter(Player.class::isInstance).collect(Collectors.toSet());
|
.filter(Player.class::isInstance).collect(Collectors.toSet());
|
||||||
|
|
||||||
case ALL_ENTITIES:
|
case ALL_ENTITIES:
|
||||||
return rangeMax == Double.POSITIVE_INFINITY
|
return this.rangeMax == Double.POSITIVE_INFINITY
|
||||||
? location.getWorld().getEntities()
|
? location.getWorld().getEntities()
|
||||||
: location.getWorld().getNearbyEntities(location, rangeMax * 2, rangeMax * 2, rangeMax * 2);
|
: location.getWorld().getNearbyEntities(location, this.rangeMax * 2, this.rangeMax * 2, this.rangeMax * 2);
|
||||||
|
|
||||||
case SELF:
|
case SELF:
|
||||||
return sender instanceof Entity ? Arrays.asList((Entity) sender) : Collections.emptyList();
|
return this.sender instanceof Entity ? Arrays.asList((Entity) this.sender) : Collections.emptyList();
|
||||||
}
|
}
|
||||||
|
|
||||||
return Collections.emptyList();
|
return Collections.emptyList();
|
||||||
@ -180,8 +180,8 @@ public class SelectorArguments {
|
|||||||
|
|
||||||
protected List<Entity> filter(Location location, Collection<Entity> list) {
|
protected List<Entity> filter(Location location, Collection<Entity> list) {
|
||||||
Stream<Entity> stream = list.stream()
|
Stream<Entity> stream = list.stream()
|
||||||
.filter(p -> rangeMin == 0 || p.getLocation().distance(location) > rangeMin)
|
.filter(p -> this.rangeMin == 0 || p.getLocation().distance(location) > this.rangeMin)
|
||||||
.filter(e -> entityType == null || e.getType() == entityType);
|
.filter(e -> this.entityType == null || e.getType() == this.entityType);
|
||||||
|
|
||||||
return stream.collect(Collectors.toList());
|
return stream.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
@ -12,12 +12,12 @@ public class SimpleNestedCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SimpleNestedCommand addSubCommand(AbstractCommand command) {
|
public SimpleNestedCommand addSubCommand(AbstractCommand command) {
|
||||||
command.getCommands().forEach(cmd -> children.put(cmd.toLowerCase(), command));
|
command.getCommands().forEach(cmd -> this.children.put(cmd.toLowerCase(), command));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SimpleNestedCommand addSubCommands(AbstractCommand... commands) {
|
public SimpleNestedCommand addSubCommands(AbstractCommand... commands) {
|
||||||
Stream.of(commands).forEach(command -> command.getCommands().forEach(cmd -> children.put(cmd.toLowerCase(), command)));
|
Stream.of(commands).forEach(command -> command.getCommands().forEach(cmd -> this.children.put(cmd.toLowerCase(), command)));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -39,7 +39,7 @@ public class Comment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ConfigFormattingRules.CommentStyle getCommentStyle() {
|
public ConfigFormattingRules.CommentStyle getCommentStyle() {
|
||||||
return commentStyle;
|
return this.commentStyle;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCommentStyle(ConfigFormattingRules.CommentStyle commentStyle) {
|
public void setCommentStyle(ConfigFormattingRules.CommentStyle commentStyle) {
|
||||||
@ -47,12 +47,12 @@ public class Comment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getLines() {
|
public List<String> getLines() {
|
||||||
return lines;
|
return this.lines;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return lines.isEmpty() ? "" : String.join("\n", lines);
|
return this.lines.isEmpty() ? "" : String.join("\n", this.lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Comment loadComment(List<String> lines) {
|
public static Comment loadComment(List<String> lines) {
|
||||||
@ -66,13 +66,13 @@ public class Comment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void writeComment(Writer output, int offset, ConfigFormattingRules.CommentStyle defaultStyle) throws IOException {
|
public void writeComment(Writer output, int offset, ConfigFormattingRules.CommentStyle defaultStyle) throws IOException {
|
||||||
ConfigFormattingRules.CommentStyle style = commentStyle != null ? commentStyle : defaultStyle;
|
ConfigFormattingRules.CommentStyle style = this.commentStyle != null ? this.commentStyle : defaultStyle;
|
||||||
int minSpacing = 0, borderSpacing = 0;
|
int minSpacing = 0, borderSpacing = 0;
|
||||||
|
|
||||||
// first draw the top of the comment
|
// first draw the top of the comment
|
||||||
if (style.drawBorder) {
|
if (style.drawBorder) {
|
||||||
// grab the longest line in the list of lines
|
// grab the longest line in the list of lines
|
||||||
minSpacing = lines.stream().max(Comparator.comparingInt(String::length)).orElse("").length();
|
minSpacing = this.lines.stream().max(Comparator.comparingInt(String::length)).orElse("").length();
|
||||||
borderSpacing = minSpacing + style.commentPrefix.length() + style.commentSuffix.length();
|
borderSpacing = minSpacing + style.commentPrefix.length() + style.commentSuffix.length();
|
||||||
|
|
||||||
// draw the first line
|
// draw the first line
|
||||||
@ -89,7 +89,7 @@ public class Comment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// then the actual comment lines
|
// then the actual comment lines
|
||||||
for (String line : lines) {
|
for (String line : this.lines) {
|
||||||
// todo? should we auto-wrap comment lines that are longer than 80 characters?
|
// todo? should we auto-wrap comment lines that are longer than 80 characters?
|
||||||
output.write((new String(new char[offset])).replace('\0', ' ') + "#" + style.commentPrefix
|
output.write((new String(new char[offset])).replace('\0', ' ') + "#" + style.commentPrefix
|
||||||
+ (minSpacing == 0 ? line : line + (new String(new char[minSpacing - line.length()])).replace('\0', ' ')) + style.commentSuffix + (style.drawBorder ? "#\n" : "\n"));
|
+ (minSpacing == 0 ? line : line + (new String(new char[minSpacing - line.length()])).replace('\0', ' ')) + style.commentSuffix + (style.drawBorder ? "#\n" : "\n"));
|
||||||
|
@ -17,8 +17,6 @@ import org.yaml.snakeyaml.representer.Representer;
|
|||||||
import java.io.BufferedInputStream;
|
import java.io.BufferedInputStream;
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
import java.io.OutputStreamWriter;
|
import java.io.OutputStreamWriter;
|
||||||
@ -28,6 +26,7 @@ import java.io.StringWriter;
|
|||||||
import java.io.Writer;
|
import java.io.Writer;
|
||||||
import java.nio.charset.Charset;
|
import java.nio.charset.Charset;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
@ -66,7 +65,7 @@ public class Config extends ConfigSection {
|
|||||||
final Plugin plugin;
|
final Plugin plugin;
|
||||||
final DumperOptions yamlOptions = new DumperOptions();
|
final DumperOptions yamlOptions = new DumperOptions();
|
||||||
final Representer yamlRepresenter = new YamlRepresenter();
|
final Representer yamlRepresenter = new YamlRepresenter();
|
||||||
final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
|
final Yaml yaml = new Yaml(new YamlConstructor(), this.yamlRepresenter, this.yamlOptions);
|
||||||
Charset defaultCharset = StandardCharsets.UTF_8;
|
Charset defaultCharset = StandardCharsets.UTF_8;
|
||||||
SaveTask saveTask;
|
SaveTask saveTask;
|
||||||
Timer autosaveTimer;
|
Timer autosaveTimer;
|
||||||
@ -117,59 +116,59 @@ public class Config extends ConfigSection {
|
|||||||
this.plugin = null;
|
this.plugin = null;
|
||||||
this.file = null;
|
this.file = null;
|
||||||
|
|
||||||
dirName = null;
|
this.dirName = null;
|
||||||
fileName = null;
|
this.fileName = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Config(@NotNull File file) {
|
public Config(@NotNull File file) {
|
||||||
this.plugin = null;
|
this.plugin = null;
|
||||||
this.file = file.getAbsoluteFile();
|
this.file = file.getAbsoluteFile();
|
||||||
|
|
||||||
dirName = null;
|
this.dirName = null;
|
||||||
fileName = null;
|
this.fileName = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Config(@NotNull Plugin plugin) {
|
public Config(@NotNull Plugin plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
|
||||||
dirName = null;
|
this.dirName = null;
|
||||||
fileName = null;
|
this.fileName = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Config(@NotNull Plugin plugin, @NotNull String file) {
|
public Config(@NotNull Plugin plugin, @NotNull String file) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
|
||||||
dirName = null;
|
this.dirName = null;
|
||||||
fileName = file;
|
this.fileName = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Config(@NotNull Plugin plugin, @Nullable String directory, @NotNull String file) {
|
public Config(@NotNull Plugin plugin, @Nullable String directory, @NotNull String file) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
|
||||||
dirName = directory;
|
this.dirName = directory;
|
||||||
fileName = file;
|
this.fileName = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigFileConfigurationAdapter getFileConfig() {
|
public ConfigFileConfigurationAdapter getFileConfig() {
|
||||||
return config;
|
return this.config;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public File getFile() {
|
public File getFile() {
|
||||||
if (file == null) {
|
if (this.file == null) {
|
||||||
if (dirName != null) {
|
if (this.dirName != null) {
|
||||||
this.file = new File(plugin.getDataFolder() + dirName, fileName != null ? fileName : "config.yml");
|
this.file = new File(this.plugin.getDataFolder() + this.dirName, this.fileName != null ? this.fileName : "config.yml");
|
||||||
} else {
|
} else {
|
||||||
this.file = new File(plugin.getDataFolder(), fileName != null ? fileName : "config.yml");
|
this.file = new File(this.plugin.getDataFolder(), this.fileName != null ? this.fileName : "config.yml");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return file;
|
return this.file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Charset getDefaultCharset() {
|
public Charset getDefaultCharset() {
|
||||||
return defaultCharset;
|
return this.defaultCharset;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -195,7 +194,7 @@ public class Config extends ConfigSection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean getLoadComments() {
|
public boolean getLoadComments() {
|
||||||
return loadComments;
|
return this.loadComments;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -208,7 +207,7 @@ public class Config extends ConfigSection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean getAutosave() {
|
public boolean getAutosave() {
|
||||||
return autosave;
|
return this.autosave;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -226,7 +225,7 @@ public class Config extends ConfigSection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int getAutosaveInterval() {
|
public int getAutosaveInterval() {
|
||||||
return autosaveInterval;
|
return this.autosaveInterval;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -244,7 +243,7 @@ public class Config extends ConfigSection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean getAutoremove() {
|
public boolean getAutoremove() {
|
||||||
return autoremove;
|
return this.autoremove;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -268,7 +267,7 @@ public class Config extends ConfigSection {
|
|||||||
*/
|
*/
|
||||||
@Nullable
|
@Nullable
|
||||||
public ConfigFormattingRules.CommentStyle getDefaultNodeCommentFormat() {
|
public ConfigFormattingRules.CommentStyle getDefaultNodeCommentFormat() {
|
||||||
return defaultNodeCommentFormat;
|
return this.defaultNodeCommentFormat;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -287,7 +286,7 @@ public class Config extends ConfigSection {
|
|||||||
*/
|
*/
|
||||||
@Nullable
|
@Nullable
|
||||||
public ConfigFormattingRules.CommentStyle getDefaultSectionCommentFormat() {
|
public ConfigFormattingRules.CommentStyle getDefaultSectionCommentFormat() {
|
||||||
return defaultSectionCommentFormat;
|
return this.defaultSectionCommentFormat;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -305,7 +304,7 @@ public class Config extends ConfigSection {
|
|||||||
* Extra lines to put between root nodes
|
* Extra lines to put between root nodes
|
||||||
*/
|
*/
|
||||||
public int getRootNodeSpacing() {
|
public int getRootNodeSpacing() {
|
||||||
return rootNodeSpacing;
|
return this.rootNodeSpacing;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -324,7 +323,7 @@ public class Config extends ConfigSection {
|
|||||||
* This is separate from rootNodeSpacing, if applicable.
|
* This is separate from rootNodeSpacing, if applicable.
|
||||||
*/
|
*/
|
||||||
public int getCommentSpacing() {
|
public int getCommentSpacing() {
|
||||||
return commentSpacing;
|
return this.commentSpacing;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -342,9 +341,9 @@ public class Config extends ConfigSection {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public Config setHeader(@NotNull String... description) {
|
public Config setHeader(@NotNull String... description) {
|
||||||
if (description.length == 0) {
|
if (description.length == 0) {
|
||||||
headerComment = null;
|
this.headerComment = null;
|
||||||
} else {
|
} else {
|
||||||
headerComment = new Comment(description);
|
this.headerComment = new Comment(description);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
@ -353,9 +352,9 @@ public class Config extends ConfigSection {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public Config setHeader(@Nullable ConfigFormattingRules.CommentStyle commentStyle, @NotNull String... description) {
|
public Config setHeader(@Nullable ConfigFormattingRules.CommentStyle commentStyle, @NotNull String... description) {
|
||||||
if (description.length == 0) {
|
if (description.length == 0) {
|
||||||
headerComment = null;
|
this.headerComment = null;
|
||||||
} else {
|
} else {
|
||||||
headerComment = new Comment(commentStyle, description);
|
this.headerComment = new Comment(commentStyle, description);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
@ -364,9 +363,9 @@ public class Config extends ConfigSection {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public Config setHeader(@Nullable List<String> description) {
|
public Config setHeader(@Nullable List<String> description) {
|
||||||
if (description == null || description.isEmpty()) {
|
if (description == null || description.isEmpty()) {
|
||||||
headerComment = null;
|
this.headerComment = null;
|
||||||
} else {
|
} else {
|
||||||
headerComment = new Comment(description);
|
this.headerComment = new Comment(description);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
@ -375,9 +374,9 @@ public class Config extends ConfigSection {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public Config setHeader(@Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> description) {
|
public Config setHeader(@Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> description) {
|
||||||
if (description == null || description.isEmpty()) {
|
if (description == null || description.isEmpty()) {
|
||||||
headerComment = null;
|
this.headerComment = null;
|
||||||
} else {
|
} else {
|
||||||
headerComment = new Comment(commentStyle, description);
|
this.headerComment = new Comment(commentStyle, description);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
@ -385,28 +384,28 @@ public class Config extends ConfigSection {
|
|||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public List<String> getHeader() {
|
public List<String> getHeader() {
|
||||||
if (headerComment != null) {
|
if (this.headerComment != null) {
|
||||||
return headerComment.getLines();
|
return this.headerComment.getLines();
|
||||||
}
|
}
|
||||||
|
|
||||||
return Collections.emptyList();
|
return Collections.emptyList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Config clearConfig(boolean clearDefaults) {
|
public Config clearConfig(boolean clearDefaults) {
|
||||||
root.values.clear();
|
this.root.values.clear();
|
||||||
root.configComments.clear();
|
this.root.configComments.clear();
|
||||||
|
|
||||||
if (clearDefaults) {
|
if (clearDefaults) {
|
||||||
root.defaultComments.clear();
|
this.root.defaultComments.clear();
|
||||||
root.defaults.clear();
|
this.root.defaults.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Config clearDefaults() {
|
public Config clearDefaults() {
|
||||||
root.defaultComments.clear();
|
this.root.defaultComments.clear();
|
||||||
root.defaults.clear();
|
this.root.defaults.clear();
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@ -418,19 +417,19 @@ public class Config extends ConfigSection {
|
|||||||
public boolean load(@NotNull File file) {
|
public boolean load(@NotNull File file) {
|
||||||
Validate.notNull(file, "File cannot be null");
|
Validate.notNull(file, "File cannot be null");
|
||||||
if (file.exists()) {
|
if (file.exists()) {
|
||||||
try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file))) {
|
try (BufferedInputStream stream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
|
||||||
Charset charset = TextUtils.detectCharset(stream, StandardCharsets.UTF_8);
|
Charset charset = TextUtils.detectCharset(stream, StandardCharsets.UTF_8);
|
||||||
|
|
||||||
// upgrade charset if file was saved in a more complex format
|
// upgrade charset if file was saved in a more complex format
|
||||||
if (charset == StandardCharsets.UTF_16BE || charset == StandardCharsets.UTF_16LE) {
|
if (charset == StandardCharsets.UTF_16BE || charset == StandardCharsets.UTF_16LE) {
|
||||||
defaultCharset = StandardCharsets.UTF_16;
|
this.defaultCharset = StandardCharsets.UTF_16;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.load(new InputStreamReader(stream, charset));
|
this.load(new InputStreamReader(stream, charset));
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (IOException | InvalidConfigurationException ex) {
|
} catch (IOException | InvalidConfigurationException ex) {
|
||||||
(plugin != null ? plugin.getLogger() : Bukkit.getLogger()).log(Level.SEVERE, "Failed to load config file: " + file.getName(), ex);
|
(this.plugin != null ? this.plugin.getLogger() : Bukkit.getLogger()).log(Level.SEVERE, "Failed to load config file: " + file.getName(), ex);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@ -461,7 +460,7 @@ public class Config extends ConfigSection {
|
|||||||
Map<?, ?> input;
|
Map<?, ?> input;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
input = (Map<?, ?>) this.yaml.load(contents);
|
input = this.yaml.load(contents);
|
||||||
} catch (YAMLException e2) {
|
} catch (YAMLException e2) {
|
||||||
throw new InvalidConfigurationException(e2);
|
throw new InvalidConfigurationException(e2);
|
||||||
} catch (ClassCastException e3) {
|
} catch (ClassCastException e3) {
|
||||||
@ -469,7 +468,7 @@ public class Config extends ConfigSection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (input != null) {
|
if (input != null) {
|
||||||
if (loadComments) {
|
if (this.loadComments) {
|
||||||
this.parseComments(contents, input);
|
this.parseComments(contents, input);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -511,7 +510,7 @@ public class Config extends ConfigSection {
|
|||||||
if (firstNode && !commentBlock.isEmpty()) {
|
if (firstNode && !commentBlock.isEmpty()) {
|
||||||
// header comment
|
// header comment
|
||||||
firstNode = false;
|
firstNode = false;
|
||||||
headerComment = Comment.loadComment(commentBlock);
|
this.headerComment = Comment.loadComment(commentBlock);
|
||||||
commentBlock.clear();
|
commentBlock.clear();
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
@ -525,10 +524,10 @@ public class Config extends ConfigSection {
|
|||||||
int lineOffset = getOffset(line);
|
int lineOffset = getOffset(line);
|
||||||
insideScalar &= lineOffset <= index;
|
insideScalar &= lineOffset <= index;
|
||||||
Matcher m;
|
Matcher m;
|
||||||
if (!insideScalar && (m = yamlNode.matcher(line)).find()) {
|
if (!insideScalar && (m = this.yamlNode.matcher(line)).find()) {
|
||||||
// we found a config node! ^.^
|
// we found a config node! ^.^
|
||||||
// check to see what the full path is
|
// check to see what the full path is
|
||||||
int depth = (m.group(1).length() / indentation);
|
int depth = (m.group(1).length() / this.indentation);
|
||||||
while (depth < currentPath.size()) {
|
while (depth < currentPath.size()) {
|
||||||
currentPath.removeLast();
|
currentPath.removeLast();
|
||||||
}
|
}
|
||||||
@ -536,7 +535,7 @@ public class Config extends ConfigSection {
|
|||||||
|
|
||||||
// do we have a comment for this node?
|
// do we have a comment for this node?
|
||||||
if (!commentBlock.isEmpty()) {
|
if (!commentBlock.isEmpty()) {
|
||||||
String path = currentPath.stream().collect(Collectors.joining(String.valueOf(pathChar)));
|
String path = currentPath.stream().collect(Collectors.joining(String.valueOf(this.pathChar)));
|
||||||
Comment comment = Comment.loadComment(commentBlock);
|
Comment comment = Comment.loadComment(commentBlock);
|
||||||
commentBlock.clear();
|
commentBlock.clear();
|
||||||
setComment(path, comment);
|
setComment(path, comment);
|
||||||
@ -553,7 +552,7 @@ public class Config extends ConfigSection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!commentBlock.isEmpty()) {
|
if (!commentBlock.isEmpty()) {
|
||||||
footerComment = Comment.loadComment(commentBlock);
|
this.footerComment = Comment.loadComment(commentBlock);
|
||||||
commentBlock.clear();
|
commentBlock.clear();
|
||||||
}
|
}
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
@ -563,53 +562,53 @@ public class Config extends ConfigSection {
|
|||||||
|
|
||||||
public void deleteNonDefaultSettings() {
|
public void deleteNonDefaultSettings() {
|
||||||
// Delete old config values (thread-safe)
|
// Delete old config values (thread-safe)
|
||||||
List<String> defaultKeys = Arrays.asList(defaults.keySet().toArray(new String[0]));
|
List<String> defaultKeys = Arrays.asList(this.defaults.keySet().toArray(new String[0]));
|
||||||
|
|
||||||
for (String key : values.keySet().toArray(new String[0])) {
|
for (String key : this.values.keySet().toArray(new String[0])) {
|
||||||
if (!defaultKeys.contains(key)) {
|
if (!defaultKeys.contains(key)) {
|
||||||
values.remove(key);
|
this.values.remove(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void onChange() {
|
protected void onChange() {
|
||||||
if (autosave) {
|
if (this.autosave) {
|
||||||
delaySave();
|
delaySave();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void delaySave() {
|
public void delaySave() {
|
||||||
// save async even if no plugin or if plugin disabled
|
// save async even if no plugin or if plugin disabled
|
||||||
if (saveTask == null && (changed || hasNewDefaults())) {
|
if (this.saveTask == null && (this.changed || hasNewDefaults())) {
|
||||||
autosaveTimer = new Timer((plugin != null ? plugin.getName() + "-ConfigSave-" : "ConfigSave-") + getFile().getName());
|
this.autosaveTimer = new Timer((this.plugin != null ? this.plugin.getName() + "-ConfigSave-" : "ConfigSave-") + getFile().getName());
|
||||||
autosaveTimer.schedule(saveTask = new SaveTask(), autosaveInterval * 1000L);
|
this.autosaveTimer.schedule(this.saveTask = new SaveTask(), this.autosaveInterval * 1000L);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean saveChanges() {
|
public boolean saveChanges() {
|
||||||
boolean saved = true;
|
boolean saved = true;
|
||||||
|
|
||||||
if (changed || hasNewDefaults()) {
|
if (this.changed || hasNewDefaults()) {
|
||||||
saved = save();
|
saved = save();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (saveTask != null) {
|
if (this.saveTask != null) {
|
||||||
//Close Threads
|
//Close Threads
|
||||||
saveTask.cancel();
|
this.saveTask.cancel();
|
||||||
autosaveTimer.cancel();
|
this.autosaveTimer.cancel();
|
||||||
saveTask = null;
|
this.saveTask = null;
|
||||||
autosaveTimer = null;
|
this.autosaveTimer = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return saved;
|
return saved;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean hasNewDefaults() {
|
boolean hasNewDefaults() {
|
||||||
if (file != null && !file.exists()) return true;
|
if (this.file != null && !this.file.exists()) return true;
|
||||||
|
|
||||||
for (String def : defaults.keySet()) {
|
for (String def : this.defaults.keySet()) {
|
||||||
if (!values.containsKey(def)) {
|
if (!this.values.containsKey(def)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -618,12 +617,12 @@ public class Config extends ConfigSection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean save() {
|
public boolean save() {
|
||||||
if (saveTask != null) {
|
if (this.saveTask != null) {
|
||||||
//Close Threads
|
//Close Threads
|
||||||
saveTask.cancel();
|
this.saveTask.cancel();
|
||||||
autosaveTimer.cancel();
|
this.autosaveTimer.cancel();
|
||||||
saveTask = null;
|
this.saveTask = null;
|
||||||
autosaveTimer = null;
|
this.autosaveTimer = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return save(getFile());
|
return save(getFile());
|
||||||
@ -642,7 +641,7 @@ public class Config extends ConfigSection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String data = this.saveToString();
|
String data = this.saveToString();
|
||||||
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), defaultCharset)) {
|
try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), this.defaultCharset)) {
|
||||||
writer.write(data);
|
writer.write(data);
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
return false;
|
return false;
|
||||||
@ -654,30 +653,30 @@ public class Config extends ConfigSection {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public String saveToString() {
|
public String saveToString() {
|
||||||
try {
|
try {
|
||||||
if (autoremove) {
|
if (this.autoremove) {
|
||||||
deleteNonDefaultSettings();
|
deleteNonDefaultSettings();
|
||||||
}
|
}
|
||||||
|
|
||||||
yamlOptions.setIndent(indentation);
|
this.yamlOptions.setIndent(this.indentation);
|
||||||
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
this.yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||||
yamlOptions.setSplitLines(false);
|
this.yamlOptions.setSplitLines(false);
|
||||||
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
this.yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||||
|
|
||||||
StringWriter str = new StringWriter();
|
StringWriter str = new StringWriter();
|
||||||
|
|
||||||
if (headerComment != null) {
|
if (this.headerComment != null) {
|
||||||
headerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED);
|
this.headerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED);
|
||||||
str.write("\n"); // add one space after the header
|
str.write("\n"); // add one space after the header
|
||||||
}
|
}
|
||||||
|
|
||||||
String dump = yaml.dump(this.getValues(false));
|
String dump = this.yaml.dump(this.getValues(false));
|
||||||
if (!dump.equals(BLANK_CONFIG)) {
|
if (!dump.equals(BLANK_CONFIG)) {
|
||||||
writeComments(dump, str);
|
writeComments(dump, str);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (footerComment != null) {
|
if (this.footerComment != null) {
|
||||||
str.write("\n");
|
str.write("\n");
|
||||||
footerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED);
|
this.footerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED);
|
||||||
}
|
}
|
||||||
|
|
||||||
return str.toString();
|
return str.toString();
|
||||||
@ -711,20 +710,20 @@ public class Config extends ConfigSection {
|
|||||||
int lineOffset = getOffset(line);
|
int lineOffset = getOffset(line);
|
||||||
insideScalar &= lineOffset <= index;
|
insideScalar &= lineOffset <= index;
|
||||||
Matcher m;
|
Matcher m;
|
||||||
if (!insideScalar && (m = yamlNode.matcher(line)).find()) {
|
if (!insideScalar && (m = this.yamlNode.matcher(line)).find()) {
|
||||||
// we found a config node! ^.^
|
// we found a config node! ^.^
|
||||||
// check to see what the full path is
|
// check to see what the full path is
|
||||||
int depth = (m.group(1).length() / indentation);
|
int depth = (m.group(1).length() / this.indentation);
|
||||||
while (depth < currentPath.size()) {
|
while (depth < currentPath.size()) {
|
||||||
currentPath.removeLast();
|
currentPath.removeLast();
|
||||||
}
|
}
|
||||||
|
|
||||||
currentPath.add(m.group(2));
|
currentPath.add(m.group(2));
|
||||||
String path = currentPath.stream().collect(Collectors.joining(String.valueOf(pathChar)));
|
String path = currentPath.stream().collect(Collectors.joining(String.valueOf(this.pathChar)));
|
||||||
|
|
||||||
// if this is a root-level node, apply extra spacing if we aren't the first node
|
// if this is a root-level node, apply extra spacing if we aren't the first node
|
||||||
if (!firstNode && depth == 0 && rootNodeSpacing > 0) {
|
if (!firstNode && depth == 0 && this.rootNodeSpacing > 0) {
|
||||||
out.write((new String(new char[rootNodeSpacing])).replace("\0", "\n")); // yes it's silly, but it works :>
|
out.write((new String(new char[this.rootNodeSpacing])).replace("\0", "\n")); // yes it's silly, but it works :>
|
||||||
}
|
}
|
||||||
firstNode = false; // we're no longer on the first node
|
firstNode = false; // we're no longer on the first node
|
||||||
|
|
||||||
@ -733,7 +732,7 @@ public class Config extends ConfigSection {
|
|||||||
if (comment != null) {
|
if (comment != null) {
|
||||||
// add spacing between previous nodes and comments
|
// add spacing between previous nodes and comments
|
||||||
if (depth != 0) {
|
if (depth != 0) {
|
||||||
out.write((new String(new char[commentSpacing])).replace("\0", "\n"));
|
out.write((new String(new char[this.commentSpacing])).replace("\0", "\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatting style for this node
|
// formatting style for this node
|
||||||
@ -742,7 +741,7 @@ public class Config extends ConfigSection {
|
|||||||
// check to see what type of node this is
|
// check to see what type of node this is
|
||||||
if (!m.group(3).trim().isEmpty()) {
|
if (!m.group(3).trim().isEmpty()) {
|
||||||
// setting node
|
// setting node
|
||||||
style = defaultNodeCommentFormat;
|
style = this.defaultNodeCommentFormat;
|
||||||
} else {
|
} else {
|
||||||
// probably a section? (need to peek ahead to check if this is a list)
|
// probably a section? (need to peek ahead to check if this is a list)
|
||||||
in.mark(1000);
|
in.mark(1000);
|
||||||
@ -750,9 +749,9 @@ public class Config extends ConfigSection {
|
|||||||
in.reset();
|
in.reset();
|
||||||
if (nextLine.startsWith("-")) {
|
if (nextLine.startsWith("-")) {
|
||||||
// not a section :P
|
// not a section :P
|
||||||
style = defaultNodeCommentFormat;
|
style = this.defaultNodeCommentFormat;
|
||||||
} else {
|
} else {
|
||||||
style = defaultSectionCommentFormat;
|
style = this.defaultSectionCommentFormat;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -22,62 +22,62 @@ public class ConfigFileConfigurationAdapter extends FileConfiguration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Config getCoreConfig() {
|
public Config getCoreConfig() {
|
||||||
return config;
|
return this.config;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String saveToString() {
|
public String saveToString() {
|
||||||
return config.saveToString();
|
return this.config.saveToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void loadFromString(String string) throws InvalidConfigurationException {
|
public void loadFromString(String string) throws InvalidConfigurationException {
|
||||||
config.loadFromString(string);
|
this.config.loadFromString(string);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected String buildHeader() {
|
protected String buildHeader() {
|
||||||
return "#" + String.join("\n#", config.getHeader());
|
return "#" + String.join("\n#", this.config.getHeader());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigOptionsAdapter options() {
|
public ConfigOptionsAdapter options() {
|
||||||
return new ConfigOptionsAdapter(config);
|
return new ConfigOptionsAdapter(this.config);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Set<String> getKeys(boolean deep) {
|
public Set<String> getKeys(boolean deep) {
|
||||||
return config.getKeys(deep);
|
return this.config.getKeys(deep);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getValues(boolean deep) {
|
public Map<String, Object> getValues(boolean deep) {
|
||||||
return config.getValues(deep);
|
return this.config.getValues(deep);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean contains(String path) {
|
public boolean contains(String path) {
|
||||||
return config.contains(path);
|
return this.config.contains(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isSet(String path) {
|
public boolean isSet(String path) {
|
||||||
return config.isSet(path);
|
return this.config.isSet(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getCurrentPath() {
|
public String getCurrentPath() {
|
||||||
return config.getCurrentPath();
|
return this.config.getCurrentPath();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return config.getName();
|
return this.config.getName();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Configuration getRoot() {
|
public Configuration getRoot() {
|
||||||
return config;
|
return this.config;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -87,186 +87,186 @@ public class ConfigFileConfigurationAdapter extends FileConfiguration {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addDefault(String path, Object value) {
|
public void addDefault(String path, Object value) {
|
||||||
config.addDefault(path, value);
|
this.config.addDefault(path, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigurationSection getDefaultSection() {
|
public ConfigurationSection getDefaultSection() {
|
||||||
return config.getDefaultSection();
|
return this.config.getDefaultSection();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void set(String path, Object value) {
|
public void set(String path, Object value) {
|
||||||
config.set(path, value);
|
this.config.set(path, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object get(String path) {
|
public Object get(String path) {
|
||||||
return config.get(path);
|
return this.config.get(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object get(String path, Object def) {
|
public Object get(String path, Object def) {
|
||||||
return config.get(path, def);
|
return this.config.get(path, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigurationSection createSection(String path) {
|
public ConfigurationSection createSection(String path) {
|
||||||
return config.createSection(path);
|
return this.config.createSection(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigurationSection createSection(String path, Map<?, ?> map) {
|
public ConfigurationSection createSection(String path, Map<?, ?> map) {
|
||||||
return config.createSection(path, map);
|
return this.config.createSection(path, map);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Other non-FileConfiguration methods
|
// Other non-FileConfiguration methods
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createDefaultSection(@NotNull String path) {
|
public ConfigSection createDefaultSection(@NotNull String path) {
|
||||||
return config.createDefaultSection(path);
|
return this.config.createDefaultSection(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createDefaultSection(@NotNull String path, String... comment) {
|
public ConfigSection createDefaultSection(@NotNull String path, String... comment) {
|
||||||
return config.createDefaultSection(path, comment);
|
return this.config.createDefaultSection(path, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||||
return config.createDefaultSection(path, commentStyle, comment);
|
return this.config.createDefaultSection(path, commentStyle, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... lines) {
|
public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... lines) {
|
||||||
return config.setComment(path, commentStyle, lines);
|
return this.config.setComment(path, commentStyle, lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
||||||
return config.setComment(path, commentStyle, lines);
|
return this.config.setComment(path, commentStyle, lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefaultComment(@NotNull String path, String... lines) {
|
public ConfigSection setDefaultComment(@NotNull String path, String... lines) {
|
||||||
return config.setDefaultComment(path, lines);
|
return this.config.setDefaultComment(path, lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefaultComment(@NotNull String path, @Nullable List<String> lines) {
|
public ConfigSection setDefaultComment(@NotNull String path, @Nullable List<String> lines) {
|
||||||
return config.setDefaultComment(path, lines);
|
return this.config.setDefaultComment(path, lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... lines) {
|
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... lines) {
|
||||||
return config.setDefaultComment(path, commentStyle, lines);
|
return this.config.setDefaultComment(path, commentStyle, lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
||||||
return config.setDefaultComment(path, commentStyle, lines);
|
return this.config.setDefaultComment(path, commentStyle, lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
public Comment getComment(@NotNull String path) {
|
public Comment getComment(@NotNull String path) {
|
||||||
return config.getComment(path);
|
return this.config.getComment(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
public String getCommentString(@NotNull String path) {
|
public String getCommentString(@NotNull String path) {
|
||||||
return config.getCommentString(path);
|
return this.config.getCommentString(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public List<ConfigSection> getSections(String path) {
|
public List<ConfigSection> getSections(String path) {
|
||||||
return config.getSections(path);
|
return this.config.getSections(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection set(@NotNull String path, @Nullable Object value, String... comment) {
|
public ConfigSection set(@NotNull String path, @Nullable Object value, String... comment) {
|
||||||
return config.set(path, value, comment);
|
return this.config.set(path, value, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection set(@NotNull String path, @Nullable Object value, List<String> comment) {
|
public ConfigSection set(@NotNull String path, @Nullable Object value, List<String> comment) {
|
||||||
return config.set(path, value, comment);
|
return this.config.set(path, value, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||||
return config.set(path, value, commentStyle, comment);
|
return this.config.set(path, value, commentStyle, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, List<String> comment) {
|
public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, List<String> comment) {
|
||||||
return config.set(path, value, commentStyle, comment);
|
return this.config.set(path, value, commentStyle, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value) {
|
public ConfigSection setDefault(@NotNull String path, @Nullable Object value) {
|
||||||
return config.setDefault(path, value);
|
return this.config.setDefault(path, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, String... comment) {
|
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, String... comment) {
|
||||||
return config.setDefault(path, value, comment);
|
return this.config.setDefault(path, value, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, List<String> comment) {
|
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, List<String> comment) {
|
||||||
return config.setDefault(path, value, comment);
|
return this.config.setDefault(path, value, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||||
return config.setDefault(path, value, commentStyle, comment);
|
return this.config.setDefault(path, value, commentStyle, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, List<String> comment) {
|
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, List<String> comment) {
|
||||||
return config.setDefault(path, value, commentStyle, comment);
|
return this.config.setDefault(path, value, commentStyle, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createSection(@NotNull String path, String... comment) {
|
public ConfigSection createSection(@NotNull String path, String... comment) {
|
||||||
return config.createSection(path, comment);
|
return this.config.createSection(path, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createSection(@NotNull String path, @Nullable List<String> comment) {
|
public ConfigSection createSection(@NotNull String path, @Nullable List<String> comment) {
|
||||||
return config.createSection(path, comment);
|
return this.config.createSection(path, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||||
return config.createSection(path, commentStyle, comment);
|
return this.config.createSection(path, commentStyle, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> comment) {
|
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> comment) {
|
||||||
return config.createSection(path, commentStyle, comment);
|
return this.config.createSection(path, commentStyle, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
public char getChar(@NotNull String path) {
|
public char getChar(@NotNull String path) {
|
||||||
return config.getChar(path);
|
return this.config.getChar(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
public char getChar(@NotNull String path, char def) {
|
public char getChar(@NotNull String path, char def) {
|
||||||
return config.getChar(path, def);
|
return this.config.getChar(path, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
public XMaterial getMaterial(@NotNull String path) {
|
public XMaterial getMaterial(@NotNull String path) {
|
||||||
return config.getMaterial(path);
|
return this.config.getMaterial(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
public XMaterial getMaterial(@NotNull String path, @Nullable XMaterial def) {
|
public XMaterial getMaterial(@NotNull String path, @Nullable XMaterial def) {
|
||||||
return config.getMaterial(path, def);
|
return this.config.getMaterial(path, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection getOrCreateConfigurationSection(@NotNull String path) {
|
public ConfigSection getOrCreateConfigurationSection(@NotNull String path) {
|
||||||
return config.getOrCreateConfigurationSection(path);
|
return this.config.getOrCreateConfigurationSection(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -32,7 +32,7 @@ public class ConfigFormattingRules {
|
|||||||
* #|_________|# <br />
|
* #|_________|# <br />
|
||||||
* ############# <br />
|
* ############# <br />
|
||||||
*/
|
*/
|
||||||
BLOCKSPACED(true, true, "|\u00AF", '\u00AF', "\u00AF|", "| ", " |", "|_", '_', "_|");
|
BLOCKSPACED(true, true, "|¯", '¯', "¯|", "| ", " |", "|_", '_', "_|");
|
||||||
|
|
||||||
final boolean drawBorder, drawSpace;
|
final boolean drawBorder, drawSpace;
|
||||||
final String commentPrefix, spacePrefixTop, spacePrefixBottom;
|
final String commentPrefix, spacePrefixTop, spacePrefixBottom;
|
||||||
|
@ -15,13 +15,13 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Config getConfig() {
|
public Config getConfig() {
|
||||||
return (Config) config.root;
|
return (Config) this.config.root;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public ConfigFileConfigurationAdapter configuration() {
|
public ConfigFileConfigurationAdapter configuration() {
|
||||||
return new ConfigFileConfigurationAdapter((Config) config.root);
|
return new ConfigFileConfigurationAdapter((Config) this.config.root);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@ -34,7 +34,7 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions {
|
|||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public ConfigOptionsAdapter pathSeparator(char value) {
|
public ConfigOptionsAdapter pathSeparator(char value) {
|
||||||
(config.root).setPathSeparator(value);
|
(this.config.root).setPathSeparator(value);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,9 +42,9 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions {
|
|||||||
@Override
|
@Override
|
||||||
public ConfigOptionsAdapter header(@Nullable String value) {
|
public ConfigOptionsAdapter header(@Nullable String value) {
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
((Config) config.root).setHeader((List) null);
|
((Config) this.config.root).setHeader((List<String>) null);
|
||||||
} else {
|
} else {
|
||||||
((Config) config.root).setHeader(value.split("\n"));
|
((Config) this.config.root).setHeader(value.split("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
@ -54,19 +54,19 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions {
|
|||||||
@Override
|
@Override
|
||||||
public ConfigOptionsAdapter copyHeader(boolean value) {
|
public ConfigOptionsAdapter copyHeader(boolean value) {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
((Config) config.root).setHeader((List) null);
|
((Config) this.config.root).setHeader((List<String>) null);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int indent() {
|
public int indent() {
|
||||||
return config.root.getIndent();
|
return this.config.root.getIndent();
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigOptionsAdapter indent(int value) {
|
public ConfigOptionsAdapter indent(int value) {
|
||||||
config.root.setIndent(value);
|
this.config.root.setIndent(value);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -42,13 +42,13 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
ConfigSection() {
|
ConfigSection() {
|
||||||
this.root = this;
|
this.root = this;
|
||||||
this.parent = null;
|
this.parent = null;
|
||||||
isDefault = false;
|
this.isDefault = false;
|
||||||
nodeKey = fullPath = "";
|
this.nodeKey = this.fullPath = "";
|
||||||
|
|
||||||
configComments = new HashMap<>();
|
this.configComments = new HashMap<>();
|
||||||
defaultComments = new HashMap<>();
|
this.defaultComments = new HashMap<>();
|
||||||
defaults = new LinkedHashMap<>();
|
this.defaults = new LinkedHashMap<>();
|
||||||
values = new LinkedHashMap<>();
|
this.values = new LinkedHashMap<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
ConfigSection(ConfigSection root, ConfigSection parent, String nodeKey, boolean isDefault) {
|
ConfigSection(ConfigSection root, ConfigSection parent, String nodeKey, boolean isDefault) {
|
||||||
@ -57,22 +57,22 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
this.nodeKey = nodeKey;
|
this.nodeKey = nodeKey;
|
||||||
this.fullPath = nodeKey != null ? parent.fullPath + nodeKey + root.pathChar : parent.fullPath;
|
this.fullPath = nodeKey != null ? parent.fullPath + nodeKey + root.pathChar : parent.fullPath;
|
||||||
this.isDefault = isDefault;
|
this.isDefault = isDefault;
|
||||||
configComments = defaultComments = null;
|
this.configComments = this.defaultComments = null;
|
||||||
defaults = null;
|
this.defaults = null;
|
||||||
values = null;
|
this.values = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getIndent() {
|
public int getIndent() {
|
||||||
return root.indentation;
|
return this.root.indentation;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setIndent(int indentation) {
|
public void setIndent(int indentation) {
|
||||||
root.indentation = indentation;
|
this.root.indentation = indentation;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void onChange() {
|
protected void onChange() {
|
||||||
if (parent != null) {
|
if (this.parent != null) {
|
||||||
root.onChange();
|
this.root.onChange();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,29 +83,29 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
* @param pathChar character to use
|
* @param pathChar character to use
|
||||||
*/
|
*/
|
||||||
public void setPathSeparator(char pathChar) {
|
public void setPathSeparator(char pathChar) {
|
||||||
if (!root.values.isEmpty() || !root.defaults.isEmpty()) {
|
if (!this.root.values.isEmpty() || !this.root.defaults.isEmpty()) {
|
||||||
throw new RuntimeException("Path change after config initialization");
|
throw new RuntimeException("Path change after config initialization");
|
||||||
}
|
}
|
||||||
|
|
||||||
root.pathChar = pathChar;
|
this.root.pathChar = pathChar;
|
||||||
}
|
}
|
||||||
|
|
||||||
public char getPathSeparator() {
|
public char getPathSeparator() {
|
||||||
return root.pathChar;
|
return this.root.pathChar;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The full key for this section node
|
* @return The full key for this section node
|
||||||
*/
|
*/
|
||||||
public String getKey() {
|
public String getKey() {
|
||||||
return !fullPath.endsWith(String.valueOf(root.pathChar)) ? fullPath : fullPath.substring(0, fullPath.length() - 1);
|
return !this.fullPath.endsWith(String.valueOf(this.root.pathChar)) ? this.fullPath : this.fullPath.substring(0, this.fullPath.length() - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The specific key that was used from the last node to get to this node
|
* @return The specific key that was used from the last node to get to this node
|
||||||
*/
|
*/
|
||||||
public String getNodeKey() {
|
public String getNodeKey() {
|
||||||
return nodeKey;
|
return this.nodeKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -116,19 +116,19 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
* @param useDefault set to true if this is a default value
|
* @param useDefault set to true if this is a default value
|
||||||
*/
|
*/
|
||||||
protected void createNodePath(@NotNull String path, boolean useDefault) {
|
protected void createNodePath(@NotNull String path, boolean useDefault) {
|
||||||
if (path.indexOf(root.pathChar) != -1) {
|
if (path.indexOf(this.root.pathChar) != -1) {
|
||||||
// if any intermediate nodes don't exist, create them
|
// if any intermediate nodes don't exist, create them
|
||||||
String[] pathParts = path.split(Pattern.quote(String.valueOf(root.pathChar)));
|
String[] pathParts = path.split(Pattern.quote(String.valueOf(this.root.pathChar)));
|
||||||
StringBuilder nodePath = new StringBuilder(fullPath);
|
StringBuilder nodePath = new StringBuilder(this.fullPath);
|
||||||
LinkedHashMap<String, Object> writeTo = useDefault ? root.defaults : root.values;
|
LinkedHashMap<String, Object> writeTo = useDefault ? this.root.defaults : this.root.values;
|
||||||
ConfigSection travelNode = this;
|
ConfigSection travelNode = this;
|
||||||
|
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
for (int i = 0; i < pathParts.length - 1; ++i) {
|
for (int i = 0; i < pathParts.length - 1; ++i) {
|
||||||
final String node = (i != 0 ? nodePath.append(root.pathChar) : nodePath).append(pathParts[i]).toString();
|
final String node = (i != 0 ? nodePath.append(this.root.pathChar) : nodePath).append(pathParts[i]).toString();
|
||||||
|
|
||||||
if (!(writeTo.get(node) instanceof ConfigSection)) {
|
if (!(writeTo.get(node) instanceof ConfigSection)) {
|
||||||
writeTo.put(node, travelNode = new ConfigSection(root, travelNode, pathParts[i], useDefault));
|
writeTo.put(node, travelNode = new ConfigSection(this.root, travelNode, pathParts[i], useDefault));
|
||||||
} else {
|
} else {
|
||||||
travelNode = (ConfigSection) writeTo.get(node);
|
travelNode = (ConfigSection) writeTo.get(node);
|
||||||
}
|
}
|
||||||
@ -140,10 +140,10 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createDefaultSection(@NotNull String path) {
|
public ConfigSection createDefaultSection(@NotNull String path) {
|
||||||
createNodePath(path, true);
|
createNodePath(path, true);
|
||||||
ConfigSection section = new ConfigSection(root, this, path, true);
|
ConfigSection section = new ConfigSection(this.root, this, path, true);
|
||||||
|
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.defaults.put(fullPath + path, section);
|
this.root.defaults.put(this.fullPath + path, section);
|
||||||
}
|
}
|
||||||
|
|
||||||
return section;
|
return section;
|
||||||
@ -152,11 +152,11 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createDefaultSection(@NotNull String path, String... comment) {
|
public ConfigSection createDefaultSection(@NotNull String path, String... comment) {
|
||||||
createNodePath(path, true);
|
createNodePath(path, true);
|
||||||
ConfigSection section = new ConfigSection(root, this, path, true);
|
ConfigSection section = new ConfigSection(this.root, this, path, true);
|
||||||
|
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.defaults.put(fullPath + path, section);
|
this.root.defaults.put(this.fullPath + path, section);
|
||||||
root.defaultComments.put(fullPath + path, new Comment(comment));
|
this.root.defaultComments.put(this.fullPath + path, new Comment(comment));
|
||||||
}
|
}
|
||||||
|
|
||||||
return section;
|
return section;
|
||||||
@ -165,11 +165,11 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||||
createNodePath(path, true);
|
createNodePath(path, true);
|
||||||
ConfigSection section = new ConfigSection(root, this, path, true);
|
ConfigSection section = new ConfigSection(this.root, this, path, true);
|
||||||
|
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.defaults.put(fullPath + path, section);
|
this.root.defaults.put(this.fullPath + path, section);
|
||||||
root.defaultComments.put(fullPath + path, new Comment(commentStyle, comment));
|
this.root.defaultComments.put(this.fullPath + path, new Comment(commentStyle, comment));
|
||||||
}
|
}
|
||||||
|
|
||||||
return section;
|
return section;
|
||||||
@ -187,11 +187,11 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setComment(@NotNull String path, @Nullable Comment comment) {
|
public ConfigSection setComment(@NotNull String path, @Nullable Comment comment) {
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
if (isDefault) {
|
if (this.isDefault) {
|
||||||
root.defaultComments.put(fullPath + path, comment);
|
this.root.defaultComments.put(this.fullPath + path, comment);
|
||||||
} else {
|
} else {
|
||||||
root.configComments.put(fullPath + path, comment);
|
this.root.configComments.put(this.fullPath + path, comment);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -205,8 +205,8 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefaultComment(@NotNull String path, @Nullable List<String> lines) {
|
public ConfigSection setDefaultComment(@NotNull String path, @Nullable List<String> lines) {
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.defaultComments.put(fullPath + path, new Comment(lines));
|
this.root.defaultComments.put(this.fullPath + path, new Comment(lines));
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
@ -219,8 +219,8 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.defaultComments.put(fullPath + path, new Comment(commentStyle, lines));
|
this.root.defaultComments.put(this.fullPath + path, new Comment(commentStyle, lines));
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
@ -228,8 +228,8 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection setDefaultComment(@NotNull String path, @Nullable Comment comment) {
|
public ConfigSection setDefaultComment(@NotNull String path, @Nullable Comment comment) {
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.defaultComments.put(fullPath + path, comment);
|
this.root.defaultComments.put(this.fullPath + path, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
@ -237,10 +237,10 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
public Comment getComment(@NotNull String path) {
|
public Comment getComment(@NotNull String path) {
|
||||||
Comment result = root.configComments.get(fullPath + path);
|
Comment result = this.root.configComments.get(this.fullPath + path);
|
||||||
|
|
||||||
if (result == null) {
|
if (result == null) {
|
||||||
result = root.defaultComments.get(fullPath + path);
|
result = this.root.defaultComments.get(this.fullPath + path);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -248,10 +248,10 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
public String getCommentString(@NotNull String path) {
|
public String getCommentString(@NotNull String path) {
|
||||||
Comment result = root.configComments.get(fullPath + path);
|
Comment result = this.root.configComments.get(this.fullPath + path);
|
||||||
|
|
||||||
if (result == null) {
|
if (result == null) {
|
||||||
result = root.defaultComments.get(fullPath + path);
|
result = this.root.defaultComments.get(this.fullPath + path);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result != null ? result.toString() : null;
|
return result != null ? result.toString() : null;
|
||||||
@ -261,8 +261,8 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
public void addDefault(@NotNull String path, @Nullable Object value) {
|
public void addDefault(@NotNull String path, @Nullable Object value) {
|
||||||
createNodePath(path, true);
|
createNodePath(path, true);
|
||||||
|
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.defaults.put(fullPath + path, value);
|
this.root.defaults.put(this.fullPath + path, value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -273,56 +273,56 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setDefaults(Configuration c) {
|
public void setDefaults(Configuration cfg) {
|
||||||
if (fullPath.isEmpty()) {
|
if (this.fullPath.isEmpty()) {
|
||||||
root.defaults.clear();
|
this.root.defaults.clear();
|
||||||
} else {
|
} else {
|
||||||
root.defaults.keySet().stream()
|
this.root.defaults.keySet().stream()
|
||||||
.filter(k -> k.startsWith(fullPath))
|
.filter(k -> k.startsWith(this.fullPath))
|
||||||
.forEach(root.defaults::remove);
|
.forEach(this.root.defaults::remove);
|
||||||
}
|
}
|
||||||
|
|
||||||
addDefaults(c);
|
addDefaults(cfg);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigSection getDefaults() {
|
public ConfigSection getDefaults() {
|
||||||
return new ConfigSection(root, this, null, true);
|
return new ConfigSection(this.root, this, null, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigSection getDefaultSection() {
|
public ConfigSection getDefaultSection() {
|
||||||
return new ConfigSection(root, this, null, true);
|
return new ConfigSection(this.root, this, null, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigOptionsAdapter options() {
|
public ConfigOptionsAdapter options() {
|
||||||
return new ConfigOptionsAdapter(root);
|
return new ConfigOptionsAdapter(this.root);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Override
|
@Override
|
||||||
public Set<String> getKeys(boolean deep) {
|
public Set<String> getKeys(boolean deep) {
|
||||||
LinkedHashSet<String> result = new LinkedHashSet<>();
|
LinkedHashSet<String> result = new LinkedHashSet<>();
|
||||||
int pathIndex = fullPath.lastIndexOf(root.pathChar);
|
int pathIndex = this.fullPath.lastIndexOf(this.root.pathChar);
|
||||||
|
|
||||||
if (deep) {
|
if (deep) {
|
||||||
result.addAll(root.defaults.keySet().stream()
|
result.addAll(this.root.defaults.keySet().stream()
|
||||||
.filter(k -> k.startsWith(fullPath))
|
.filter(k -> k.startsWith(this.fullPath))
|
||||||
.map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
.map(k -> !k.endsWith(String.valueOf(this.root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||||
result.addAll(root.values.keySet().stream()
|
result.addAll(this.root.values.keySet().stream()
|
||||||
.filter(k -> k.startsWith(fullPath))
|
.filter(k -> k.startsWith(this.fullPath))
|
||||||
.map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
.map(k -> !k.endsWith(String.valueOf(this.root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||||
} else {
|
} else {
|
||||||
result.addAll(root.defaults.keySet().stream()
|
result.addAll(this.root.defaults.keySet().stream()
|
||||||
.filter(k -> k.startsWith(fullPath) && k.lastIndexOf(root.pathChar) == pathIndex)
|
.filter(k -> k.startsWith(this.fullPath) && k.lastIndexOf(this.root.pathChar) == pathIndex)
|
||||||
.map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
.map(k -> !k.endsWith(String.valueOf(this.root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||||
result.addAll(root.values.keySet().stream()
|
result.addAll(this.root.values.keySet().stream()
|
||||||
.filter(k -> k.startsWith(fullPath) && k.lastIndexOf(root.pathChar) == pathIndex)
|
.filter(k -> k.startsWith(this.fullPath) && k.lastIndexOf(this.root.pathChar) == pathIndex)
|
||||||
.map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
.map(k -> !k.endsWith(String.valueOf(this.root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -333,43 +333,43 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getValues(boolean deep) {
|
public Map<String, Object> getValues(boolean deep) {
|
||||||
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
|
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
|
||||||
int pathIndex = fullPath.lastIndexOf(root.pathChar);
|
int pathIndex = this.fullPath.lastIndexOf(this.root.pathChar);
|
||||||
|
|
||||||
if (deep) {
|
if (deep) {
|
||||||
result.putAll((Map<String, Object>) root.defaults.entrySet().stream()
|
result.putAll((Map<String, Object>) this.root.defaults.entrySet().stream()
|
||||||
.filter(k -> k.getKey().startsWith(fullPath))
|
.filter(k -> k.getKey().startsWith(this.fullPath))
|
||||||
.collect(Collectors.toMap(
|
.collect(Collectors.toMap(
|
||||||
e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
e -> !e.getKey().endsWith(String.valueOf(this.root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||||
Map.Entry::getValue,
|
Map.Entry::getValue,
|
||||||
(v1, v2) -> {
|
(v1, v2) -> {
|
||||||
throw new IllegalStateException();
|
throw new IllegalStateException();
|
||||||
}, // never going to be merging keys
|
}, // never going to be merging keys
|
||||||
LinkedHashMap::new)));
|
LinkedHashMap::new)));
|
||||||
|
|
||||||
result.putAll((Map<String, Object>) root.values.entrySet().stream()
|
result.putAll((Map<String, Object>) this.root.values.entrySet().stream()
|
||||||
.filter(k -> k.getKey().startsWith(fullPath))
|
.filter(k -> k.getKey().startsWith(this.fullPath))
|
||||||
.collect(Collectors.toMap(
|
.collect(Collectors.toMap(
|
||||||
e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
e -> !e.getKey().endsWith(String.valueOf(this.root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||||
Map.Entry::getValue,
|
Map.Entry::getValue,
|
||||||
(v1, v2) -> {
|
(v1, v2) -> {
|
||||||
throw new IllegalStateException();
|
throw new IllegalStateException();
|
||||||
}, // never going to be merging keys
|
}, // never going to be merging keys
|
||||||
LinkedHashMap::new)));
|
LinkedHashMap::new)));
|
||||||
} else {
|
} else {
|
||||||
result.putAll((Map<String, Object>) root.defaults.entrySet().stream()
|
result.putAll((Map<String, Object>) this.root.defaults.entrySet().stream()
|
||||||
.filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex)
|
.filter(k -> k.getKey().startsWith(this.fullPath) && k.getKey().lastIndexOf(this.root.pathChar) == pathIndex)
|
||||||
.collect(Collectors.toMap(
|
.collect(Collectors.toMap(
|
||||||
e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
e -> !e.getKey().endsWith(String.valueOf(this.root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||||
Map.Entry::getValue,
|
Map.Entry::getValue,
|
||||||
(v1, v2) -> {
|
(v1, v2) -> {
|
||||||
throw new IllegalStateException();
|
throw new IllegalStateException();
|
||||||
}, // never going to be merging keys
|
}, // never going to be merging keys
|
||||||
LinkedHashMap::new)));
|
LinkedHashMap::new)));
|
||||||
|
|
||||||
result.putAll((Map<String, Object>) root.values.entrySet().stream()
|
result.putAll((Map<String, Object>) this.root.values.entrySet().stream()
|
||||||
.filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex)
|
.filter(k -> k.getKey().startsWith(this.fullPath) && k.getKey().lastIndexOf(this.root.pathChar) == pathIndex)
|
||||||
.collect(Collectors.toMap(
|
.collect(Collectors.toMap(
|
||||||
e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
e -> !e.getKey().endsWith(String.valueOf(this.root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||||
Map.Entry::getValue,
|
Map.Entry::getValue,
|
||||||
(v1, v2) -> {
|
(v1, v2) -> {
|
||||||
throw new IllegalStateException();
|
throw new IllegalStateException();
|
||||||
@ -399,51 +399,51 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean contains(@NotNull String path) {
|
public boolean contains(@NotNull String path) {
|
||||||
return root.defaults.containsKey(fullPath + path) || root.values.containsKey(fullPath + path);
|
return this.root.defaults.containsKey(this.fullPath + path) || this.root.values.containsKey(this.fullPath + path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean contains(@NotNull String path, boolean ignoreDefault) {
|
public boolean contains(@NotNull String path, boolean ignoreDefault) {
|
||||||
return (!ignoreDefault && root.defaults.containsKey(fullPath + path)) || root.values.containsKey(fullPath + path);
|
return (!ignoreDefault && this.root.defaults.containsKey(this.fullPath + path)) || this.root.values.containsKey(this.fullPath + path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isSet(@NotNull String path) {
|
public boolean isSet(@NotNull String path) {
|
||||||
return root.defaults.get(fullPath + path) != null || root.values.get(fullPath + path) != null;
|
return this.root.defaults.get(this.fullPath + path) != null || this.root.values.get(this.fullPath + path) != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getCurrentPath() {
|
public String getCurrentPath() {
|
||||||
return fullPath.isEmpty() ? "" : fullPath.substring(0, fullPath.length() - 1);
|
return this.fullPath.isEmpty() ? "" : this.fullPath.substring(0, this.fullPath.length() - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
if (fullPath.isEmpty()) {
|
if (this.fullPath.isEmpty()) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
String[] parts = fullPath.split(Pattern.quote(String.valueOf(root.pathChar)));
|
String[] parts = this.fullPath.split(Pattern.quote(String.valueOf(this.root.pathChar)));
|
||||||
return parts[parts.length - 1];
|
return parts[parts.length - 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigSection getRoot() {
|
public ConfigSection getRoot() {
|
||||||
return root;
|
return this.root;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConfigSection getParent() {
|
public ConfigSection getParent() {
|
||||||
return parent;
|
return this.parent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public Object get(@NotNull String path) {
|
public Object get(@NotNull String path) {
|
||||||
Object result = root.values.get(fullPath + path);
|
Object result = this.root.values.get(this.fullPath + path);
|
||||||
|
|
||||||
if (result == null) {
|
if (result == null) {
|
||||||
result = root.defaults.get(fullPath + path);
|
result = this.root.defaults.get(this.fullPath + path);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -452,36 +452,36 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
@Nullable
|
@Nullable
|
||||||
@Override
|
@Override
|
||||||
public Object get(@NotNull String path, @Nullable Object def) {
|
public Object get(@NotNull String path, @Nullable Object def) {
|
||||||
Object result = root.values.get(fullPath + path);
|
Object result = this.root.values.get(this.fullPath + path);
|
||||||
|
|
||||||
return result != null ? result : def;
|
return result != null ? result : def;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void set(@NotNull String path, @Nullable Object value) {
|
public void set(@NotNull String path, @Nullable Object value) {
|
||||||
if (isDefault) {
|
if (this.isDefault) {
|
||||||
addDefault(path, value);
|
addDefault(path, value);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
createNodePath(path, false);
|
createNodePath(path, false);
|
||||||
Object last;
|
Object last;
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
if (value != null) {
|
if (value != null) {
|
||||||
root.changed |= (last = root.values.put(fullPath + path, value)) != value;
|
this.root.changed |= (last = this.root.values.put(this.fullPath + path, value)) != value;
|
||||||
} else {
|
} else {
|
||||||
root.changed |= (last = root.values.remove(fullPath + path)) != null;
|
this.root.changed |= (last = this.root.values.remove(this.fullPath + path)) != null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (last != value && last instanceof ConfigSection) {
|
if (last != value && last instanceof ConfigSection) {
|
||||||
// clean up orphaned nodes
|
// clean up orphaned nodes
|
||||||
final String trim = fullPath + path + root.pathChar;
|
final String trim = this.fullPath + path + this.root.pathChar;
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.values.keySet().stream()
|
this.root.values.keySet().stream()
|
||||||
.filter(k -> k.startsWith(trim))
|
.filter(k -> k.startsWith(trim))
|
||||||
.collect(Collectors.toSet())
|
.collect(Collectors.toSet())
|
||||||
.forEach(root.values::remove);
|
.forEach(this.root.values::remove);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -546,13 +546,13 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
@Override
|
@Override
|
||||||
public ConfigSection createSection(@NotNull String path) {
|
public ConfigSection createSection(@NotNull String path) {
|
||||||
createNodePath(path, false);
|
createNodePath(path, false);
|
||||||
ConfigSection section = new ConfigSection(root, this, path, false);
|
ConfigSection section = new ConfigSection(this.root, this, path, false);
|
||||||
|
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.values.put(fullPath + path, section);
|
this.root.values.put(this.fullPath + path, section);
|
||||||
}
|
}
|
||||||
|
|
||||||
root.changed = true;
|
this.root.changed = true;
|
||||||
onChange();
|
onChange();
|
||||||
|
|
||||||
return section;
|
return section;
|
||||||
@ -576,14 +576,14 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> comment) {
|
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> comment) {
|
||||||
createNodePath(path, false);
|
createNodePath(path, false);
|
||||||
ConfigSection section = new ConfigSection(root, this, path, false);
|
ConfigSection section = new ConfigSection(this.root, this, path, false);
|
||||||
|
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.values.put(fullPath + path, section);
|
this.root.values.put(this.fullPath + path, section);
|
||||||
}
|
}
|
||||||
|
|
||||||
setComment(path, commentStyle, comment);
|
setComment(path, commentStyle, comment);
|
||||||
root.changed = true;
|
this.root.changed = true;
|
||||||
onChange();
|
onChange();
|
||||||
|
|
||||||
return section;
|
return section;
|
||||||
@ -593,10 +593,10 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
@Override
|
@Override
|
||||||
public ConfigSection createSection(@NotNull String path, Map<?, ?> map) {
|
public ConfigSection createSection(@NotNull String path, Map<?, ?> map) {
|
||||||
createNodePath(path, false);
|
createNodePath(path, false);
|
||||||
ConfigSection section = new ConfigSection(root, this, path, false);
|
ConfigSection section = new ConfigSection(this.root, this, path, false);
|
||||||
|
|
||||||
synchronized (root.lock) {
|
synchronized (this.root.lock) {
|
||||||
root.values.put(fullPath + path, section);
|
this.root.values.put(this.fullPath + path, section);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||||
@ -608,7 +608,7 @@ public class ConfigSection extends MemoryConfiguration {
|
|||||||
section.set(entry.getKey().toString(), entry.getValue());
|
section.set(entry.getKey().toString(), entry.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
root.changed = true;
|
this.root.changed = true;
|
||||||
onChange();
|
onChange();
|
||||||
|
|
||||||
return section;
|
return section;
|
||||||
|
@ -35,88 +35,88 @@ public class ConfigSetting {
|
|||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public String getKey() {
|
public String getKey() {
|
||||||
return key;
|
return this.key;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Integer> getIntegerList() {
|
public List<Integer> getIntegerList() {
|
||||||
return config.getIntegerList(key);
|
return this.config.getIntegerList(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getStringList() {
|
public List<String> getStringList() {
|
||||||
return config.getStringList(key);
|
return this.config.getStringList(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean getBoolean() {
|
public boolean getBoolean() {
|
||||||
return config.getBoolean(key);
|
return this.config.getBoolean(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean getBoolean(boolean def) {
|
public boolean getBoolean(boolean def) {
|
||||||
return config.getBoolean(key, def);
|
return this.config.getBoolean(this.key, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getInt() {
|
public int getInt() {
|
||||||
return config.getInt(key);
|
return this.config.getInt(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getInt(int def) {
|
public int getInt(int def) {
|
||||||
return config.getInt(key, def);
|
return this.config.getInt(this.key, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
public long getLong() {
|
public long getLong() {
|
||||||
return config.getLong(key);
|
return this.config.getLong(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public long getLong(long def) {
|
public long getLong(long def) {
|
||||||
return config.getLong(key, def);
|
return this.config.getLong(this.key, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
public double getDouble() {
|
public double getDouble() {
|
||||||
return config.getDouble(key);
|
return this.config.getDouble(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public double getDouble(double def) {
|
public double getDouble(double def) {
|
||||||
return config.getDouble(key, def);
|
return this.config.getDouble(this.key, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getString() {
|
public String getString() {
|
||||||
return config.getString(key);
|
return this.config.getString(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getString(String def) {
|
public String getString(String def) {
|
||||||
return config.getString(key, def);
|
return this.config.getString(this.key, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Object getObject() {
|
public Object getObject() {
|
||||||
return config.get(key);
|
return this.config.get(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Object getObject(Object def) {
|
public Object getObject(Object def) {
|
||||||
return config.get(key, def);
|
return this.config.get(this.key, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> T getObject(@NotNull Class<T> clazz) {
|
public <T> T getObject(@NotNull Class<T> clazz) {
|
||||||
return config.getObject(key, clazz);
|
return this.config.getObject(this.key, clazz);
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> T getObject(@NotNull Class<T> clazz, @Nullable T def) {
|
public <T> T getObject(@NotNull Class<T> clazz, @Nullable T def) {
|
||||||
return config.getObject(key, clazz, def);
|
return this.config.getObject(this.key, clazz, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
public char getChar() {
|
public char getChar() {
|
||||||
return config.getChar(key);
|
return this.config.getChar(this.key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public char getChar(char def) {
|
public char getChar(char def) {
|
||||||
return config.getChar(key, def);
|
return this.config.getChar(this.key, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public XMaterial getMaterial() {
|
public XMaterial getMaterial() {
|
||||||
String val = config.getString(key);
|
String val = this.config.getString(this.key);
|
||||||
Optional<XMaterial> mat = CompatibleMaterial.getMaterial(config.getString(key));
|
Optional<XMaterial> mat = CompatibleMaterial.getMaterial(this.config.getString(this.key));
|
||||||
|
|
||||||
if (!mat.isPresent()) {
|
if (!mat.isPresent()) {
|
||||||
SongodaCore.getLogger().log(Level.WARNING, String.format("Config value \"%s\" has an invalid material name: \"%s\"", key, val));
|
SongodaCore.getLogger().log(Level.WARNING, String.format("Config value \"%s\" has an invalid material name: \"%s\"", this.key, val));
|
||||||
}
|
}
|
||||||
return mat.orElse(XMaterial.STONE);
|
return mat.orElse(XMaterial.STONE);
|
||||||
}
|
}
|
||||||
@ -124,11 +124,11 @@ public class ConfigSetting {
|
|||||||
@NotNull
|
@NotNull
|
||||||
public XMaterial getMaterial(@NotNull XMaterial def) {
|
public XMaterial getMaterial(@NotNull XMaterial def) {
|
||||||
//return config.getMaterial(key, def);
|
//return config.getMaterial(key, def);
|
||||||
String val = config.getString(key);
|
String val = this.config.getString(this.key);
|
||||||
Optional<XMaterial> mat = val != null ? CompatibleMaterial.getMaterial(val) : Optional.empty();
|
Optional<XMaterial> mat = val != null ? CompatibleMaterial.getMaterial(val) : Optional.empty();
|
||||||
|
|
||||||
if (!mat.isPresent()) {
|
if (!mat.isPresent()) {
|
||||||
SongodaCore.getLogger().log(Level.WARNING, String.format("Config value \"%s\" has an invalid material name: \"%s\"", key, val));
|
SongodaCore.getLogger().log(Level.WARNING, String.format("Config value \"%s\" has an invalid material name: \"%s\"", this.key, val));
|
||||||
}
|
}
|
||||||
return mat.orElse(def);
|
return mat.orElse(def);
|
||||||
}
|
}
|
||||||
|
@ -39,7 +39,7 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
public SimpleDataStore(@NotNull Plugin plugin, @NotNull String filename, @NotNull Function<ConfigurationSection, T> loadFunction) {
|
public SimpleDataStore(@NotNull Plugin plugin, @NotNull String filename, @NotNull Function<ConfigurationSection, T> loadFunction) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.filename = filename;
|
this.filename = filename;
|
||||||
dirName = null;
|
this.dirName = null;
|
||||||
this.getFromSection = loadFunction;
|
this.getFromSection = loadFunction;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,23 +52,22 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
public File getFile() {
|
public File getFile() {
|
||||||
if (file == null) {
|
if (this.file == null) {
|
||||||
if (dirName != null) {
|
if (this.dirName != null) {
|
||||||
this.file = new File(plugin.getDataFolder() + dirName, filename != null ? filename : "data.yml");
|
this.file = new File(this.plugin.getDataFolder() + this.dirName, this.filename != null ? this.filename : "data.yml");
|
||||||
} else {
|
} else {
|
||||||
this.file = new File(plugin.getDataFolder(), filename != null ? filename : "data.yml");
|
this.file = new File(this.plugin.getDataFolder(), this.filename != null ? this.filename : "data.yml");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return file;
|
return this.file;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return a directly-modifiable instance of the data mapping for this
|
* @return a directly modifiable instance of the data mapping for this storage
|
||||||
* storage
|
|
||||||
*/
|
*/
|
||||||
public Map<Object, T> getData() {
|
public Map<Object, T> getData() {
|
||||||
return data;
|
return this.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -82,7 +81,7 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
*/
|
*/
|
||||||
@Nullable
|
@Nullable
|
||||||
public T get(Object key) {
|
public T get(Object key) {
|
||||||
return data.get(key);
|
return this.data.get(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -97,8 +96,8 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
public T remove(@NotNull Object key) {
|
public T remove(@NotNull Object key) {
|
||||||
T temp;
|
T temp;
|
||||||
|
|
||||||
synchronized (lock) {
|
synchronized (this.lock) {
|
||||||
temp = data.remove(key);
|
temp = this.data.remove(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
save();
|
save();
|
||||||
@ -122,8 +121,8 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
|
|
||||||
T temp;
|
T temp;
|
||||||
|
|
||||||
synchronized (lock) {
|
synchronized (this.lock) {
|
||||||
temp = data.remove(value.getKey());
|
temp = this.data.remove(value.getKey());
|
||||||
}
|
}
|
||||||
|
|
||||||
save();
|
save();
|
||||||
@ -148,8 +147,8 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
|
|
||||||
T temp;
|
T temp;
|
||||||
|
|
||||||
synchronized (lock) {
|
synchronized (this.lock) {
|
||||||
temp = data.put(value.getKey(), value);
|
temp = this.data.put(value.getKey(), value);
|
||||||
}
|
}
|
||||||
|
|
||||||
save();
|
save();
|
||||||
@ -168,10 +167,10 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
synchronized (lock) {
|
synchronized (this.lock) {
|
||||||
for (T t : value) {
|
for (T t : value) {
|
||||||
if (t != null) {
|
if (t != null) {
|
||||||
data.put(t.getKey(), t);
|
this.data.put(t.getKey(), t);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -191,10 +190,10 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
synchronized (lock) {
|
synchronized (this.lock) {
|
||||||
for (T v : value) {
|
for (T v : value) {
|
||||||
if (v != null) {
|
if (v != null) {
|
||||||
data.put(v.getKey(), v);
|
this.data.put(v.getKey(), v);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -213,27 +212,27 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
try {
|
try {
|
||||||
YamlConfiguration f = new YamlConfiguration();
|
YamlConfiguration f = new YamlConfiguration();
|
||||||
f.options().pathSeparator('\0');
|
f.options().pathSeparator('\0');
|
||||||
f.load(file);
|
f.load(this.file);
|
||||||
|
|
||||||
synchronized (lock) {
|
synchronized (this.lock) {
|
||||||
data.clear();
|
this.data.clear();
|
||||||
|
|
||||||
f.getValues(false).values().stream()
|
f.getValues(false).values().stream()
|
||||||
.filter(ConfigurationSection.class::isInstance)
|
.filter(ConfigurationSection.class::isInstance)
|
||||||
.map(v -> getFromSection.apply((ConfigurationSection) v))
|
.map(v -> this.getFromSection.apply((ConfigurationSection) v))
|
||||||
.forEach(v -> data.put(v.getKey(), v));
|
.forEach(v -> this.data.put(v.getKey(), v));
|
||||||
}
|
}
|
||||||
} catch (IOException | InvalidConfigurationException ex) {
|
} catch (IOException | InvalidConfigurationException ex) {
|
||||||
plugin.getLogger().log(Level.SEVERE, "Failed to load data from " + file.getName(), ex);
|
this.plugin.getLogger().log(Level.SEVERE, "Failed to load data from " + this.file.getName(), ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Optionally save this storage's data to file if there have been changes
|
* Optionally, save this storage's data to file if there have been changes
|
||||||
* made
|
* made
|
||||||
*/
|
*/
|
||||||
public void saveChanges() {
|
public void saveChanges() {
|
||||||
if (saveTask != null || data.values().stream().anyMatch(DataStoreObject::hasChanged)) {
|
if (this.saveTask != null || this.data.values().stream().anyMatch(DataStoreObject::hasChanged)) {
|
||||||
flushSave();
|
flushSave();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -243,9 +242,9 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
*/
|
*/
|
||||||
public void save() {
|
public void save() {
|
||||||
// save async even if no plugin or if plugin disabled
|
// save async even if no plugin or if plugin disabled
|
||||||
if (saveTask == null) {
|
if (this.saveTask == null) {
|
||||||
autosaveTimer = new Timer((plugin != null ? plugin.getName() + "-DataStoreSave-" : "DataStoreSave-") + getFile().getName());
|
this.autosaveTimer = new Timer((this.plugin != null ? this.plugin.getName() + "-DataStoreSave-" : "DataStoreSave-") + getFile().getName());
|
||||||
autosaveTimer.schedule(saveTask = new SaveTask(), autosaveInterval * 1000L);
|
this.autosaveTimer.schedule(this.saveTask = new SaveTask(), this.autosaveInterval * 1000L);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -253,25 +252,25 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
|||||||
* Force a new save of this storage's data
|
* Force a new save of this storage's data
|
||||||
*/
|
*/
|
||||||
public void flushSave() {
|
public void flushSave() {
|
||||||
if (saveTask != null) {
|
if (this.saveTask != null) {
|
||||||
//Close Threads
|
//Close Threads
|
||||||
saveTask.cancel();
|
this.saveTask.cancel();
|
||||||
autosaveTimer.cancel();
|
this.autosaveTimer.cancel();
|
||||||
saveTask = null;
|
this.saveTask = null;
|
||||||
autosaveTimer = null;
|
this.autosaveTimer = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
YamlConfiguration f = new YamlConfiguration();
|
YamlConfiguration yamlConfig = new YamlConfiguration();
|
||||||
|
|
||||||
synchronized (lock) {
|
synchronized (this.lock) {
|
||||||
data.values().forEach(e -> e.saveToSection(f.createSection(e.getConfigKey())));
|
this.data.values().forEach(e -> e.saveToSection(yamlConfig.createSection(e.getConfigKey())));
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
f.save(getFile());
|
yamlConfig.save(getFile());
|
||||||
data.values().forEach(e -> e.setChanged(false));
|
this.data.values().forEach(e -> e.setChanged(false));
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
plugin.getLogger().log(Level.SEVERE, "Failed to save data to " + file.getName(), ex);
|
this.plugin.getLogger().log(Level.SEVERE, "Failed to save data to " + this.file.getName(), ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -59,19 +59,19 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
if (!(parent instanceof ConfigEditorGui)) {
|
if (!(parent instanceof ConfigEditorGui)) {
|
||||||
setOnClose((gui) -> save());
|
setOnClose((gui) -> save());
|
||||||
} else {
|
} else {
|
||||||
setOnClose((gui) -> ((ConfigEditorGui) parent).edits |= edits);
|
setOnClose((gui) -> ((ConfigEditorGui) parent).edits |= this.edits);
|
||||||
}
|
}
|
||||||
|
|
||||||
// if we have a ConfigSection, we can also grab comments
|
// if we have a ConfigSection, we can also grab comments
|
||||||
try {
|
try {
|
||||||
configSection_getCommentString = node.getClass().getDeclaredMethod("getCommentString", String.class);
|
this.configSection_getCommentString = node.getClass().getDeclaredMethod("getCommentString", String.class);
|
||||||
} catch (Exception ignore) {
|
} catch (Exception ignore) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// decorate header
|
// decorate header
|
||||||
this.setTitle(ChatColor.DARK_BLUE + file);
|
this.setTitle(ChatColor.DARK_BLUE + file);
|
||||||
this.setUseHeader(true);
|
this.setUseHeader(true);
|
||||||
headerBackItem = footerBackItem = GuiUtils.getBorderItem(XMaterial.GRAY_STAINED_GLASS_PANE.parseItem());
|
this.headerBackItem = this.footerBackItem = GuiUtils.getBorderItem(XMaterial.GRAY_STAINED_GLASS_PANE.parseItem());
|
||||||
final String path = node.getCurrentPath();
|
final String path = node.getCurrentPath();
|
||||||
this.setItem(4, configItem(XMaterial.FILLED_MAP, !path.isEmpty() ? path : file, config, !path.isEmpty() ? path : null, ChatColor.BLACK.toString()));
|
this.setItem(4, configItem(XMaterial.FILLED_MAP, !path.isEmpty() ? path : file, config, !path.isEmpty() ? path : null, ChatColor.BLACK.toString()));
|
||||||
this.setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, "Exit"), (event) -> event.player.closeInventory());
|
this.setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, "Exit"), (event) -> event.player.closeInventory());
|
||||||
@ -79,22 +79,22 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
// compile list of settings
|
// compile list of settings
|
||||||
for (String key : node.getKeys(false)) {
|
for (String key : node.getKeys(false)) {
|
||||||
if (node.isConfigurationSection(key)) {
|
if (node.isConfigurationSection(key)) {
|
||||||
sections.add(key);
|
this.sections.add(key);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
settings.add(key);
|
this.settings.add(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
// next we need to display the config settings
|
// next we need to display the config settings
|
||||||
int index = 9;
|
int index = 9;
|
||||||
for (final String sectionKey : sections) {
|
for (final String sectionKey : this.sections) {
|
||||||
setButton(index++, configItem(XMaterial.WRITABLE_BOOK, ChatColor.YELLOW + sectionKey, node, sectionKey, "Click to open this section"),
|
setButton(index++, configItem(XMaterial.WRITABLE_BOOK, ChatColor.YELLOW + sectionKey, node, sectionKey, "Click to open this section"),
|
||||||
(event) -> event.manager.showGUI(event.player, new ConfigEditorGui(player, plugin, this, file, config, node.getConfigurationSection(sectionKey))));
|
(event) -> event.manager.showGUI(event.player, new ConfigEditorGui(player, plugin, this, file, config, node.getConfigurationSection(sectionKey))));
|
||||||
}
|
}
|
||||||
|
|
||||||
// now display individual settings
|
// now display individual settings
|
||||||
for (final String settingKey : settings) {
|
for (final String settingKey : this.settings) {
|
||||||
final Object val = node.get(settingKey);
|
final Object val = node.get(settingKey);
|
||||||
if (val == null) {
|
if (val == null) {
|
||||||
continue;
|
continue;
|
||||||
@ -130,7 +130,7 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
(event) -> {
|
(event) -> {
|
||||||
SimplePagedGui paged = new SimplePagedGui(this);
|
SimplePagedGui paged = new SimplePagedGui(this);
|
||||||
paged.setTitle(ChatColor.BLUE + settingKey);
|
paged.setTitle(ChatColor.BLUE + settingKey);
|
||||||
paged.setHeaderBackItem(headerBackItem).setFooterBackItem(footerBackItem).setDefaultItem(blankItem);
|
paged.setHeaderBackItem(this.headerBackItem).setFooterBackItem(this.footerBackItem).setDefaultItem(this.blankItem);
|
||||||
paged.setItem(4, configItem(XMaterial.FILLED_MAP, settingKey, node, settingKey, "Choose an item to change this value to"));
|
paged.setItem(4, configItem(XMaterial.FILLED_MAP, settingKey, node, settingKey, "Choose an item to change this value to"));
|
||||||
int i = 9;
|
int i = 9;
|
||||||
for (XMaterial mat : getAllValidMaterials()) {
|
for (XMaterial mat : getAllValidMaterials()) {
|
||||||
@ -179,18 +179,18 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ConfigurationSection getCurrentNode() {
|
public ConfigurationSection getCurrentNode() {
|
||||||
return node;
|
return this.node;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void updateValue(int clickCell, String path) {
|
protected void updateValue(int clickCell, String path) {
|
||||||
ItemStack item = inventory.getItem(clickCell);
|
ItemStack item = this.inventory.getItem(clickCell);
|
||||||
|
|
||||||
if (item == null || item == AIR) {
|
if (item == null || item == AIR) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ItemMeta meta = item.getItemMeta();
|
ItemMeta meta = item.getItemMeta();
|
||||||
Object val = node.get(path);
|
Object val = this.node.get(path);
|
||||||
|
|
||||||
if (meta != null && val != null) {
|
if (meta != null && val != null) {
|
||||||
String valStr;
|
String valStr;
|
||||||
@ -212,17 +212,17 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
setItem(clickCell, item);
|
setItem(clickCell, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
edits = true;
|
this.edits = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void toggle(int clickCell, String path) {
|
void toggle(int clickCell, String path) {
|
||||||
boolean val = !node.getBoolean(path);
|
boolean val = !this.node.getBoolean(path);
|
||||||
node.set(path, val);
|
this.node.set(path, val);
|
||||||
|
|
||||||
if (val) {
|
if (val) {
|
||||||
setItem(clickCell, ItemUtils.addGlow(inventory.getItem(clickCell)));
|
setItem(clickCell, ItemUtils.addGlow(this.inventory.getItem(clickCell)));
|
||||||
} else {
|
} else {
|
||||||
setItem(clickCell, ItemUtils.removeGlow(inventory.getItem(clickCell)));
|
setItem(clickCell, ItemUtils.removeGlow(this.inventory.getItem(clickCell)));
|
||||||
}
|
}
|
||||||
|
|
||||||
updateValue(clickCell, path);
|
updateValue(clickCell, path);
|
||||||
@ -230,12 +230,12 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
|
|
||||||
boolean setNumber(int clickCell, String path, String input) {
|
boolean setNumber(int clickCell, String path, String input) {
|
||||||
try {
|
try {
|
||||||
if (node.isInt(path)) {
|
if (this.node.isInt(path)) {
|
||||||
node.set(path, Integer.parseInt(input));
|
this.node.set(path, Integer.parseInt(input));
|
||||||
} else if (node.isDouble(path)) {
|
} else if (this.node.isDouble(path)) {
|
||||||
node.set(path, Double.parseDouble(input));
|
this.node.set(path, Double.parseDouble(input));
|
||||||
} else if (node.isLong(path)) {
|
} else if (this.node.isLong(path)) {
|
||||||
node.set(path, Long.parseLong(input));
|
this.node.set(path, Long.parseLong(input));
|
||||||
}
|
}
|
||||||
|
|
||||||
updateValue(clickCell, path);
|
updateValue(clickCell, path);
|
||||||
@ -250,42 +250,42 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
Optional<XMaterial> mat = CompatibleMaterial.getMaterial(item.getType());
|
Optional<XMaterial> mat = CompatibleMaterial.getMaterial(item.getType());
|
||||||
|
|
||||||
if (!mat.isPresent()) {
|
if (!mat.isPresent()) {
|
||||||
node.set(path, XMaterial.STONE.name());
|
this.node.set(path, XMaterial.STONE.name());
|
||||||
} else {
|
} else {
|
||||||
node.set(path, mat.get().name());
|
this.node.set(path, mat.get().name());
|
||||||
}
|
}
|
||||||
|
|
||||||
updateValue(clickCell, path);
|
updateValue(clickCell, path);
|
||||||
}
|
}
|
||||||
|
|
||||||
void setList(int clickCell, String path, List<String> list) {
|
void setList(int clickCell, String path, List<String> list) {
|
||||||
node.set(path, list);
|
this.node.set(path, list);
|
||||||
updateValue(clickCell, path);
|
updateValue(clickCell, path);
|
||||||
}
|
}
|
||||||
|
|
||||||
void save() {
|
void save() {
|
||||||
if (!edits) {
|
if (!this.edits) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// could also check and call saveChanges()
|
// could also check and call saveChanges()
|
||||||
if (config instanceof FileConfiguration) {
|
if (this.config instanceof FileConfiguration) {
|
||||||
try {
|
try {
|
||||||
((FileConfiguration) config).save(new File(plugin.getDataFolder(), file));
|
((FileConfiguration) this.config).save(new File(this.plugin.getDataFolder(), this.file));
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
plugin.getLogger().log(Level.SEVERE, "Failed to save config changes to " + file, ex);
|
this.plugin.getLogger().log(Level.SEVERE, "Failed to save config changes to " + this.file, ex);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else if (config instanceof Config) {
|
} else if (this.config instanceof Config) {
|
||||||
((Config) config).save();
|
((Config) this.config).save();
|
||||||
} else {
|
} else {
|
||||||
player.sendMessage(ChatColor.RED + "Unknown configuration type '" + config.getClass().getName() + "' - Please report this error!");
|
this.player.sendMessage(ChatColor.RED + "Unknown configuration type '" + this.config.getClass().getName() + "' - Please report this error!");
|
||||||
plugin.getLogger().log(Level.WARNING, "Unknown configuration type '" + config.getClass().getName() + "' - Please report this error!");
|
this.plugin.getLogger().log(Level.WARNING, "Unknown configuration type '" + this.config.getClass().getName() + "' - Please report this error!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
plugin.reloadConfig();
|
this.plugin.reloadConfig();
|
||||||
player.sendMessage(ChatColor.GREEN + "Config " + file + " saved!");
|
this.player.sendMessage(ChatColor.GREEN + "Config " + this.file + " saved!");
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isNumber(Object value) {
|
private boolean isNumber(Object value) {
|
||||||
@ -307,9 +307,9 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
protected ItemStack configItem(XMaterial type, String name, ConfigurationSection node, String path, String def) {
|
protected ItemStack configItem(XMaterial type, String name, ConfigurationSection node, String path, String def) {
|
||||||
String[] info = null;
|
String[] info = null;
|
||||||
|
|
||||||
if (configSection_getCommentString != null) {
|
if (this.configSection_getCommentString != null) {
|
||||||
try {
|
try {
|
||||||
Object comment = configSection_getCommentString.invoke(node, path);
|
Object comment = this.configSection_getCommentString.invoke(node, path);
|
||||||
|
|
||||||
if (comment != null) {
|
if (comment != null) {
|
||||||
info = comment.toString().split("\n");
|
info = comment.toString().split("\n");
|
||||||
@ -328,9 +328,9 @@ public class ConfigEditorGui extends SimplePagedGui {
|
|||||||
|
|
||||||
String[] info = null;
|
String[] info = null;
|
||||||
|
|
||||||
if (configSection_getCommentString != null) {
|
if (this.configSection_getCommentString != null) {
|
||||||
try {
|
try {
|
||||||
Object comment = configSection_getCommentString.invoke(node, path);
|
Object comment = this.configSection_getCommentString.invoke(node, path);
|
||||||
if (comment != null) {
|
if (comment != null) {
|
||||||
info = (value + "\n" + comment).split("\n");
|
info = (value + "\n" + comment).split("\n");
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ public class ConfigEditorListEditorGui extends SimplePagedGui {
|
|||||||
|
|
||||||
this.current = current;
|
this.current = current;
|
||||||
this.blankItem = current.getDefaultItem();
|
this.blankItem = current.getDefaultItem();
|
||||||
headerBackItem = footerBackItem = current.getHeaderBackItem();
|
this.headerBackItem = this.footerBackItem = current.getHeaderBackItem();
|
||||||
setTitle(ChatColor.DARK_BLUE + "String List Editor");
|
setTitle(ChatColor.DARK_BLUE + "String List Editor");
|
||||||
this.setUseHeader(true);
|
this.setUseHeader(true);
|
||||||
this.setItem(4, current.configItem(XMaterial.FILLED_MAP, key, current.getCurrentNode(), key, null));
|
this.setItem(4, current.configItem(XMaterial.FILLED_MAP, key, current.getCurrentNode(), key, null));
|
||||||
@ -33,14 +33,14 @@ public class ConfigEditorListEditorGui extends SimplePagedGui {
|
|||||||
|
|
||||||
this.setButton(8, GuiUtils.createButtonItem(XMaterial.LAVA_BUCKET, ChatColor.RED + "Discard Changes"), (event) -> event.player.closeInventory());
|
this.setButton(8, GuiUtils.createButtonItem(XMaterial.LAVA_BUCKET, ChatColor.RED + "Discard Changes"), (event) -> event.player.closeInventory());
|
||||||
this.setButton(0, GuiUtils.createButtonItem(XMaterial.REDSTONE, ChatColor.GREEN + "Save"), (event) -> {
|
this.setButton(0, GuiUtils.createButtonItem(XMaterial.REDSTONE, ChatColor.GREEN + "Save"), (event) -> {
|
||||||
saveChanges = true;
|
this.saveChanges = true;
|
||||||
event.player.closeInventory();
|
event.player.closeInventory();
|
||||||
});
|
});
|
||||||
this.setButton(1, GuiUtils.createButtonItem(XMaterial.CHEST, ChatColor.BLUE + "Add Item"),
|
this.setButton(1, GuiUtils.createButtonItem(XMaterial.CHEST, ChatColor.BLUE + "Add Item"),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
event.gui.exit();
|
event.gui.exit();
|
||||||
ChatPrompt.showPrompt(event.manager.getPlugin(), event.player, "Enter a new value to add:", response -> {
|
ChatPrompt.showPrompt(event.manager.getPlugin(), event.player, "Enter a new value to add:", response -> {
|
||||||
values.add(response.getMessage().trim());
|
this.values.add(response.getMessage().trim());
|
||||||
redraw();
|
redraw();
|
||||||
})
|
})
|
||||||
.setOnClose(() -> event.manager.showGUI(event.player, this))
|
.setOnClose(() -> event.manager.showGUI(event.player, this))
|
||||||
@ -54,24 +54,24 @@ public class ConfigEditorListEditorGui extends SimplePagedGui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void redraw() {
|
void redraw() {
|
||||||
page = 1;
|
this.page = 1;
|
||||||
|
|
||||||
// clear old display
|
// clear old display
|
||||||
if (inventory != null) {
|
if (this.inventory != null) {
|
||||||
for (Integer i : cellItems.keySet().toArray(new Integer[0])) {
|
for (Integer i : this.cellItems.keySet().toArray(new Integer[0])) {
|
||||||
if (i > 8) {
|
if (i > 8) {
|
||||||
cellItems.remove(i);
|
this.cellItems.remove(i);
|
||||||
conditionalButtons.remove(i);
|
this.conditionalButtons.remove(i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// update items
|
// update items
|
||||||
int i = 9;
|
int i = 9;
|
||||||
for (String item : values) {
|
for (String item : this.values) {
|
||||||
final int index = i - 9;
|
final int index = i - 9;
|
||||||
setButton(i++, GuiUtils.createButtonItem(XMaterial.PAPER, item, "Right-click to remove"), ClickType.RIGHT, (event) -> {
|
setButton(i++, GuiUtils.createButtonItem(XMaterial.PAPER, item, "Right-click to remove"), ClickType.RIGHT, (event) -> {
|
||||||
values.remove(index);
|
this.values.remove(index);
|
||||||
redraw();
|
redraw();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -34,11 +34,11 @@ public class PluginConfigGui extends SimplePagedGui {
|
|||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
|
||||||
// collect list of plugins
|
// collect list of plugins
|
||||||
configs.put(plugin.getCoreConfig().getFile().getName(), plugin.getCoreConfig());
|
this.configs.put(plugin.getCoreConfig().getFile().getName(), plugin.getCoreConfig());
|
||||||
List<Config> more = plugin.getExtraConfig();
|
List<Config> more = plugin.getExtraConfig();
|
||||||
if (more != null && !more.isEmpty()) {
|
if (more != null && !more.isEmpty()) {
|
||||||
for (Config cfg : more) {
|
for (Config cfg : more) {
|
||||||
configs.put(cfg.getFile().getName(), cfg);
|
this.configs.put(cfg.getFile().getName(), cfg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -54,7 +54,7 @@ public class PluginConfigGui extends SimplePagedGui {
|
|||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
|
||||||
// collect list of plugins
|
// collect list of plugins
|
||||||
configs.put("config.yml", plugin.getConfig());
|
this.configs.put("config.yml", plugin.getConfig());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// can we also grab extra config from this mysterious plugin?
|
// can we also grab extra config from this mysterious plugin?
|
||||||
@ -64,11 +64,11 @@ public class PluginConfigGui extends SimplePagedGui {
|
|||||||
// if we have the getExtraConfig function, we should also be able to get the file
|
// if we have the getExtraConfig function, we should also be able to get the file
|
||||||
Method method_Config_getFile = ((List<?>) more).get(0).getClass().getDeclaredMethod("getFile");
|
Method method_Config_getFile = ((List<?>) more).get(0).getClass().getDeclaredMethod("getFile");
|
||||||
for (Object cfg : ((List<?>) more)) {
|
for (Object cfg : ((List<?>) more)) {
|
||||||
configs.put(((File) method_Config_getFile.invoke(cfg)).getName(), (MemoryConfiguration) cfg);
|
this.configs.put(((File) method_Config_getFile.invoke(cfg)).getName(), (MemoryConfiguration) cfg);
|
||||||
}
|
}
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
// include a failsafe, I guess
|
// include a failsafe, I guess
|
||||||
((List<?>) more).forEach(cfg -> configs.put("(File " + configs.size() + ")", (MemoryConfiguration) cfg));
|
((List<?>) more).forEach(cfg -> this.configs.put("(File " + this.configs.size() + ")", (MemoryConfiguration) cfg));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
|
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
|
||||||
@ -82,16 +82,16 @@ public class PluginConfigGui extends SimplePagedGui {
|
|||||||
this.blankItem = GuiUtils.getBorderItem(XMaterial.LIGHT_GRAY_STAINED_GLASS_PANE);
|
this.blankItem = GuiUtils.getBorderItem(XMaterial.LIGHT_GRAY_STAINED_GLASS_PANE);
|
||||||
|
|
||||||
// decorate header
|
// decorate header
|
||||||
this.setTitle(ChatColor.DARK_BLUE + plugin.getName() + " Plugin Config");
|
this.setTitle(ChatColor.DARK_BLUE + this.plugin.getName() + " Plugin Config");
|
||||||
this.setUseHeader(true);
|
this.setUseHeader(true);
|
||||||
headerBackItem = footerBackItem = GuiUtils.getBorderItem(XMaterial.GRAY_STAINED_GLASS_PANE.parseItem());
|
this.headerBackItem = this.footerBackItem = GuiUtils.getBorderItem(XMaterial.GRAY_STAINED_GLASS_PANE.parseItem());
|
||||||
this.setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, "Exit"), (event) -> event.player.closeInventory());
|
this.setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, "Exit"), (event) -> event.player.closeInventory());
|
||||||
|
|
||||||
// List out all config files that this plugin has
|
// List out all config files that this plugin has
|
||||||
int i = 9;
|
int i = 9;
|
||||||
for (Map.Entry<String, MemoryConfiguration> config : configs.entrySet()) {
|
for (Map.Entry<String, MemoryConfiguration> config : this.configs.entrySet()) {
|
||||||
this.setButton(i++, GuiUtils.createButtonItem(XMaterial.BOOK, ChatColor.YELLOW + config.getKey(), "Click to edit this config"),
|
this.setButton(i++, GuiUtils.createButtonItem(XMaterial.BOOK, ChatColor.YELLOW + config.getKey(), "Click to edit this config"),
|
||||||
(event) -> event.manager.showGUI(event.player, new ConfigEditorGui(event.player, plugin, this, config.getKey(), config.getValue())));
|
(event) -> event.manager.showGUI(event.player, new ConfigEditorGui(event.player, this.plugin, this, config.getKey(), config.getValue())));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,11 +11,11 @@ import java.util.Collections;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public final class PluginInfo {
|
public final class PluginInfo {
|
||||||
protected final JavaPlugin javaPlugin;
|
private final JavaPlugin javaPlugin;
|
||||||
protected final int songodaId;
|
private final int songodaId;
|
||||||
protected final String coreIcon;
|
private final String coreIcon;
|
||||||
protected final XMaterial icon;
|
private final XMaterial icon;
|
||||||
protected final String coreLibraryVersion;
|
private final String coreLibraryVersion;
|
||||||
|
|
||||||
private final List<PluginInfoModule> modules = new ArrayList<>();
|
private final List<PluginInfoModule> modules = new ArrayList<>();
|
||||||
private boolean hasUpdate = false;
|
private boolean hasUpdate = false;
|
||||||
@ -34,17 +34,17 @@ public final class PluginInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getLatestVersion() {
|
public String getLatestVersion() {
|
||||||
return latestVersion;
|
return this.latestVersion;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLatestVersion(String latestVersion) {
|
public void setLatestVersion(String latestVersion) {
|
||||||
this.latestVersion = latestVersion;
|
this.latestVersion = latestVersion;
|
||||||
|
|
||||||
hasUpdate = latestVersion != null && !latestVersion.isEmpty() && !javaPlugin.getDescription().getVersion().equalsIgnoreCase(latestVersion);
|
this.hasUpdate = latestVersion != null && !latestVersion.isEmpty() && !this.javaPlugin.getDescription().getVersion().equalsIgnoreCase(latestVersion);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getNotification() {
|
public String getNotification() {
|
||||||
return notification;
|
return this.notification;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setNotification(String notification) {
|
public void setNotification(String notification) {
|
||||||
@ -52,7 +52,7 @@ public final class PluginInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasUpdate() {
|
public boolean hasUpdate() {
|
||||||
return hasUpdate;
|
return this.hasUpdate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHasUpdate(boolean hasUpdate) {
|
public void setHasUpdate(boolean hasUpdate) {
|
||||||
@ -60,7 +60,7 @@ public final class PluginInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getChangeLog() {
|
public String getChangeLog() {
|
||||||
return changeLog;
|
return this.changeLog;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setChangeLog(String changeLog) {
|
public void setChangeLog(String changeLog) {
|
||||||
@ -68,7 +68,7 @@ public final class PluginInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getMarketplaceLink() {
|
public String getMarketplaceLink() {
|
||||||
return marketplaceLink;
|
return this.marketplaceLink;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMarketplaceLink(String marketplaceLink) {
|
public void setMarketplaceLink(String marketplaceLink) {
|
||||||
@ -76,7 +76,7 @@ public final class PluginInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public JSONObject getJson() {
|
public JSONObject getJson() {
|
||||||
return json;
|
return this.json;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setJson(JSONObject json) {
|
public void setJson(JSONObject json) {
|
||||||
@ -84,29 +84,33 @@ public final class PluginInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public PluginInfoModule addModule(PluginInfoModule module) {
|
public PluginInfoModule addModule(PluginInfoModule module) {
|
||||||
modules.add(module);
|
this.modules.add(module);
|
||||||
|
|
||||||
return module;
|
return module;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<PluginInfoModule> getModules() {
|
public List<PluginInfoModule> getModules() {
|
||||||
return Collections.unmodifiableList(modules);
|
return Collections.unmodifiableList(this.modules);
|
||||||
}
|
}
|
||||||
|
|
||||||
public JavaPlugin getJavaPlugin() {
|
public JavaPlugin getJavaPlugin() {
|
||||||
return javaPlugin;
|
return this.javaPlugin;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getSongodaId() {
|
public int getSongodaId() {
|
||||||
return songodaId;
|
return this.songodaId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getCoreIcon() {
|
public String getCoreIcon() {
|
||||||
return coreIcon;
|
return this.coreIcon;
|
||||||
|
}
|
||||||
|
|
||||||
|
public XMaterial getIcon() {
|
||||||
|
return this.icon;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getCoreLibraryVersion() {
|
public String getCoreLibraryVersion() {
|
||||||
return coreLibraryVersion;
|
return this.coreLibraryVersion;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getDependencyVersion() {
|
public int getDependencyVersion() {
|
||||||
|
@ -18,11 +18,11 @@ public class SongodaCoreCommand extends AbstractCommand {
|
|||||||
@Override
|
@Override
|
||||||
protected ReturnType runCommand(CommandSender sender, String... args) {
|
protected ReturnType runCommand(CommandSender sender, String... args) {
|
||||||
if (sender instanceof Player) {
|
if (sender instanceof Player) {
|
||||||
if (guiManager == null || guiManager.isClosed()) {
|
if (this.guiManager == null || this.guiManager.isClosed()) {
|
||||||
guiManager = new GuiManager(SongodaCore.getHijackedPlugin());
|
this.guiManager = new GuiManager(SongodaCore.getHijackedPlugin());
|
||||||
}
|
}
|
||||||
|
|
||||||
guiManager.showGUI((Player) sender, new SongodaCoreOverviewGUI());
|
this.guiManager.showGUI((Player) sender, new SongodaCoreOverviewGUI());
|
||||||
} else {
|
} else {
|
||||||
sender.sendMessage("/songoda diag");
|
sender.sendMessage("/songoda diag");
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ import org.bukkit.event.inventory.ClickType;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
final class SongodaCoreOverviewGUI extends Gui {
|
final class SongodaCoreOverviewGUI extends Gui {
|
||||||
protected SongodaCoreOverviewGUI() {
|
SongodaCoreOverviewGUI() {
|
||||||
List<PluginInfo> plugins = SongodaCore.getPlugins();
|
List<PluginInfo> plugins = SongodaCore.getPlugins();
|
||||||
// could do pages, too, but don't think we'll have that many at a time for a while
|
// could do pages, too, but don't think we'll have that many at a time for a while
|
||||||
int max = (int) Math.ceil(plugins.size() / 9.);
|
int max = (int) Math.ceil(plugins.size() / 9.);
|
||||||
@ -20,11 +20,11 @@ final class SongodaCoreOverviewGUI extends Gui {
|
|||||||
|
|
||||||
// TODO: this could use some decorating
|
// TODO: this could use some decorating
|
||||||
|
|
||||||
for (int i = 0; i < plugins.size(); i++) {
|
for (int i = 0; i < plugins.size(); ++i) {
|
||||||
final PluginInfo plugin = plugins.get(i);
|
final PluginInfo plugin = plugins.get(i);
|
||||||
|
|
||||||
if (plugin.hasUpdate()) {
|
if (plugin.hasUpdate()) {
|
||||||
setButton(i, GuiUtils.createButtonItem(plugin.icon != null ? plugin.icon : XMaterial.STONE,
|
setButton(i, GuiUtils.createButtonItem(plugin.getIcon() != null ? plugin.getIcon() : XMaterial.STONE,
|
||||||
ChatColor.GOLD + plugin.getJavaPlugin().getName(),
|
ChatColor.GOLD + plugin.getJavaPlugin().getName(),
|
||||||
ChatColor.GRAY + "Latest Version: " + plugin.getLatestVersion(),
|
ChatColor.GRAY + "Latest Version: " + plugin.getLatestVersion(),
|
||||||
ChatColor.GRAY + "Installed Version: " + plugin.getJavaPlugin().getDescription().getVersion(),
|
ChatColor.GRAY + "Installed Version: " + plugin.getJavaPlugin().getDescription().getVersion(),
|
||||||
@ -42,7 +42,7 @@ final class SongodaCoreOverviewGUI extends Gui {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
setButton(i, GuiUtils.createButtonItem(plugin.icon != null ? plugin.icon : XMaterial.STONE,
|
setButton(i, GuiUtils.createButtonItem(plugin.getIcon() != null ? plugin.getIcon() : XMaterial.STONE,
|
||||||
ChatColor.GOLD + plugin.getJavaPlugin().getName(),
|
ChatColor.GOLD + plugin.getJavaPlugin().getName(),
|
||||||
ChatColor.GRAY + "Installed Version: " + plugin.getJavaPlugin().getDescription().getVersion(),
|
ChatColor.GRAY + "Installed Version: " + plugin.getJavaPlugin().getDescription().getVersion(),
|
||||||
"",
|
"",
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package com.craftaro.core.data;
|
package com.craftaro.core.data;
|
||||||
|
|
||||||
public interface ComputedValue {
|
public interface ComputedValue {
|
||||||
|
|
||||||
Object compute();
|
Object compute();
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,6 @@ import org.jooq.DSLContext;
|
|||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
|
||||||
public interface DatabaseConnector {
|
public interface DatabaseConnector {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if the connection to the database has been created
|
* Checks if the connection to the database has been created
|
||||||
*
|
*
|
||||||
@ -35,5 +34,4 @@ public interface DatabaseConnector {
|
|||||||
interface ConnectionCallback {
|
interface ConnectionCallback {
|
||||||
void accept(DSLContext ctx) throws SQLException;
|
void accept(DSLContext ctx) throws SQLException;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -12,49 +12,48 @@ import java.io.File;
|
|||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class DatabaseManager {
|
public class DatabaseManager {
|
||||||
|
|
||||||
private static DatabaseManager INSTANCE;
|
private static DatabaseManager INSTANCE;
|
||||||
|
|
||||||
private final MonitoredThread thread;
|
private final MonitoredThread thread;
|
||||||
private DatabaseConnector connector;
|
private final DatabaseConnector connector;
|
||||||
|
|
||||||
private final Config databaseConfig;
|
private final Config databaseConfig;
|
||||||
|
|
||||||
public DatabaseManager(SongodaPlugin plugin) {
|
public DatabaseManager(SongodaPlugin plugin) {
|
||||||
INSTANCE = this;
|
INSTANCE = this;
|
||||||
thread = new MonitoredThread(plugin.getName().toLowerCase() + "-sql-thread", 15, TimeUnit.SECONDS);
|
this.thread = new MonitoredThread(plugin.getName().toLowerCase() + "-sql-thread", 15, TimeUnit.SECONDS);
|
||||||
databaseConfig = new Config(plugin, "database.yml");
|
this.databaseConfig = new Config(plugin, "database.yml");
|
||||||
|
|
||||||
if (!new File(plugin.getDataFolder(), "database.yml").exists())
|
if (!new File(plugin.getDataFolder(), "database.yml").exists())
|
||||||
plugin.saveResource("database.yml", false);
|
plugin.saveResource("database.yml", false);
|
||||||
databaseConfig.load();
|
this.databaseConfig.load();
|
||||||
|
|
||||||
String type = databaseConfig.getString("type", "H2").toUpperCase();
|
String type = this.databaseConfig.getString("type", "H2").toUpperCase();
|
||||||
String host = databaseConfig.getString("host", "localhost");
|
String host = this.databaseConfig.getString("host", "localhost");
|
||||||
int port = databaseConfig.getInt("port", 3306);
|
int port = this.databaseConfig.getInt("port", 3306);
|
||||||
String database = databaseConfig.getString("database", "plugin");
|
String database = this.databaseConfig.getString("database", "plugin");
|
||||||
String username = databaseConfig.getString("username", "root");
|
String username = this.databaseConfig.getString("username", "root");
|
||||||
String password = databaseConfig.getString("password", "");
|
String password = this.databaseConfig.getString("password", "");
|
||||||
int poolSize = databaseConfig.getInt("poolSize", 10);
|
int poolSize = this.databaseConfig.getInt("poolSize", 10);
|
||||||
boolean useSSL = databaseConfig.getBoolean("useSSL", false);
|
boolean useSSL = this.databaseConfig.getBoolean("useSSL", false);
|
||||||
boolean autoReconnect = databaseConfig.getBoolean("autoReconnect", true);
|
boolean autoReconnect = this.databaseConfig.getBoolean("autoReconnect", true);
|
||||||
|
|
||||||
String dataPath = plugin.getDataFolder().getPath().replaceAll("\\\\", "/") + "/";
|
String dataPath = plugin.getDataFolder().getPath().replaceAll("\\\\", "/") + "/";
|
||||||
|
|
||||||
String dbFile = "./" + dataPath + databaseConfig.getString("file", "data");
|
String dbFile = "./" + dataPath + this.databaseConfig.getString("file", "data");
|
||||||
|
|
||||||
switch (DatabaseType.valueOf(type)) {
|
switch (DatabaseType.valueOf(type)) {
|
||||||
case H2:
|
case H2:
|
||||||
connector = new H2Connector(dbFile, poolSize);
|
this.connector = new H2Connector(dbFile, poolSize);
|
||||||
break;
|
break;
|
||||||
case MYSQL:
|
case MYSQL:
|
||||||
connector = new MySQLConnector(host, port, database, username, password, useSSL, autoReconnect, poolSize);
|
this.connector = new MySQLConnector(host, port, database, username, password, useSSL, autoReconnect, poolSize);
|
||||||
break;
|
break;
|
||||||
case SQLITE:
|
case SQLITE:
|
||||||
connector = new SQLiteConnector(dbFile, poolSize);
|
this.connector = new SQLiteConnector(dbFile, poolSize);
|
||||||
break;
|
break;
|
||||||
case MARIADB:
|
case MARIADB:
|
||||||
connector = new MariaDBConnector(host, port, database, username, password, useSSL, autoReconnect, poolSize);
|
this.connector = new MariaDBConnector(host, port, database, username, password, useSSL, autoReconnect, poolSize);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Invalid database type: " + type);
|
throw new IllegalArgumentException("Invalid database type: " + type);
|
||||||
@ -66,7 +65,7 @@ public class DatabaseManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void execute(Runnable runnable, boolean nonDisruptable) {
|
public void execute(Runnable runnable, boolean nonDisruptable) {
|
||||||
thread.execute(runnable, nonDisruptable);
|
this.thread.execute(runnable, nonDisruptable);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void load(String name, Runnable load) {
|
public void load(String name, Runnable load) {
|
||||||
@ -75,11 +74,11 @@ public class DatabaseManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public DatabaseConnector getDatabaseConnector() {
|
public DatabaseConnector getDatabaseConnector() {
|
||||||
return connector;
|
return this.connector;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Config getConfig() {
|
public Config getConfig() {
|
||||||
return databaseConfig;
|
return this.databaseConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static DatabaseManager getInstance() {
|
public static DatabaseManager getInstance() {
|
||||||
|
@ -3,7 +3,6 @@ package com.craftaro.core.data;
|
|||||||
import org.jooq.SQLDialect;
|
import org.jooq.SQLDialect;
|
||||||
|
|
||||||
public enum DatabaseType {
|
public enum DatabaseType {
|
||||||
|
|
||||||
MARIADB,
|
MARIADB,
|
||||||
MYSQL,
|
MYSQL,
|
||||||
H2,
|
H2,
|
||||||
|
@ -3,8 +3,6 @@ package com.craftaro.core.data;
|
|||||||
import org.jooq.DSLContext;
|
import org.jooq.DSLContext;
|
||||||
|
|
||||||
public interface LoadsData {
|
public interface LoadsData {
|
||||||
|
|
||||||
|
|
||||||
default void loadData() {
|
default void loadData() {
|
||||||
DatabaseManager.getInstance().getDatabaseConnector().connect(false, ctx -> {
|
DatabaseManager.getInstance().getDatabaseConnector().connect(false, ctx -> {
|
||||||
setupTables(ctx);
|
setupTables(ctx);
|
||||||
@ -15,5 +13,4 @@ public interface LoadsData {
|
|||||||
void loadDataImpl(DSLContext ctx);
|
void loadDataImpl(DSLContext ctx);
|
||||||
|
|
||||||
void setupTables(DSLContext ctx);
|
void setupTables(DSLContext ctx);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,6 @@ import org.jooq.impl.DSL;
|
|||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
|
||||||
public class SQLBase {
|
public class SQLBase {
|
||||||
|
|
||||||
protected final DSLContext ctx;
|
protected final DSLContext ctx;
|
||||||
|
|
||||||
public SQLBase(DSLContext ctx) {
|
public SQLBase(DSLContext ctx) {
|
||||||
@ -39,8 +38,10 @@ public class SQLBase {
|
|||||||
|
|
||||||
protected Field getField(String field, Class<?> type) {
|
protected Field getField(String field, Class<?> type) {
|
||||||
String fieldFinal = "`" + field + "`";
|
String fieldFinal = "`" + field + "`";
|
||||||
if (type == boolean.class)
|
if (type == boolean.class) {
|
||||||
return DSL.field(fieldFinal, int.class);
|
return DSL.field(fieldFinal, int.class);
|
||||||
|
}
|
||||||
|
|
||||||
return type == null ? DSL.field(fieldFinal) : DSL.field(fieldFinal, type);
|
return type == null ? DSL.field(fieldFinal) : DSL.field(fieldFinal, type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,41 +8,42 @@ import java.util.LinkedList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class SQLBatch implements SavesData {
|
public class SQLBatch implements SavesData {
|
||||||
|
|
||||||
private final List<SavesData> batch = new LinkedList<>();
|
private final List<SavesData> batch = new LinkedList<>();
|
||||||
|
|
||||||
public SQLBatch add(SavesData... data) {
|
public SQLBatch add(SavesData... data) {
|
||||||
batch.addAll(Arrays.asList(data));
|
this.batch.addAll(Arrays.asList(data));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLBatch addAll(Collection<? extends SavesData> data) {
|
public SQLBatch addAll(Collection<? extends SavesData> data) {
|
||||||
batch.addAll(data);
|
this.batch.addAll(data);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<SavesData> getBatch() {
|
public List<SavesData> getBatch() {
|
||||||
return batch;
|
return this.batch;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void save(String... columns) {
|
public void save(String... columns) {
|
||||||
DatabaseManager.getInstance().getDatabaseConnector().connect(ctx -> {
|
DatabaseManager.getInstance().getDatabaseConnector().connect(ctx -> {
|
||||||
for (SavesData data : batch)
|
for (SavesData data : this.batch) {
|
||||||
data.saveImpl(ctx, columns);
|
data.saveImpl(ctx, columns);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void saveImpl(DSLContext ctx, String... columns) {
|
public void saveImpl(DSLContext ctx, String... columns) {
|
||||||
for (SavesData data : batch)
|
for (SavesData data : this.batch) {
|
||||||
data.saveImpl(ctx, columns);
|
data.saveImpl(ctx, columns);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void deleteImpl(DSLContext ctx) {
|
public void deleteImpl(DSLContext ctx) {
|
||||||
for (SavesData data : batch)
|
for (SavesData data : this.batch) {
|
||||||
data.deleteImpl(ctx);
|
data.deleteImpl(ctx);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,6 @@ import org.jooq.DSLContext;
|
|||||||
import org.jooq.impl.DSL;
|
import org.jooq.impl.DSL;
|
||||||
|
|
||||||
public class SQLDelete extends SQLBase {
|
public class SQLDelete extends SQLBase {
|
||||||
|
|
||||||
private SQLDelete(DSLContext ctx) {
|
private SQLDelete(DSLContext ctx) {
|
||||||
super(ctx);
|
super(ctx);
|
||||||
}
|
}
|
||||||
@ -14,11 +13,11 @@ public class SQLDelete extends SQLBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void delete(String table, String id, Object value) {
|
public void delete(String table, String id, Object value) {
|
||||||
new SQLExecutable(ctx, ctx.delete(DSL.table(table)).where(DSL.field(id).eq(value))).execute();
|
new SQLExecutable(this.ctx, this.ctx.delete(DSL.table(table)).where(DSL.field(id).eq(value))).execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void delete(String table, String id, Object value, String id2, Object value2) {
|
public void delete(String table, String id, Object value, String id2, Object value2) {
|
||||||
new SQLExecutable(ctx, ctx.delete(DSL.table(table)).where(DSL.field(id).eq(value))
|
new SQLExecutable(this.ctx, this.ctx.delete(DSL.table(table)).where(DSL.field(id).eq(value))
|
||||||
.and(DSL.field(id2).eq(value2))).execute();
|
.and(DSL.field(id2).eq(value2))).execute();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,6 @@ import java.util.List;
|
|||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
public class SQLExecutable extends SQLBase {
|
public class SQLExecutable extends SQLBase {
|
||||||
|
|
||||||
protected Query query;
|
protected Query query;
|
||||||
|
|
||||||
public SQLExecutable(DSLContext ctx, Query query) {
|
public SQLExecutable(DSLContext ctx, Query query) {
|
||||||
@ -18,14 +17,18 @@ public class SQLExecutable extends SQLBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int execute() {
|
public int execute() {
|
||||||
return query.execute();
|
return this.query.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Stream<SQLResult.StoredRecord> get() {
|
public Stream<SQLResult.StoredRecord> get() {
|
||||||
if (query instanceof ResultQuery) {
|
if (this.query instanceof ResultQuery) {
|
||||||
ResultQuery<?> resultQuery = (ResultQuery<?>) query;
|
ResultQuery<?> resultQuery = (ResultQuery<?>) this.query;
|
||||||
Result<?> result = resultQuery.getResult();
|
Result<?> result = resultQuery.getResult();
|
||||||
return result.stream().map(SQLResult::new).map(SQLResult::getResults).flatMap(List::stream);
|
return result
|
||||||
|
.stream()
|
||||||
|
.map(SQLResult::new)
|
||||||
|
.map(SQLResult::getResults)
|
||||||
|
.flatMap(List::stream);
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalStateException("Query is not an instance of ResultQuery");
|
throw new IllegalStateException("Query is not an instance of ResultQuery");
|
||||||
}
|
}
|
||||||
|
@ -15,7 +15,6 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public class SQLInsert extends SQLBase {
|
public class SQLInsert extends SQLBase {
|
||||||
|
|
||||||
private String table;
|
private String table;
|
||||||
private final Map<String, Object> fields = new LinkedHashMap<>();
|
private final Map<String, Object> fields = new LinkedHashMap<>();
|
||||||
private boolean voidedKey = false;
|
private boolean voidedKey = false;
|
||||||
@ -36,55 +35,58 @@ public class SQLInsert extends SQLBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SQLInsert withField(String field, Object value, boolean voidKey) {
|
public SQLInsert withField(String field, Object value, boolean voidKey) {
|
||||||
if (voidKey)
|
if (voidKey) {
|
||||||
voidedKey = true;
|
this.voidedKey = true;
|
||||||
|
}
|
||||||
return voidKey ? this : withField(field, value);
|
return voidKey ? this : withField(field, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLInsert withField(String field, Object value) {
|
public SQLInsert withField(String field, Object value) {
|
||||||
if (field.equalsIgnoreCase("desc"))
|
if (field.equalsIgnoreCase("desc")) {
|
||||||
field = "`desc`";
|
field = "`desc`";
|
||||||
fields.put(field.toLowerCase(), value);
|
}
|
||||||
|
this.fields.put(field.toLowerCase(), value);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
// For some reason this must be used before we submit. So I'm going to apply the values here.
|
// For some reason, this must be used before we submit. So I'm going to apply the values here.
|
||||||
public SQLExecutable onDuplicateKeyUpdate(String... columns) {
|
public SQLExecutable onDuplicateKeyUpdate(String... columns) {
|
||||||
currentStep = ctx.insertInto(DSL.table(table), fields.keySet().stream().map(DSL::field).toArray(Field[]::new));
|
this.currentStep = this.ctx.insertInto(DSL.table(this.table), this.fields.keySet().stream().map(DSL::field).toArray(Field[]::new));
|
||||||
currentStep = currentStep.values(fields.values().stream().map(this::cleanValue).toArray());
|
this.currentStep = this.currentStep.values(this.fields.values().stream().map(this::cleanValue).toArray());
|
||||||
|
|
||||||
if (voidedKey)
|
if (this.voidedKey) {
|
||||||
return new SQLExecutable(ctx, currentStep);
|
return new SQLExecutable(this.ctx, this.currentStep);
|
||||||
|
}
|
||||||
|
|
||||||
SQLOnDupeUpdate sqlOnDupeUpdate = new SQLOnDupeUpdate(ctx, currentStep, columns);
|
SQLOnDupeUpdate sqlOnDupeUpdate = new SQLOnDupeUpdate(this.ctx, this.currentStep, columns);
|
||||||
for (String column : (columns.length > 0 ? new HashSet<>(Arrays.asList(columns)) : fields.keySet()))
|
for (String column : (columns.length > 0 ? new HashSet<>(Arrays.asList(columns)) : this.fields.keySet())) {
|
||||||
sqlOnDupeUpdate.set(column.replace("`", ""), fields.get(column.toLowerCase()));
|
sqlOnDupeUpdate.set(column.replace("`", ""), this.fields.get(column.toLowerCase()));
|
||||||
|
}
|
||||||
return sqlOnDupeUpdate;
|
return sqlOnDupeUpdate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class SQLOnDupeUpdate extends SQLExecutable {
|
public static class SQLOnDupeUpdate extends SQLExecutable {
|
||||||
|
|
||||||
private InsertOnDuplicateSetStep currentStep;
|
private InsertOnDuplicateSetStep currentStep;
|
||||||
private final List<String> columnsToUpdate = new ArrayList<>();
|
private final List<String> columnsToUpdate = new ArrayList<>();
|
||||||
|
|
||||||
|
|
||||||
public SQLOnDupeUpdate(DSLContext ctx, InsertValuesStepN currentStep, String... columns) {
|
public SQLOnDupeUpdate(DSLContext ctx, InsertValuesStepN currentStep, String... columns) {
|
||||||
super(ctx, null);
|
super(ctx, null);
|
||||||
this.currentStep = currentStep.onDuplicateKeyUpdate();
|
this.currentStep = currentStep.onDuplicateKeyUpdate();
|
||||||
columnsToUpdate.addAll(Arrays.asList(columns));
|
this.columnsToUpdate.addAll(Arrays.asList(columns));
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLOnDupeUpdate set(String field, Object value) {
|
public SQLOnDupeUpdate set(String field, Object value) {
|
||||||
if (!columnsToUpdate.isEmpty() && !columnsToUpdate.contains(field))
|
if (!this.columnsToUpdate.isEmpty() && !this.columnsToUpdate.contains(field)) {
|
||||||
return this;
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
value = cleanValue(value);
|
value = cleanValue(value);
|
||||||
Field fieldName = getField(field, value == null ? null : value.getClass());
|
Field fieldName = getField(field, value == null ? null : value.getClass());
|
||||||
|
|
||||||
if (currentStep != null) {
|
if (this.currentStep != null) {
|
||||||
this.query = value == null ? this.currentStep.setNull(fieldName)
|
this.query = value == null ? this.currentStep.setNull(fieldName)
|
||||||
: this.currentStep.set(fieldName, value);
|
: this.currentStep.set(fieldName, value);
|
||||||
currentStep = null;
|
this.currentStep = null;
|
||||||
} else {
|
} else {
|
||||||
this.query = value == null ? ((InsertOnDuplicateSetMoreStep) this.query).setNull(fieldName)
|
this.query = value == null ? ((InsertOnDuplicateSetMoreStep) this.query).setNull(fieldName)
|
||||||
: ((InsertOnDuplicateSetMoreStep) this.query).set(fieldName, value);
|
: ((InsertOnDuplicateSetMoreStep) this.query).set(fieldName, value);
|
||||||
|
@ -19,7 +19,7 @@ public class SQLResult {
|
|||||||
Object value = record.get(fieldName);
|
Object value = record.get(fieldName);
|
||||||
map.put(fieldName, new StoredData(value));
|
map.put(fieldName, new StoredData(value));
|
||||||
}
|
}
|
||||||
results.add(new StoredRecord(map));
|
this.results.add(new StoredRecord(map));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -30,11 +30,11 @@ public class SQLResult {
|
|||||||
Object value = record.get(fieldName);
|
Object value = record.get(fieldName);
|
||||||
map.put(fieldName, new StoredData(value));
|
map.put(fieldName, new StoredData(value));
|
||||||
}
|
}
|
||||||
results.add(new StoredRecord(map));
|
this.results.add(new StoredRecord(map));
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<StoredRecord> getResults() {
|
public List<StoredRecord> getResults() {
|
||||||
return results;
|
return this.results;
|
||||||
}
|
}
|
||||||
|
|
||||||
public interface SQLResultI {
|
public interface SQLResultI {
|
||||||
@ -49,15 +49,15 @@ public class SQLResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public StoredData get(String key) {
|
public StoredData get(String key) {
|
||||||
return record.get(key);
|
return this.record.get(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean has(String key) {
|
public boolean has(String key) {
|
||||||
return record.containsKey(key) && record.get(key).asString() != null;
|
return this.record.containsKey(key) && this.record.get(key).asString() != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isNull(String key) {
|
public boolean isNull(String key) {
|
||||||
return record.containsKey(key) && record.get(key).isNull();
|
return this.record.containsKey(key) && this.record.get(key).isNull();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,6 @@ import org.jooq.SelectWhereStep;
|
|||||||
import org.jooq.impl.DSL;
|
import org.jooq.impl.DSL;
|
||||||
|
|
||||||
public class SQLSelect extends SQLBase {
|
public class SQLSelect extends SQLBase {
|
||||||
|
|
||||||
private Select<?> currentStep;
|
private Select<?> currentStep;
|
||||||
|
|
||||||
public SQLSelect(DSLContext ctx) {
|
public SQLSelect(DSLContext ctx) {
|
||||||
@ -22,23 +21,23 @@ public class SQLSelect extends SQLBase {
|
|||||||
|
|
||||||
public SQLSelect select(String... fields) {
|
public SQLSelect select(String... fields) {
|
||||||
if (fields.length > 0) {
|
if (fields.length > 0) {
|
||||||
currentStep = ctx.select(DSL.field(fields[0]));
|
this.currentStep = this.ctx.select(DSL.field(fields[0]));
|
||||||
for (int i = 1; i < fields.length; i++) {
|
for (int i = 1; i < fields.length; i++) {
|
||||||
currentStep = ((SelectSelectStep<?>)currentStep).select(DSL.field(fields[i]));
|
this.currentStep = ((SelectSelectStep<?>) this.currentStep).select(DSL.field(fields[i]));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
currentStep = ctx.select();
|
this.currentStep = this.ctx.select();
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLSelect from(String table) {
|
public SQLSelect from(String table) {
|
||||||
currentStep = ((SelectSelectStep<?>)currentStep).from(DSL.table(table));
|
this.currentStep = ((SelectSelectStep<?>) this.currentStep).from(DSL.table(table));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void from(String table, SQLResult.SQLResultI result) {
|
public void from(String table, SQLResult.SQLResultI result) {
|
||||||
Result<?> resultData = ((SelectSelectStep<?>)currentStep).from(DSL.table(table)).fetch();
|
Result<?> resultData = ((SelectSelectStep<?>) this.currentStep).from(DSL.table(table)).fetch();
|
||||||
SQLResult rs = new SQLResult(resultData);
|
SQLResult rs = new SQLResult(resultData);
|
||||||
for (SQLResult.StoredRecord record : rs.getResults()) {
|
for (SQLResult.StoredRecord record : rs.getResults()) {
|
||||||
result.forEach(record);
|
result.forEach(record);
|
||||||
@ -46,12 +45,12 @@ public class SQLSelect extends SQLBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SQLWhere where(String id, Object value) {
|
public SQLWhere where(String id, Object value) {
|
||||||
currentStep = ((SelectWhereStep<?>)currentStep).where(DSL.field(id).eq(value));
|
this.currentStep = ((SelectWhereStep<?>) this.currentStep).where(DSL.field(id).eq(value));
|
||||||
return new SQLWhere(ctx, currentStep);
|
return new SQLWhere(this.ctx, this.currentStep);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLWhere whereBetween(String id, Object value1, Object value2) {
|
public SQLWhere whereBetween(String id, Object value1, Object value2) {
|
||||||
currentStep = ((SelectWhereStep<?>)currentStep).where(DSL.field(id).between(value1, value2));
|
this.currentStep = ((SelectWhereStep<?>) this.currentStep).where(DSL.field(id).between(value1, value2));
|
||||||
return new SQLWhere(ctx, currentStep);
|
return new SQLWhere(this.ctx, this.currentStep);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,14 +11,13 @@ import java.util.Arrays;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class SQLUpdate extends SQLBase {
|
public class SQLUpdate extends SQLBase {
|
||||||
|
|
||||||
private final List<String> columnsToUpdate = new ArrayList<>();
|
private final List<String> columnsToUpdate = new ArrayList<>();
|
||||||
|
|
||||||
private UpdateSetStep currentStep;
|
private UpdateSetStep currentStep;
|
||||||
|
|
||||||
private SQLUpdate(DSLContext ctx, String... columns) {
|
private SQLUpdate(DSLContext ctx, String... columns) {
|
||||||
super(ctx);
|
super(ctx);
|
||||||
columnsToUpdate.addAll(Arrays.asList(columns));
|
this.columnsToUpdate.addAll(Arrays.asList(columns));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static SQLUpdate create(DSLContext ctx, String... columns) {
|
public static SQLUpdate create(DSLContext ctx, String... columns) {
|
||||||
@ -26,13 +25,14 @@ public class SQLUpdate extends SQLBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SQLUpdate update(String table) {
|
public SQLUpdate update(String table) {
|
||||||
this.currentStep = ctx.update(DSL.table(table));
|
this.currentStep = this.ctx.update(DSL.table(table));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLUpdate set(String field, Object value) {
|
public SQLUpdate set(String field, Object value) {
|
||||||
if (!columnsToUpdate.isEmpty() && !columnsToUpdate.contains(field))
|
if (!this.columnsToUpdate.isEmpty() && !this.columnsToUpdate.contains(field)) {
|
||||||
return this;
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
value = cleanValue(value);
|
value = cleanValue(value);
|
||||||
Field fieldName = getField(field, value == null ? null : value.getClass());
|
Field fieldName = getField(field, value == null ? null : value.getClass());
|
||||||
@ -42,6 +42,6 @@ public class SQLUpdate extends SQLBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public SQLWhere where(String id, Object value) {
|
public SQLWhere where(String id, Object value) {
|
||||||
return new SQLWhere(ctx, ((UpdateSetMoreStep) this.currentStep).where(DSL.field(id).eq(value)));
|
return new SQLWhere(this.ctx, ((UpdateSetMoreStep) this.currentStep).where(DSL.field(id).eq(value)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,18 +6,17 @@ import org.jooq.UpdateConditionStep;
|
|||||||
import org.jooq.impl.DSL;
|
import org.jooq.impl.DSL;
|
||||||
|
|
||||||
public class SQLWhere extends SQLExecutable {
|
public class SQLWhere extends SQLExecutable {
|
||||||
|
|
||||||
public SQLWhere(DSLContext ctx, Query query) {
|
public SQLWhere(DSLContext ctx, Query query) {
|
||||||
super(ctx, query);
|
super(ctx, query);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLWhere and(String id, Object value) {
|
public SQLWhere and(String id, Object value) {
|
||||||
query = ((UpdateConditionStep) query).and(DSL.field(id).eq(value));
|
this.query = ((UpdateConditionStep) this.query).and(DSL.field(id).eq(value));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLWhere or(String id, Object value) {
|
public SQLWhere or(String id, Object value) {
|
||||||
query = ((UpdateConditionStep) query).or(DSL.field(id).eq(value));
|
this.query = ((UpdateConditionStep) this.query).or(DSL.field(id).eq(value));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,6 @@ import org.jooq.Result;
|
|||||||
import org.jooq.impl.DSL;
|
import org.jooq.impl.DSL;
|
||||||
|
|
||||||
public interface SavesData {
|
public interface SavesData {
|
||||||
|
|
||||||
default void save(String... columns) {
|
default void save(String... columns) {
|
||||||
DatabaseManager.getInstance().getDatabaseConnector().connect(ctx ->
|
DatabaseManager.getInstance().getDatabaseConnector().connect(ctx ->
|
||||||
saveImpl(ctx, columns));
|
saveImpl(ctx, columns));
|
||||||
@ -32,8 +31,8 @@ public interface SavesData {
|
|||||||
Result<Record1<Object>> results = ctx.select(DSL.field("id")).from(DSL.table(table)).orderBy(DSL.field("id").desc()).fetch();
|
Result<Record1<Object>> results = ctx.select(DSL.field("id")).from(DSL.table(table)).orderBy(DSL.field("id").desc()).fetch();
|
||||||
Record1<Object> result = results.get(0);
|
Record1<Object> result = results.get(0);
|
||||||
return result != null ? result.get(DSL.field("id"), Integer.class) : -1;
|
return result != null ? result.get(DSL.field("id"), Integer.class) : -1;
|
||||||
} catch (Exception e) {
|
} catch (Exception ex) {
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,6 @@ import java.time.Instant;
|
|||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public class StoredData {
|
public class StoredData {
|
||||||
|
|
||||||
private Object object;
|
private Object object;
|
||||||
|
|
||||||
public StoredData(Object object) {
|
public StoredData(Object object) {
|
||||||
@ -15,16 +14,20 @@ public class StoredData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Object getObject() {
|
public Object getObject() {
|
||||||
return object;
|
return this.object;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String asString() {
|
public String asString() {
|
||||||
if (object == null) return null;
|
if (this.object == null) {
|
||||||
return object.toString();
|
return null;
|
||||||
|
}
|
||||||
|
return this.object.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public int asInt() {
|
public int asInt() {
|
||||||
if (object == null) return 0;
|
if (this.object == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
return Integer.parseInt(asString());
|
return Integer.parseInt(asString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -34,7 +37,9 @@ public class StoredData {
|
|||||||
|
|
||||||
public long asLong() {
|
public long asLong() {
|
||||||
String string = asString();
|
String string = asString();
|
||||||
if (string == null) return 0;
|
if (string == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
return Long.parseLong(string);
|
return Long.parseLong(string);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,8 +52,9 @@ public class StoredData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean asBoolean() {
|
public boolean asBoolean() {
|
||||||
if (object instanceof Integer)
|
if (this.object instanceof Integer) {
|
||||||
return (int) object == 1;
|
return (int) this.object == 1;
|
||||||
|
}
|
||||||
return Boolean.parseBoolean(asString());
|
return Boolean.parseBoolean(asString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,12 +63,12 @@ public class StoredData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean isNull() {
|
public boolean isNull() {
|
||||||
return object == null;
|
return this.object == null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// get longblob
|
// get longblob
|
||||||
public byte[] asBytes() {
|
public byte[] asBytes() {
|
||||||
return (byte[]) object;
|
return (byte[]) this.object;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UUID asUniqueID() {
|
public UUID asUniqueID() {
|
||||||
|
@ -50,9 +50,10 @@ public class H2Connector implements DatabaseConnector {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (sqlThread)
|
if (sqlThread) {
|
||||||
DatabaseManager.getInstance().execute(runnable);
|
DatabaseManager.getInstance().execute(runnable);
|
||||||
else
|
} else {
|
||||||
runnable.run();
|
runnable.run();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -53,7 +53,10 @@ public class MariaDBConnector implements DatabaseConnector {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (sqlThread) DatabaseManager.getInstance().execute(runnable);
|
if (sqlThread) {
|
||||||
else runnable.run();
|
DatabaseManager.getInstance().execute(runnable);
|
||||||
|
} else {
|
||||||
|
runnable.run();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,6 @@ import org.jooq.impl.DSL;
|
|||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
|
|
||||||
public class MySQLConnector implements DatabaseConnector {
|
public class MySQLConnector implements DatabaseConnector {
|
||||||
|
|
||||||
private HikariDataSource hikari;
|
private HikariDataSource hikari;
|
||||||
private boolean initializedSuccessfully;
|
private boolean initializedSuccessfully;
|
||||||
|
|
||||||
@ -52,10 +51,11 @@ public class MySQLConnector implements DatabaseConnector {
|
|||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
if (sqlThread)
|
if (sqlThread) {
|
||||||
DatabaseManager.getInstance().execute(runnable);
|
DatabaseManager.getInstance().execute(runnable);
|
||||||
else
|
} else {
|
||||||
runnable.run();
|
runnable.run();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -49,9 +49,10 @@ public class SQLiteConnector implements DatabaseConnector {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (sqlThread)
|
if (sqlThread) {
|
||||||
DatabaseManager.getInstance().execute(runnable);
|
DatabaseManager.getInstance().execute(runnable);
|
||||||
else
|
} else {
|
||||||
runnable.run();
|
runnable.run();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,16 +3,15 @@ package com.craftaro.core.data.lazy;
|
|||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
public class Lazy<T> {
|
public class Lazy<T> {
|
||||||
|
|
||||||
private Supplier<T> supplier = null;
|
private Supplier<T> supplier = null;
|
||||||
private T value = null;
|
private T value = null;
|
||||||
|
|
||||||
public synchronized T get() {
|
public synchronized T get() {
|
||||||
if (value == null && supplier != null) {
|
if (this.value == null && this.supplier != null) {
|
||||||
value = supplier.get();
|
this.value = this.supplier.get();
|
||||||
supplier = null;
|
this.supplier = null;
|
||||||
}
|
}
|
||||||
return value;
|
return this.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized T getOrDefault(T def) {
|
public synchronized T getOrDefault(T def) {
|
||||||
@ -21,7 +20,7 @@ public class Lazy<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public synchronized Lazy<T> reset() {
|
public synchronized Lazy<T> reset() {
|
||||||
value = null;
|
this.value = null;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,7 +35,7 @@ public class Lazy<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public synchronized boolean isLoaded() {
|
public synchronized boolean isLoaded() {
|
||||||
return supplier != null;
|
return this.supplier != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -7,60 +7,66 @@ import java.util.Set;
|
|||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
public class LazyList<T> {
|
public class LazyList<T> {
|
||||||
|
|
||||||
private final List<T> list;
|
private final List<T> list;
|
||||||
private List<Lazy<T>> lazyList;
|
private List<Lazy<T>> lazyList;
|
||||||
|
|
||||||
public LazyList(List list) {
|
public LazyList(List<T> list) {
|
||||||
this.list = list == null ? new LinkedList<>() : list;
|
this.list = list == null ? new LinkedList<>() : list;
|
||||||
this.lazyList = new LinkedList<>();
|
this.lazyList = new LinkedList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<T> getList() {
|
public List<T> getList() {
|
||||||
loadList();
|
loadList();
|
||||||
return list;
|
return this.list;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Set<T> getSet() {
|
public Set<T> getSet() {
|
||||||
loadList();
|
loadList();
|
||||||
return new HashSet<>(list);
|
return new HashSet<>(this.list);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void add(Supplier<T> supplier) {
|
public void add(Supplier<T> supplier) {
|
||||||
if (lazyList == null)
|
if (this.lazyList == null) {
|
||||||
list.add(supplier.get());
|
this.list.add(supplier.get());
|
||||||
else if (supplier != null)
|
} else if (supplier != null) {
|
||||||
lazyList.add(new Lazy<T>().set(supplier));
|
this.lazyList.add(new Lazy<T>().set(supplier));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void add(T items) {
|
public void add(T items) {
|
||||||
list.add(items);
|
this.list.add(items);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addAll(List<T> items) {
|
public void addAll(List<T> items) {
|
||||||
list.addAll(items);
|
this.list.addAll(items);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addAll(Supplier<T>... suppliers) {
|
public void addAll(Supplier<T>... suppliers) {
|
||||||
for (Supplier<T> supplier : suppliers)
|
for (Supplier<T> supplier : suppliers) {
|
||||||
add(supplier);
|
add(supplier);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void loadList() {
|
private void loadList() {
|
||||||
if (lazyList == null) return;
|
if (this.lazyList == null) {
|
||||||
for (Lazy<T> lazy : lazyList)
|
return;
|
||||||
list.add(lazy.get());
|
}
|
||||||
lazyList = null;
|
|
||||||
|
for (Lazy<T> lazy : this.lazyList) {
|
||||||
|
this.list.add(lazy.get());
|
||||||
|
}
|
||||||
|
this.lazyList = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void clear() {
|
public void clear() {
|
||||||
list.clear();
|
this.list.clear();
|
||||||
lazyList.clear();
|
this.lazyList.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isEmpty() {
|
public boolean isEmpty() {
|
||||||
if (lazyList != null)
|
if (this.lazyList != null) {
|
||||||
return lazyList.isEmpty();
|
return this.lazyList.isEmpty();
|
||||||
return list.isEmpty();
|
}
|
||||||
|
return this.list.isEmpty();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,6 @@ import java.util.Map;
|
|||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public interface Data {
|
public interface Data {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the auto increment id of this data
|
* Gets the auto increment id of this data
|
||||||
*
|
*
|
||||||
@ -40,6 +39,7 @@ public interface Data {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* No plugin prefix is required for the table
|
* No plugin prefix is required for the table
|
||||||
|
*
|
||||||
* @return The table name where the data should be stored
|
* @return The table name where the data should be stored
|
||||||
*/
|
*/
|
||||||
String getTableName();
|
String getTableName();
|
||||||
|
@ -78,30 +78,30 @@ public class DataManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void load(DatabaseType forcedType) throws SQLException {
|
private void load(DatabaseType forcedType) throws SQLException {
|
||||||
String databaseType = databaseConfig.getString("Connection Settings.Type").toUpperCase();
|
String databaseType = this.databaseConfig.getString("Connection Settings.Type").toUpperCase();
|
||||||
if (forcedType != null) {
|
if (forcedType != null) {
|
||||||
databaseType = forcedType.name();
|
databaseType = forcedType.name();
|
||||||
}
|
}
|
||||||
switch (databaseType) {
|
switch (databaseType) {
|
||||||
case "MYSQL": {
|
case "MYSQL": {
|
||||||
this.databaseConnector = new MySQLConnector(plugin, databaseConfig);
|
this.databaseConnector = new MySQLConnector(this.plugin, this.databaseConfig);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "MARIADB": {
|
case "MARIADB": {
|
||||||
this.databaseConnector = new MariaDBConnector(plugin, databaseConfig);
|
this.databaseConnector = new MariaDBConnector(this.plugin, this.databaseConfig);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "SQLITE": {
|
case "SQLITE": {
|
||||||
this.databaseConnector = new SQLiteConnector(plugin);
|
this.databaseConnector = new SQLiteConnector(this.plugin);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default: {
|
default: {
|
||||||
this.databaseConnector = new H2Connector(plugin);
|
this.databaseConnector = new H2Connector(this.plugin);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.type = databaseConnector.getType();
|
this.type = this.databaseConnector.getType();
|
||||||
this.plugin.getLogger().info("Data handler connected using " + databaseConnector.getType().name() + ".");
|
this.plugin.getLogger().info("Data handler connected using " + this.databaseConnector.getType().name() + ".");
|
||||||
|
|
||||||
runMigrations();
|
runMigrations();
|
||||||
}
|
}
|
||||||
@ -110,14 +110,14 @@ public class DataManager {
|
|||||||
* @return the database connector
|
* @return the database connector
|
||||||
*/
|
*/
|
||||||
public DatabaseConnector getDatabaseConnector() {
|
public DatabaseConnector getDatabaseConnector() {
|
||||||
return databaseConnector;
|
return this.databaseConnector;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return the database executor service
|
* @return the database executor service
|
||||||
*/
|
*/
|
||||||
public ExecutorService getAsyncPool() {
|
public ExecutorService getAsyncPool() {
|
||||||
return asyncPool;
|
return this.asyncPool;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -216,7 +216,7 @@ public class DataManager {
|
|||||||
public synchronized int getNextId(String table) {
|
public synchronized int getNextId(String table) {
|
||||||
String prefixedTable = getTablePrefix() + table;
|
String prefixedTable = getTablePrefix() + table;
|
||||||
if (!this.autoIncrementCache.containsKey(prefixedTable)) {
|
if (!this.autoIncrementCache.containsKey(prefixedTable)) {
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
// context.select(DSL.max(DSL.field("id"))).from(prefixedTable).fetchOptional().ifPresentOrElse(record -> {
|
// context.select(DSL.max(DSL.field("id"))).from(prefixedTable).fetchOptional().ifPresentOrElse(record -> {
|
||||||
// if (record.get(0, Integer.class) == null) {
|
// if (record.get(0, Integer.class) == null) {
|
||||||
// this.autoIncrementCache.put(prefixedTable, new AtomicInteger(1));
|
// this.autoIncrementCache.put(prefixedTable, new AtomicInteger(1));
|
||||||
@ -238,13 +238,13 @@ public class DataManager {
|
|||||||
return this.autoIncrementCache.get(prefixedTable).incrementAndGet();
|
return this.autoIncrementCache.get(prefixedTable).incrementAndGet();
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: Fix/create javadocs for all methods
|
// TODO: Fix/create javadocs for all methods
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Saves the data to the database
|
* Saves the data to the database
|
||||||
*/
|
*/
|
||||||
public void save(Data data) {
|
public void save(Data data) {
|
||||||
asyncPool.execute(() -> {
|
this.asyncPool.execute(() -> {
|
||||||
saveSync(data);
|
saveSync(data);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -253,7 +253,7 @@ public class DataManager {
|
|||||||
* Saves the data to the database
|
* Saves the data to the database
|
||||||
*/
|
*/
|
||||||
public void save(Data data, String idField, Object idValue) {
|
public void save(Data data, String idField, Object idValue) {
|
||||||
asyncPool.execute(() -> {
|
this.asyncPool.execute(() -> {
|
||||||
saveSync(data, idField, idValue);
|
saveSync(data, idField, idValue);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -262,7 +262,7 @@ public class DataManager {
|
|||||||
* Saves the data to the database
|
* Saves the data to the database
|
||||||
*/
|
*/
|
||||||
public void saveSync(Data data, String idField, Object idValue) {
|
public void saveSync(Data data, String idField, Object idValue) {
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
||||||
.set(data.serialize())
|
.set(data.serialize())
|
||||||
.onConflict(DSL.field(idField)).doUpdate()
|
.onConflict(DSL.field(idField)).doUpdate()
|
||||||
@ -276,7 +276,7 @@ public class DataManager {
|
|||||||
* Saves the data to the database synchronously
|
* Saves the data to the database synchronously
|
||||||
*/
|
*/
|
||||||
public void saveSync(Data data) {
|
public void saveSync(Data data) {
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
||||||
.set(data.serialize())
|
.set(data.serialize())
|
||||||
.onConflict(data.getId() != -1 ? DSL.field("id") : DSL.field("uuid")).doUpdate()
|
.onConflict(data.getId() != -1 ? DSL.field("id") : DSL.field("uuid")).doUpdate()
|
||||||
@ -290,7 +290,7 @@ public class DataManager {
|
|||||||
* Saves the data in batch to the database
|
* Saves the data in batch to the database
|
||||||
*/
|
*/
|
||||||
public void saveBatch(Collection<Data> dataBatch) {
|
public void saveBatch(Collection<Data> dataBatch) {
|
||||||
asyncPool.execute(() -> {
|
this.asyncPool.execute(() -> {
|
||||||
saveBatchSync(dataBatch);
|
saveBatchSync(dataBatch);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -299,7 +299,7 @@ public class DataManager {
|
|||||||
* Saves the data in batch to the database
|
* Saves the data in batch to the database
|
||||||
*/
|
*/
|
||||||
public void saveBatchSync(Collection<Data> dataBatch) {
|
public void saveBatchSync(Collection<Data> dataBatch) {
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
List<Query> queries = new ArrayList<>();
|
List<Query> queries = new ArrayList<>();
|
||||||
for (Data data : dataBatch) {
|
for (Data data : dataBatch) {
|
||||||
queries.add(context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
queries.add(context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
||||||
@ -317,7 +317,7 @@ public class DataManager {
|
|||||||
* Deletes the data from the database
|
* Deletes the data from the database
|
||||||
*/
|
*/
|
||||||
public void delete(Data data) {
|
public void delete(Data data) {
|
||||||
asyncPool.execute(() -> {
|
this.asyncPool.execute(() -> {
|
||||||
deleteSync(data);
|
deleteSync(data);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -326,7 +326,7 @@ public class DataManager {
|
|||||||
* Deletes the data from the database
|
* Deletes the data from the database
|
||||||
*/
|
*/
|
||||||
public void deleteSync(Data data) {
|
public void deleteSync(Data data) {
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
||||||
.where(data.getId() != -1 ? DSL.field("id").eq(data.getId()) : DSL.field("uuid").eq(data.getUniqueId().toString()))
|
.where(data.getId() != -1 ? DSL.field("id").eq(data.getId()) : DSL.field("uuid").eq(data.getUniqueId().toString()))
|
||||||
.execute();
|
.execute();
|
||||||
@ -334,13 +334,13 @@ public class DataManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void delete(Data data, String idField, Object idValue) {
|
public void delete(Data data, String idField, Object idValue) {
|
||||||
asyncPool.execute(() -> {
|
this.asyncPool.execute(() -> {
|
||||||
deleteSync(data, idField, idValue);
|
deleteSync(data, idField, idValue);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deleteSync(Data data, String idField, Object idValue) {
|
public void deleteSync(Data data, String idField, Object idValue) {
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
||||||
.where(DSL.field(idField).eq(idValue))
|
.where(DSL.field(idField).eq(idValue))
|
||||||
.execute();
|
.execute();
|
||||||
@ -351,8 +351,8 @@ public class DataManager {
|
|||||||
* Deletes the data from the database
|
* Deletes the data from the database
|
||||||
*/
|
*/
|
||||||
public void delete(Data data, String uuidColumn) {
|
public void delete(Data data, String uuidColumn) {
|
||||||
asyncPool.execute(() -> {
|
this.asyncPool.execute(() -> {
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
||||||
.where(data.getId() != -1 ? DSL.field("id").eq(data.getId()) : DSL.field(uuidColumn).eq(data.getUniqueId().toString()))
|
.where(data.getId() != -1 ? DSL.field("id").eq(data.getId()) : DSL.field(uuidColumn).eq(data.getUniqueId().toString()))
|
||||||
.execute();
|
.execute();
|
||||||
@ -372,7 +372,7 @@ public class DataManager {
|
|||||||
try {
|
try {
|
||||||
AtomicReference<Data> data = new AtomicReference<>();
|
AtomicReference<Data> data = new AtomicReference<>();
|
||||||
AtomicBoolean found = new AtomicBoolean(false);
|
AtomicBoolean found = new AtomicBoolean(false);
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
try {
|
try {
|
||||||
Data newData = (Data) clazz.getConstructor().newInstance();
|
Data newData = (Data) clazz.getConstructor().newInstance();
|
||||||
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
||||||
@ -410,7 +410,7 @@ public class DataManager {
|
|||||||
try {
|
try {
|
||||||
AtomicReference<Data> data = new AtomicReference<>();
|
AtomicReference<Data> data = new AtomicReference<>();
|
||||||
AtomicBoolean found = new AtomicBoolean(false);
|
AtomicBoolean found = new AtomicBoolean(false);
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
try {
|
try {
|
||||||
Data newData = (Data) clazz.getConstructor().newInstance();
|
Data newData = (Data) clazz.getConstructor().newInstance();
|
||||||
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
||||||
@ -449,7 +449,7 @@ public class DataManager {
|
|||||||
try {
|
try {
|
||||||
AtomicReference<Data> data = new AtomicReference<>();
|
AtomicReference<Data> data = new AtomicReference<>();
|
||||||
AtomicBoolean found = new AtomicBoolean(false);
|
AtomicBoolean found = new AtomicBoolean(false);
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
try {
|
try {
|
||||||
Data newData = (Data) clazz.getConstructor().newInstance();
|
Data newData = (Data) clazz.getConstructor().newInstance();
|
||||||
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
||||||
@ -482,7 +482,7 @@ public class DataManager {
|
|||||||
public <T extends Data> List<T> loadBatch(Class<?> clazz, String table) {
|
public <T extends Data> List<T> loadBatch(Class<?> clazz, String table) {
|
||||||
try {
|
try {
|
||||||
List<Data> dataList = Collections.synchronizedList(new ArrayList<>());
|
List<Data> dataList = Collections.synchronizedList(new ArrayList<>());
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
try {
|
try {
|
||||||
for (@NotNull Record record : Objects.requireNonNull(context.select()
|
for (@NotNull Record record : Objects.requireNonNull(context.select()
|
||||||
.from(DSL.table(getTablePrefix() + table))
|
.from(DSL.table(getTablePrefix() + table))
|
||||||
@ -509,7 +509,7 @@ public class DataManager {
|
|||||||
public <T extends Data> List<T> loadBatch(Class<?> clazz, String table, Condition... conditions) {
|
public <T extends Data> List<T> loadBatch(Class<?> clazz, String table, Condition... conditions) {
|
||||||
try {
|
try {
|
||||||
List<Data> dataList = Collections.synchronizedList(new ArrayList<>());
|
List<Data> dataList = Collections.synchronizedList(new ArrayList<>());
|
||||||
databaseConnector.connectDSL(context -> {
|
this.databaseConnector.connectDSL(context -> {
|
||||||
try {
|
try {
|
||||||
for (@NotNull Record record : Objects.requireNonNull(context.select()
|
for (@NotNull Record record : Objects.requireNonNull(context.select()
|
||||||
.from(DSL.table(getTablePrefix() + table))
|
.from(DSL.table(getTablePrefix() + table))
|
||||||
|
@ -31,6 +31,7 @@ public abstract class DataMigration {
|
|||||||
/**
|
/**
|
||||||
* @param plugin The plugin to convert data for
|
* @param plugin The plugin to convert data for
|
||||||
* @param toType The new database type
|
* @param toType The new database type
|
||||||
|
*
|
||||||
* @return The new data manager instance
|
* @return The new data manager instance
|
||||||
*/
|
*/
|
||||||
public static DataManager convert(SongodaPlugin plugin, DatabaseType toType) throws Exception {
|
public static DataManager convert(SongodaPlugin plugin, DatabaseType toType) throws Exception {
|
||||||
@ -41,7 +42,7 @@ public abstract class DataMigration {
|
|||||||
}
|
}
|
||||||
DataManager to = new DataManager(plugin, Collections.emptyList(), toType);
|
DataManager to = new DataManager(plugin, Collections.emptyList(), toType);
|
||||||
if (!to.getDatabaseConnector().isInitialized()) {
|
if (!to.getDatabaseConnector().isInitialized()) {
|
||||||
plugin.getLogger().severe("Invalid database configuration for " + toType.name() +"! Please check your "+plugin.getName()+"/database.yml file.");
|
plugin.getLogger().severe("Invalid database configuration for " + toType.name() + "! Please check your " + plugin.getName() + "/database.yml file.");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -56,7 +57,7 @@ public abstract class DataMigration {
|
|||||||
|
|
||||||
// Export schema
|
// Export schema
|
||||||
DatabaseMetaData meta = fromConnection.getMetaData();
|
DatabaseMetaData meta = fromConnection.getMetaData();
|
||||||
ResultSet tables = meta.getTables(null, null, null, new String[]{"TABLE"});
|
ResultSet tables = meta.getTables(null, null, null, new String[] {"TABLE"});
|
||||||
|
|
||||||
while (tables.next()) {
|
while (tables.next()) {
|
||||||
String tableName = tables.getString("TABLE_NAME");
|
String tableName = tables.getString("TABLE_NAME");
|
||||||
@ -74,7 +75,7 @@ public abstract class DataMigration {
|
|||||||
String columnType = metaRs.getColumnTypeName(i);
|
String columnType = metaRs.getColumnTypeName(i);
|
||||||
int columnSize = metaRs.getColumnDisplaySize(i);
|
int columnSize = metaRs.getColumnDisplaySize(i);
|
||||||
//Fix EpicHoppers BIT column type from corrupted db
|
//Fix EpicHoppers BIT column type from corrupted db
|
||||||
if (columnType.equals("BIT") && plugin.getName().toLowerCase().equals("epichoppers")) {
|
if (columnType.equals("BIT") && plugin.getName().equalsIgnoreCase("epichoppers")) {
|
||||||
columnType = "VARCHAR";
|
columnType = "VARCHAR";
|
||||||
columnSize = 20;
|
columnSize = 20;
|
||||||
}
|
}
|
||||||
@ -120,22 +121,22 @@ public abstract class DataMigration {
|
|||||||
|
|
||||||
toConnection.commit();
|
toConnection.commit();
|
||||||
plugin.getLogger().info("Successfully migrated data from " + from.getDatabaseConnector().getType() + " to " + to.getDatabaseConnector().getType());
|
plugin.getLogger().info("Successfully migrated data from " + from.getDatabaseConnector().getType() + " to " + to.getDatabaseConnector().getType());
|
||||||
} catch (Exception e) {
|
} catch (Exception ex) {
|
||||||
if (toConnection != null) {
|
if (toConnection != null) {
|
||||||
try {
|
try {
|
||||||
toConnection.rollback();
|
toConnection.rollback();
|
||||||
} catch (SQLException e1) {
|
} catch (SQLException ex1) {
|
||||||
e1.printStackTrace();
|
ex1.printStackTrace();
|
||||||
plugin.getLogger().severe("Failed to rollback data for the new database");
|
plugin.getLogger().severe("Failed to rollback data for the new database");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
plugin.getLogger().severe("Failed to migrate data from " + from.getDatabaseConnector().getType() + " to " + to.getDatabaseConnector().getType());
|
plugin.getLogger().severe("Failed to migrate data from " + from.getDatabaseConnector().getType() + " to " + to.getDatabaseConnector().getType());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
fromConnector.closeConnection();
|
fromConnector.closeConnection();
|
||||||
//Get rid of the old SQLite database file if it exists and create a backup
|
//Get rid of the old SQLite database file if it exists and create a backup
|
||||||
File databaseFile = new File(plugin.getDataFolder(), plugin.getName().toLowerCase()+".db");
|
File databaseFile = new File(plugin.getDataFolder(), plugin.getName().toLowerCase() + ".db");
|
||||||
if (databaseFile.exists()) {
|
if (databaseFile.exists()) {
|
||||||
|
|
||||||
//rename it to .old
|
//rename it to .old
|
||||||
@ -159,8 +160,8 @@ public abstract class DataMigration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rs.close();
|
rs.close();
|
||||||
} catch (SQLException e) {
|
} catch (SQLException ex) {
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
columns.setLength(columns.length() - 2);
|
columns.setLength(columns.length() - 2);
|
||||||
@ -168,7 +169,7 @@ public abstract class DataMigration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Utility method to convert byte array to hexadecimal string
|
// Utility method to convert a byte array to hexadecimal string
|
||||||
private static String bytesToHex(byte[] bytes) {
|
private static String bytesToHex(byte[] bytes) {
|
||||||
StringBuilder hexString = new StringBuilder();
|
StringBuilder hexString = new StringBuilder();
|
||||||
for (byte b : bytes) {
|
for (byte b : bytes) {
|
||||||
|
@ -29,6 +29,7 @@ public interface DatabaseConnector {
|
|||||||
* Executes a callback with a Connection passed and automatically closes it when finished
|
* Executes a callback with a Connection passed and automatically closes it when finished
|
||||||
*
|
*
|
||||||
* @param callback The callback to execute once the connection is retrieved
|
* @param callback The callback to execute once the connection is retrieved
|
||||||
|
*
|
||||||
* @return The result of the callback
|
* @return The result of the callback
|
||||||
*/
|
*/
|
||||||
OptionalResult connectOptional(ConnectionOptionalCallback callback);
|
OptionalResult connectOptional(ConnectionOptionalCallback callback);
|
||||||
@ -44,6 +45,7 @@ public interface DatabaseConnector {
|
|||||||
* Executes a callback with a DSLContext passed and automatically closes it when finished
|
* Executes a callback with a DSLContext passed and automatically closes it when finished
|
||||||
*
|
*
|
||||||
* @param callback The callback to execute once the connection is retrieved
|
* @param callback The callback to execute once the connection is retrieved
|
||||||
|
*
|
||||||
* @return The result of the callback
|
* @return The result of the callback
|
||||||
*/
|
*/
|
||||||
OptionalResult connectDSLOptional(DSLContextOptionalCallback callback);
|
OptionalResult connectDSLOptional(DSLContextOptionalCallback callback);
|
||||||
@ -82,12 +84,14 @@ public interface DatabaseConnector {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a connection from the database
|
* Gets a connection from the database
|
||||||
|
*
|
||||||
* @return The connection
|
* @return The connection
|
||||||
*/
|
*/
|
||||||
Connection getConnection() throws SQLException;
|
Connection getConnection() throws SQLException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the database type
|
* Gets the database type
|
||||||
|
*
|
||||||
* @return The database type
|
* @return The database type
|
||||||
*/
|
*/
|
||||||
DatabaseType getType();
|
DatabaseType getType();
|
||||||
|
@ -3,7 +3,6 @@ package com.craftaro.core.database;
|
|||||||
import org.jooq.SQLDialect;
|
import org.jooq.SQLDialect;
|
||||||
|
|
||||||
public enum DatabaseType {
|
public enum DatabaseType {
|
||||||
|
|
||||||
MARIADB,
|
MARIADB,
|
||||||
MYSQL,
|
MYSQL,
|
||||||
H2,
|
H2,
|
||||||
|
@ -12,7 +12,6 @@ import java.sql.Connection;
|
|||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
|
||||||
public class MariaDBConnector implements DatabaseConnector {
|
public class MariaDBConnector implements DatabaseConnector {
|
||||||
|
|
||||||
private final SongodaPlugin plugin;
|
private final SongodaPlugin plugin;
|
||||||
private HikariDataSource hikari;
|
private HikariDataSource hikari;
|
||||||
private boolean initializedSuccessfully;
|
private boolean initializedSuccessfully;
|
||||||
@ -78,7 +77,7 @@ public class MariaDBConnector implements DatabaseConnector {
|
|||||||
try (Connection connection = getConnection()) {
|
try (Connection connection = getConnection()) {
|
||||||
return callback.accept(connection);
|
return callback.accept(connection);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a MariaDB query: " + ex.getMessage());
|
SongodaCore.getLogger().severe("An error occurred executing a MariaDB query: " + ex.getMessage());
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
return OptionalResult.empty();
|
return OptionalResult.empty();
|
||||||
@ -99,7 +98,7 @@ public class MariaDBConnector implements DatabaseConnector {
|
|||||||
try (Connection connection = getConnection()) {
|
try (Connection connection = getConnection()) {
|
||||||
return callback.accept(DSL.using(connection, SQLDialect.MARIADB));
|
return callback.accept(DSL.using(connection, SQLDialect.MARIADB));
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a MariaDB query: " + ex.getMessage());
|
SongodaCore.getLogger().severe("An error occurred executing a MariaDB query: " + ex.getMessage());
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
return OptionalResult.empty();
|
return OptionalResult.empty();
|
||||||
|
@ -73,7 +73,7 @@ public class MySQLConnector implements DatabaseConnector {
|
|||||||
try (Connection connection = getConnection()) {
|
try (Connection connection = getConnection()) {
|
||||||
return callback.accept(connection);
|
return callback.accept(connection);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
SongodaCore.getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
return OptionalResult.empty();
|
return OptionalResult.empty();
|
||||||
@ -81,7 +81,7 @@ public class MySQLConnector implements DatabaseConnector {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void connectDSL(DSLContextCallback callback) {
|
public void connectDSL(DSLContextCallback callback) {
|
||||||
try (Connection connection = getConnection()){
|
try (Connection connection = getConnection()) {
|
||||||
callback.accept(DSL.using(connection, SQLDialect.MYSQL));
|
callback.accept(DSL.using(connection, SQLDialect.MYSQL));
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
this.plugin.getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
this.plugin.getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
||||||
@ -94,7 +94,7 @@ public class MySQLConnector implements DatabaseConnector {
|
|||||||
try (Connection connection = getConnection()) {
|
try (Connection connection = getConnection()) {
|
||||||
return callback.accept(DSL.using(connection, SQLDialect.MYSQL));
|
return callback.accept(DSL.using(connection, SQLDialect.MYSQL));
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
SongodaCore.getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
return OptionalResult.empty();
|
return OptionalResult.empty();
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package com.craftaro.core.database;
|
package com.craftaro.core.database;
|
||||||
|
|
||||||
public class OptionalResult {
|
public class OptionalResult {
|
||||||
|
|
||||||
private final Object value;
|
private final Object value;
|
||||||
private final boolean present;
|
private final boolean present;
|
||||||
|
|
||||||
@ -11,15 +10,15 @@ public class OptionalResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public <T> T get(Class<T> clazz) {
|
public <T> T get(Class<T> clazz) {
|
||||||
return clazz.cast(value);
|
return clazz.cast(this.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isPresent() {
|
public boolean isPresent() {
|
||||||
return present;
|
return this.present;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <V> V getOrDefault(V defaultValue) {
|
public <V> V getOrDefault(V defaultValue) {
|
||||||
return present ? (V) value : defaultValue;
|
return this.present ? (V) this.value : defaultValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static OptionalResult empty() {
|
public static OptionalResult empty() {
|
||||||
|
@ -18,7 +18,7 @@ public class SQLiteConnector implements DatabaseConnector {
|
|||||||
|
|
||||||
SQLiteConnector() {
|
SQLiteConnector() {
|
||||||
this.plugin = null;
|
this.plugin = null;
|
||||||
this.connectionString = "jdbc:sqlite:" + "."+File.separator+"db_test"+File.separator+"CraftaroCoreTestSQLite.db";
|
this.connectionString = "jdbc:sqlite:" + "." + File.separator + "db_test" + File.separator + "CraftaroCoreTestSQLite.db";
|
||||||
}
|
}
|
||||||
|
|
||||||
public SQLiteConnector(Plugin plugin) {
|
public SQLiteConnector(Plugin plugin) {
|
||||||
@ -63,7 +63,7 @@ public class SQLiteConnector implements DatabaseConnector {
|
|||||||
try (Connection connection = getConnection()) {
|
try (Connection connection = getConnection()) {
|
||||||
return callback.accept(connection);
|
return callback.accept(connection);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
SongodaCore.getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
return OptionalResult.empty();
|
return OptionalResult.empty();
|
||||||
@ -71,7 +71,7 @@ public class SQLiteConnector implements DatabaseConnector {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void connectDSL(DSLContextCallback callback) {
|
public void connectDSL(DSLContextCallback callback) {
|
||||||
try (Connection connection = getConnection()){
|
try (Connection connection = getConnection()) {
|
||||||
callback.accept(DSL.using(connection, SQLDialect.SQLITE));
|
callback.accept(DSL.using(connection, SQLDialect.SQLITE));
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
this.plugin.getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
this.plugin.getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
||||||
@ -84,7 +84,7 @@ public class SQLiteConnector implements DatabaseConnector {
|
|||||||
try (Connection connection = getConnection()) {
|
try (Connection connection = getConnection()) {
|
||||||
return callback.accept(DSL.using(connection, SQLDialect.SQLITE));
|
return callback.accept(DSL.using(connection, SQLDialect.SQLITE));
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
SongodaCore.getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
return OptionalResult.empty();
|
return OptionalResult.empty();
|
||||||
|
@ -7,13 +7,12 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public class SerializedLocation {
|
public class SerializedLocation {
|
||||||
|
private final String world;
|
||||||
private String world;
|
private final double x;
|
||||||
private double x;
|
private final double y;
|
||||||
private double y;
|
private final double z;
|
||||||
private double z;
|
private final float pitch;
|
||||||
private float pitch = 0;
|
private final float yaw;
|
||||||
private float yaw = 0;
|
|
||||||
|
|
||||||
public SerializedLocation(Location location) {
|
public SerializedLocation(Location location) {
|
||||||
this.world = location.getWorld().getName();
|
this.world = location.getWorld().getName();
|
||||||
@ -23,6 +22,9 @@ public class SerializedLocation {
|
|||||||
if (location.getPitch() != 0 && location.getYaw() != 0) {
|
if (location.getPitch() != 0 && location.getYaw() != 0) {
|
||||||
this.pitch = location.getPitch();
|
this.pitch = location.getPitch();
|
||||||
this.yaw = location.getYaw();
|
this.yaw = location.getYaw();
|
||||||
|
} else {
|
||||||
|
this.pitch = 0;
|
||||||
|
this.yaw = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -31,8 +33,8 @@ public class SerializedLocation {
|
|||||||
(double) map.get("x"),
|
(double) map.get("x"),
|
||||||
(double) map.get("y"),
|
(double) map.get("y"),
|
||||||
(double) map.get("z"),
|
(double) map.get("z"),
|
||||||
Double.valueOf((double)map.getOrDefault("yaw", 0.0)).floatValue(),
|
Double.valueOf((double) map.getOrDefault("yaw", 0.0)).floatValue(),
|
||||||
Double.valueOf((double)map.getOrDefault("pitch", 0.0)).floatValue());
|
Double.valueOf((double) map.getOrDefault("pitch", 0.0)).floatValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Map<String, Object> of(Location location) {
|
public static Map<String, Object> of(Location location) {
|
||||||
@ -49,18 +51,18 @@ public class SerializedLocation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Location asLocation() {
|
public Location asLocation() {
|
||||||
return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
|
return new Location(Bukkit.getWorld(this.world), this.x, this.y, this.z, this.yaw, this.pitch);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> asMap() {
|
public Map<String, Object> asMap() {
|
||||||
Map<String, Object> map = new HashMap<>();
|
Map<String, Object> map = new HashMap<>();
|
||||||
map.put("world", world);
|
map.put("world", this.world);
|
||||||
map.put("x", x);
|
map.put("x", this.x);
|
||||||
map.put("y", y);
|
map.put("y", this.y);
|
||||||
map.put("z", z);
|
map.put("z", this.z);
|
||||||
if (pitch != 0 && yaw != 0) {
|
if (this.pitch != 0 && this.yaw != 0) {
|
||||||
map.put("pitch", pitch);
|
map.put("pitch", this.pitch);
|
||||||
map.put("yaw", yaw);
|
map.put("yaw", this.yaw);
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
@ -48,7 +48,7 @@ public class Dependency {
|
|||||||
this.artifactId = artifactId;
|
this.artifactId = artifactId;
|
||||||
this.version = version;
|
this.version = version;
|
||||||
if (baseRelocate) {
|
if (baseRelocate) {
|
||||||
//Add base relocate
|
// Add base relocate
|
||||||
this.relocations.add(new Relocation(groupId, "com.craftaro.third_party." + groupId));
|
this.relocations.add(new Relocation(groupId, "com.craftaro.third_party." + groupId));
|
||||||
}
|
}
|
||||||
if (extraRelocations.length > 0) {
|
if (extraRelocations.length > 0) {
|
||||||
|
@ -28,7 +28,7 @@ public class DependencyLoader {
|
|||||||
private final ClassLoaderAccess parentClassLoaderAccess;
|
private final ClassLoaderAccess parentClassLoaderAccess;
|
||||||
|
|
||||||
public DependencyLoader(Plugin plugin) {
|
public DependencyLoader(Plugin plugin) {
|
||||||
//Bind loaded dependencies to the plugin's parent class loader so classes could be accessed across plugins
|
// Bind loaded dependencies to the plugin's parent class loader so classes could be accessed across plugins
|
||||||
ClassLoader parentClassLoader = plugin.getClass().getClassLoader().getParent();
|
ClassLoader parentClassLoader = plugin.getClass().getClassLoader().getParent();
|
||||||
if (parentClassLoader instanceof URLClassLoader) {
|
if (parentClassLoader instanceof URLClassLoader) {
|
||||||
this.libraryLoader = new LibraryLoader(
|
this.libraryLoader = new LibraryLoader(
|
||||||
@ -38,7 +38,7 @@ public class DependencyLoader {
|
|||||||
);
|
);
|
||||||
this.parentClassLoaderAccess = new ClassLoaderAccess((URLClassLoader) parentClassLoader);
|
this.parentClassLoaderAccess = new ClassLoaderAccess((URLClassLoader) parentClassLoader);
|
||||||
} else {
|
} else {
|
||||||
//We have AppClassLoader here
|
// We have AppClassLoader here
|
||||||
this.libraryLoader = new LibraryLoader(
|
this.libraryLoader = new LibraryLoader(
|
||||||
parentClassLoader,
|
parentClassLoader,
|
||||||
new File(plugin.getDataFolder().getParentFile(), CraftaroCoreConstants.getProjectName() + "/dependencies/v" + DEPENDENCY_VERSION),
|
new File(plugin.getDataFolder().getParentFile(), CraftaroCoreConstants.getProjectName() + "/dependencies/v" + DEPENDENCY_VERSION),
|
||||||
@ -108,11 +108,11 @@ public class DependencyLoader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
//Do not check path here, it uses the original non relocated paths. Use isJarLoaded instead
|
// Do not check the path here, it uses the original non-relocated paths. Use isJarLoaded instead
|
||||||
this.libraryLoader.load(new LibraryLoader.Dependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getRepositoryUrl()), false);
|
this.libraryLoader.load(new LibraryLoader.Dependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getRepositoryUrl()), false);
|
||||||
} catch (Exception e) {
|
} catch (Exception ex) {
|
||||||
// Something went wrong
|
// Something went wrong
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
SongodaCore.getLogger().info("----------------------------");
|
SongodaCore.getLogger().info("----------------------------");
|
||||||
}
|
}
|
||||||
|
@ -44,7 +44,7 @@ public class AnvilGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected void open() {
|
protected void open() {
|
||||||
anvil.open();
|
this.anvil.open();
|
||||||
}
|
}
|
||||||
|
|
||||||
public AnvilGui setInput(ItemStack item) {
|
public AnvilGui setInput(ItemStack item) {
|
||||||
@ -60,26 +60,26 @@ public class AnvilGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public AnvilGui setOutputPrompt(String str) {
|
public AnvilGui setOutputPrompt(String str) {
|
||||||
endPrompt = Arrays.asList(str);
|
this.endPrompt = Arrays.asList(str);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public AnvilGui setOutputPrompt(String... str) {
|
public AnvilGui setOutputPrompt(String... str) {
|
||||||
endPrompt = Arrays.asList(str);
|
this.endPrompt = Arrays.asList(str);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public AnvilGui setOutputPrompt(List<String> str) {
|
public AnvilGui setOutputPrompt(List<String> str) {
|
||||||
endPrompt = str;
|
this.endPrompt = str;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
void updateOutputPrompt() {
|
void updateOutputPrompt() {
|
||||||
if (endPrompt != null) {
|
if (this.endPrompt != null) {
|
||||||
ItemStack in = cellItems.get(0);
|
ItemStack in = this.cellItems.get(0);
|
||||||
|
|
||||||
if (in != null) {
|
if (in != null) {
|
||||||
setItem(2, GuiUtils.createButtonItem(in, endPrompt));
|
setItem(2, GuiUtils.createButtonItem(in, this.endPrompt));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -89,7 +89,7 @@ public class AnvilGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getInputText() {
|
public String getInputText() {
|
||||||
return anvil != null ? anvil.getRenameText() : null;
|
return this.anvil != null ? this.anvil.getRenameText() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@ -99,42 +99,40 @@ public class AnvilGui extends Gui {
|
|||||||
|
|
||||||
createInventory();
|
createInventory();
|
||||||
ItemStack item;
|
ItemStack item;
|
||||||
if (cellItems.containsKey(0)) {
|
if (this.cellItems.containsKey(0)) {
|
||||||
item = cellItems.get(0);
|
item = this.cellItems.get(0);
|
||||||
|
|
||||||
inventory.setItem(0, item);
|
this.inventory.setItem(0, item);
|
||||||
} else if (cellItems.containsKey(1)) {
|
} else if (this.cellItems.containsKey(1)) {
|
||||||
item = cellItems.get(1);
|
item = this.cellItems.get(1);
|
||||||
|
|
||||||
inventory.setItem(1, item);
|
this.inventory.setItem(1, item);
|
||||||
} else if (!acceptsItems) {
|
} else if (!this.acceptsItems) {
|
||||||
item = GuiUtils.createButtonItem(XMaterial.PAPER, " ", " ");
|
item = GuiUtils.createButtonItem(XMaterial.PAPER, " ", " ");
|
||||||
|
|
||||||
cellItems.put(0, item);
|
this.cellItems.put(0, item);
|
||||||
inventory.setItem(0, item);
|
this.inventory.setItem(0, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cellItems.containsKey(2)) {
|
if (this.cellItems.containsKey(2)) {
|
||||||
item = cellItems.get(2);
|
item = this.cellItems.get(2);
|
||||||
|
|
||||||
inventory.setItem(2, item);
|
this.inventory.setItem(2, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
return inventory;
|
return this.inventory;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void createInventory() {
|
protected void createInventory() {
|
||||||
AnvilCore nms = Nms.getImplementations().getAnvil();
|
AnvilCore nms = Nms.getImplementations().getAnvil();
|
||||||
|
|
||||||
if (nms != null) {
|
this.anvil = nms.createAnvil(this.player, new GuiHolder(this.guiManager, this));
|
||||||
anvil = nms.createAnvil(player, new GuiHolder(guiManager, this));
|
this.anvil.setCustomTitle(this.title);
|
||||||
anvil.setCustomTitle(title);
|
this.anvil.setLevelCost(0);
|
||||||
anvil.setLevelCost(0);
|
|
||||||
|
|
||||||
inventory = anvil.getInventory();
|
this.inventory = this.anvil.getInventory();
|
||||||
|
|
||||||
anvil.setOnChange(this::updateOutputPrompt);
|
this.anvil.setOnChange(this::updateOutputPrompt);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -29,7 +29,7 @@ public class CustomizableGui extends Gui {
|
|||||||
private static boolean showGuiKeys = false;
|
private static boolean showGuiKeys = false;
|
||||||
private int activationCount = 0;
|
private int activationCount = 0;
|
||||||
|
|
||||||
private static final Map<String, CustomContent> loadedGuis = new HashMap<>();
|
private static final Map<String, CustomContent> LOADED_GUIS = new HashMap<>();
|
||||||
private final CustomContent customContent;
|
private final CustomContent customContent;
|
||||||
|
|
||||||
public CustomizableGui(Plugin plugin, String guiKey) {
|
public CustomizableGui(Plugin plugin, String guiKey) {
|
||||||
@ -39,9 +39,8 @@ public class CustomizableGui extends Gui {
|
|||||||
public CustomizableGui(@NotNull Plugin plugin, @NotNull String guiKey, @Nullable Gui parent) {
|
public CustomizableGui(@NotNull Plugin plugin, @NotNull String guiKey, @Nullable Gui parent) {
|
||||||
super(parent);
|
super(parent);
|
||||||
|
|
||||||
if (!loadedGuis.containsKey(guiKey) || showGuiKeys) {
|
if (!LOADED_GUIS.containsKey(guiKey) || showGuiKeys) {
|
||||||
File localeFolder = new File(plugin.getDataFolder(), "gui/");
|
File localeFolder = new File(plugin.getDataFolder(), "gui/");
|
||||||
|
|
||||||
if (!localeFolder.exists()) {
|
if (!localeFolder.exists()) {
|
||||||
localeFolder.mkdir();
|
localeFolder.mkdir();
|
||||||
}
|
}
|
||||||
@ -74,8 +73,8 @@ public class CustomizableGui extends Gui {
|
|||||||
config.saveChanges();
|
config.saveChanges();
|
||||||
}
|
}
|
||||||
|
|
||||||
CustomContent customContent = loadedGuis.computeIfAbsent(guiKey, g -> new CustomContent(guiKey));
|
CustomContent customContent = LOADED_GUIS.computeIfAbsent(guiKey, g -> new CustomContent(guiKey));
|
||||||
loadedGuis.put(guiKey, customContent);
|
LOADED_GUIS.put(guiKey, customContent);
|
||||||
this.customContent = customContent;
|
this.customContent = customContent;
|
||||||
|
|
||||||
int rows = config.getInt("overrides.__ROWS__", -1);
|
int rows = config.getInt("overrides.__ROWS__", -1);
|
||||||
@ -113,7 +112,7 @@ public class CustomizableGui extends Gui {
|
|||||||
customContent.disableButton(disabled);
|
customContent.disableButton(disabled);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.customContent = loadedGuis.get(guiKey);
|
this.customContent = LOADED_GUIS.get(guiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
setPrivateDefaultAction(event -> {
|
setPrivateDefaultAction(event -> {
|
||||||
|
@ -15,6 +15,7 @@ import org.bukkit.event.inventory.ClickType;
|
|||||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||||
import org.bukkit.inventory.Inventory;
|
import org.bukkit.inventory.Inventory;
|
||||||
import org.bukkit.inventory.ItemStack;
|
import org.bukkit.inventory.ItemStack;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -288,7 +289,7 @@ public class DoubleGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean onClickPlayerInventory(GuiManager manager, Player player, Inventory openInv, InventoryClickEvent event) {
|
protected boolean onClickPlayerInventory(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory openInv, InventoryClickEvent event) {
|
||||||
final int cell = event.getSlot(), offsetCell = clickOffset(cell);
|
final int cell = event.getSlot(), offsetCell = clickOffset(cell);
|
||||||
Map<ClickType, Clickable> conditionals = this.conditionalButtons.get(offsetCell);
|
Map<ClickType, Clickable> conditionals = this.conditionalButtons.get(offsetCell);
|
||||||
Clickable button;
|
Clickable button;
|
||||||
@ -307,7 +308,7 @@ public class DoubleGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean onClickOutside(GuiManager manager, Player player, InventoryClickEvent event) {
|
protected boolean onClickOutside(@NotNull GuiManager manager, @NotNull Player player, @NotNull InventoryClickEvent event) {
|
||||||
if (this.dropper != null) {
|
if (this.dropper != null) {
|
||||||
return this.dropper.onDrop(new GuiDropItemEvent(manager, this, player, event));
|
return this.dropper.onDrop(new GuiDropItemEvent(manager, this, player, event));
|
||||||
}
|
}
|
||||||
@ -317,7 +318,7 @@ public class DoubleGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(GuiManager manager, Player player) {
|
public void onOpen(@NotNull GuiManager manager, @NotNull Player player) {
|
||||||
// replace the player's inventory
|
// replace the player's inventory
|
||||||
if (this.startStashed) {
|
if (this.startStashed) {
|
||||||
stashItems(player);
|
stashItems(player);
|
||||||
@ -328,7 +329,7 @@ public class DoubleGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onClose(GuiManager manager, Player player) {
|
public void onClose(@NotNull GuiManager manager, @NotNull Player player) {
|
||||||
// restore the player's inventory
|
// restore the player's inventory
|
||||||
restoreStash(player);
|
restoreStash(player);
|
||||||
|
|
||||||
@ -361,32 +362,32 @@ public class DoubleGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setUnlocked(int cell) {
|
public @NotNull DoubleGui setUnlocked(int cell) {
|
||||||
return (DoubleGui) super.setUnlocked(cell);
|
return (DoubleGui) super.setUnlocked(cell);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setUnlocked(int cell, boolean open) {
|
public @NotNull DoubleGui setUnlocked(int cell, boolean open) {
|
||||||
return (DoubleGui) super.setUnlocked(cell, open);
|
return (DoubleGui) super.setUnlocked(cell, open);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setUnlocked(int row, int col) {
|
public @NotNull DoubleGui setUnlocked(int row, int col) {
|
||||||
return (DoubleGui) super.setUnlocked(row, col);
|
return (DoubleGui) super.setUnlocked(row, col);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setUnlocked(int row, int col, boolean open) {
|
public @NotNull DoubleGui setUnlocked(int row, int col, boolean open) {
|
||||||
return (DoubleGui) super.setUnlocked(row, col, open);
|
return (DoubleGui) super.setUnlocked(row, col, open);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setUnlockedRange(int cellFirst, int cellLast) {
|
public @NotNull DoubleGui setUnlockedRange(int cellFirst, int cellLast) {
|
||||||
return (DoubleGui) super.setUnlockedRange(cellFirst, cellLast);
|
return (DoubleGui) super.setUnlockedRange(cellFirst, cellLast);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) {
|
public @NotNull DoubleGui setUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) {
|
||||||
return (DoubleGui) super.setUnlockedRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast);
|
return (DoubleGui) super.setUnlockedRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -401,192 +402,192 @@ public class DoubleGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setTitle(String title) {
|
public @NotNull DoubleGui setTitle(String title) {
|
||||||
return (DoubleGui) super.setTitle(title);
|
return (DoubleGui) super.setTitle(title);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setRows(int rows) {
|
public @NotNull DoubleGui setRows(int rows) {
|
||||||
return (DoubleGui) super.setRows(rows);
|
return (DoubleGui) super.setRows(rows);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setDefaultItem(ItemStack item) {
|
public @NotNull DoubleGui setDefaultItem(ItemStack item) {
|
||||||
return (DoubleGui) super.setDefaultItem(item);
|
return (DoubleGui) super.setDefaultItem(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setItem(int cell, ItemStack item) {
|
public @NotNull DoubleGui setItem(int cell, ItemStack item) {
|
||||||
return (DoubleGui) super.setItem(cell, item);
|
return (DoubleGui) super.setItem(cell, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setItem(int row, int col, ItemStack item) {
|
public @NotNull DoubleGui setItem(int row, int col, ItemStack item) {
|
||||||
return (DoubleGui) super.setItem(row, col, item);
|
return (DoubleGui) super.setItem(row, col, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui highlightItem(int cell) {
|
public @NotNull DoubleGui highlightItem(int cell) {
|
||||||
return (DoubleGui) super.highlightItem(cell);
|
return (DoubleGui) super.highlightItem(cell);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui highlightItem(int row, int col) {
|
public @NotNull DoubleGui highlightItem(int row, int col) {
|
||||||
return (DoubleGui) super.highlightItem(row, col);
|
return (DoubleGui) super.highlightItem(row, col);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int cell, String name, String... lore) {
|
public @NotNull DoubleGui updateItem(int cell, String name, String... lore) {
|
||||||
return (DoubleGui) super.updateItem(cell, name, lore);
|
return (DoubleGui) super.updateItem(cell, name, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int row, int col, String name, List<String> lore) {
|
public @NotNull DoubleGui updateItem(int row, int col, String name, List<String> lore) {
|
||||||
return (DoubleGui) super.updateItem(col + row * 9, name, lore);
|
return (DoubleGui) super.updateItem(col + row * 9, name, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int cell, String name, List<String> lore) {
|
public @NotNull DoubleGui updateItem(int cell, @NotNull String name, List<String> lore) {
|
||||||
return (DoubleGui) super.updateItem(cell, name, lore);
|
return (DoubleGui) super.updateItem(cell, name, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int row, int col, ItemStack itemTo, String title, String... lore) {
|
public @NotNull DoubleGui updateItem(int row, int col, @NotNull ItemStack itemTo, String title, String... lore) {
|
||||||
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int cell, ItemStack itemTo, String title, String... lore) {
|
public @NotNull DoubleGui updateItem(int cell, @NotNull ItemStack itemTo, String title, String... lore) {
|
||||||
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int row, int col, XMaterial itemTo, String title, String... lore) {
|
public @NotNull DoubleGui updateItem(int row, int col, @NotNull XMaterial itemTo, String title, String... lore) {
|
||||||
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int cell, XMaterial itemTo, String title, String... lore) {
|
public @NotNull DoubleGui updateItem(int cell, @NotNull XMaterial itemTo, String title, String... lore) {
|
||||||
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int row, int col, ItemStack itemTo, String title, List<String> lore) {
|
public @NotNull DoubleGui updateItem(int row, int col, @NotNull ItemStack itemTo, String title, List<String> lore) {
|
||||||
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int cell, ItemStack itemTo, String title, List<String> lore) {
|
public @NotNull DoubleGui updateItem(int cell, @NotNull ItemStack itemTo, String title, List<String> lore) {
|
||||||
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int row, int col, XMaterial itemTo, String title, List<String> lore) {
|
public @NotNull DoubleGui updateItem(int row, int col, @NotNull XMaterial itemTo, String title, List<String> lore) {
|
||||||
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui updateItem(int cell, XMaterial itemTo, String title, List<String> lore) {
|
public @NotNull DoubleGui updateItem(int cell, @NotNull XMaterial itemTo, String title, List<String> lore) {
|
||||||
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setAction(int cell, Clickable action) {
|
public @NotNull DoubleGui setAction(int cell, Clickable action) {
|
||||||
return (DoubleGui) super.setAction(cell, action);
|
return (DoubleGui) super.setAction(cell, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setAction(int row, int col, Clickable action) {
|
public @NotNull DoubleGui setAction(int row, int col, Clickable action) {
|
||||||
return (DoubleGui) super.setAction(row, col, action);
|
return (DoubleGui) super.setAction(row, col, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setAction(int cell, ClickType type, Clickable action) {
|
public @NotNull DoubleGui setAction(int cell, ClickType type, Clickable action) {
|
||||||
return (DoubleGui) super.setAction(cell, type, action);
|
return (DoubleGui) super.setAction(cell, type, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setAction(int row, int col, ClickType type, Clickable action) {
|
public @NotNull DoubleGui setAction(int row, int col, ClickType type, Clickable action) {
|
||||||
return (DoubleGui) super.setAction(row, col, type, action);
|
return (DoubleGui) super.setAction(row, col, type, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setActionForRange(int cellFirst, int cellLast, Clickable action) {
|
public @NotNull DoubleGui setActionForRange(int cellFirst, int cellLast, Clickable action) {
|
||||||
return (DoubleGui) super.setActionForRange(cellFirst, cellLast, action);
|
return (DoubleGui) super.setActionForRange(cellFirst, cellLast, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, Clickable action) {
|
public @NotNull DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, Clickable action) {
|
||||||
return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, action);
|
return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setActionForRange(int cellFirst, int cellLast, ClickType type, Clickable action) {
|
public @NotNull DoubleGui setActionForRange(int cellFirst, int cellLast, ClickType type, Clickable action) {
|
||||||
return (DoubleGui) super.setActionForRange(cellFirst, cellLast, type, action);
|
return (DoubleGui) super.setActionForRange(cellFirst, cellLast, type, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, ClickType type, Clickable action) {
|
public @NotNull DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, ClickType type, Clickable action) {
|
||||||
return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, type, action);
|
return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, type, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui clearActions(int cell) {
|
public @NotNull DoubleGui clearActions(int cell) {
|
||||||
return (DoubleGui) super.clearActions(cell);
|
return (DoubleGui) super.clearActions(cell);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui clearActions(int row, int col) {
|
public @NotNull DoubleGui clearActions(int row, int col) {
|
||||||
return (DoubleGui) super.clearActions(row, col);
|
return (DoubleGui) super.clearActions(row, col);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setButton(int cell, ItemStack item, Clickable action) {
|
public @NotNull DoubleGui setButton(int cell, ItemStack item, Clickable action) {
|
||||||
return (DoubleGui) super.setButton(cell, item, action);
|
return (DoubleGui) super.setButton(cell, item, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setButton(int row, int col, ItemStack item, Clickable action) {
|
public @NotNull DoubleGui setButton(int row, int col, ItemStack item, Clickable action) {
|
||||||
return (DoubleGui) super.setButton(row, col, item, action);
|
return (DoubleGui) super.setButton(row, col, item, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setButton(int cell, ItemStack item, ClickType type, Clickable action) {
|
public @NotNull DoubleGui setButton(int cell, ItemStack item, ClickType type, Clickable action) {
|
||||||
return (DoubleGui) super.setButton(cell, item, type, action);
|
return (DoubleGui) super.setButton(cell, item, type, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setButton(int row, int col, ItemStack item, ClickType type, Clickable action) {
|
public @NotNull DoubleGui setButton(int row, int col, ItemStack item, ClickType type, Clickable action) {
|
||||||
return (DoubleGui) super.setButton(row, col, item, type, action);
|
return (DoubleGui) super.setButton(row, col, item, type, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setOnOpen(Openable action) {
|
public @NotNull DoubleGui setOnOpen(Openable action) {
|
||||||
return (DoubleGui) super.setOnOpen(action);
|
return (DoubleGui) super.setOnOpen(action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setOnClose(Closable action) {
|
public @NotNull DoubleGui setOnClose(Closable action) {
|
||||||
return (DoubleGui) super.setOnClose(action);
|
return (DoubleGui) super.setOnClose(action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setOnDrop(Droppable action) {
|
public @NotNull DoubleGui setOnDrop(Droppable action) {
|
||||||
return (DoubleGui) super.setOnDrop(action);
|
return (DoubleGui) super.setOnDrop(action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setOnPage(Pagable action) {
|
public @NotNull DoubleGui setOnPage(Pagable action) {
|
||||||
return (DoubleGui) super.setOnPage(action);
|
return (DoubleGui) super.setOnPage(action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setNextPage(int row, int col, ItemStack item) {
|
public @NotNull DoubleGui setNextPage(int row, int col, @NotNull ItemStack item) {
|
||||||
return (DoubleGui) super.setNextPage(row, col, item);
|
return (DoubleGui) super.setNextPage(row, col, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DoubleGui setPrevPage(int row, int col, ItemStack item) {
|
public @NotNull DoubleGui setPrevPage(int row, int col, @NotNull ItemStack item) {
|
||||||
return (DoubleGui) super.setPrevPage(row, col, item);
|
return (DoubleGui) super.setPrevPage(row, col, item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -896,7 +896,7 @@ public class Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8) && title.length() > 32) {
|
if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8) && title.length() > 32) {
|
||||||
return title.charAt(30) == '\u00A7' ? title.substring(0, 30) : title.substring(0, 31);
|
return title.charAt(30) == '§' ? title.substring(0, 30) : title.substring(0, 31);
|
||||||
}
|
}
|
||||||
|
|
||||||
return title;
|
return title;
|
||||||
@ -932,7 +932,7 @@ public class Gui {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected boolean onClickPlayerInventory(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory openInv, @NotNull InventoryClickEvent event) {
|
protected boolean onClickPlayerInventory(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory openInv, InventoryClickEvent event) {
|
||||||
// no events for this yet
|
// no events for this yet
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@ -8,9 +8,9 @@ public enum GuiType {
|
|||||||
HOPPER(InventoryType.HOPPER, 5, 1),
|
HOPPER(InventoryType.HOPPER, 5, 1),
|
||||||
FURNACE(InventoryType.FURNACE, 3, 2);
|
FURNACE(InventoryType.FURNACE, 3, 2);
|
||||||
|
|
||||||
protected final InventoryType type;
|
final InventoryType type;
|
||||||
protected final int rows;
|
final int rows;
|
||||||
protected final int columns;
|
final int columns;
|
||||||
|
|
||||||
GuiType(InventoryType type, int rows, int columns) {
|
GuiType(InventoryType type, int rows, int columns) {
|
||||||
this.type = type;
|
this.type = type;
|
||||||
|
@ -56,8 +56,8 @@ public class GuiUtils {
|
|||||||
// fix newlines
|
// fix newlines
|
||||||
ArrayList<String> newLore = new ArrayList<>();
|
ArrayList<String> newLore = new ArrayList<>();
|
||||||
|
|
||||||
for (String l : lines) {
|
for (String line : lines) {
|
||||||
for (String l2 : l.split("\n")) {
|
for (String l2 : line.split("\n")) {
|
||||||
if (l2.length() < 54) {
|
if (l2.length() < 54) {
|
||||||
newLore.add(l2);
|
newLore.add(l2);
|
||||||
continue;
|
continue;
|
||||||
@ -66,7 +66,7 @@ public class GuiUtils {
|
|||||||
// try to shorten the string
|
// try to shorten the string
|
||||||
String shorterString = l2;
|
String shorterString = l2;
|
||||||
ChatColor lastColor = null; // todo? probably should also track formatting codes..
|
ChatColor lastColor = null; // todo? probably should also track formatting codes..
|
||||||
int line = 0;
|
int lineNumber = 0;
|
||||||
while (shorterString.length() > 50) {
|
while (shorterString.length() > 50) {
|
||||||
int breakingSpace = -1;
|
int breakingSpace = -1;
|
||||||
|
|
||||||
@ -80,18 +80,18 @@ public class GuiUtils {
|
|||||||
|
|
||||||
if (breakingSpace == -1) {
|
if (breakingSpace == -1) {
|
||||||
breakingSpace = Math.max(50, shorterString.length());
|
breakingSpace = Math.max(50, shorterString.length());
|
||||||
newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace) + "-");
|
newLore.add((lineNumber != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace) + "-");
|
||||||
shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1);
|
shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1);
|
||||||
} else {
|
} else {
|
||||||
newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace));
|
newLore.add((lineNumber != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace));
|
||||||
shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1);
|
shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
++line;
|
++lineNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!shorterString.isEmpty()) {
|
if (!shorterString.isEmpty()) {
|
||||||
newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + " " + shorterString);
|
newLore.add((lineNumber != 0 && lastColor != null ? lastColor.toString() : "") + " " + shorterString);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,8 +24,8 @@ import java.util.UUID;
|
|||||||
* Calling this class on anything below 1.12 will cause ClassLoader Exceptions!
|
* Calling this class on anything below 1.12 will cause ClassLoader Exceptions!
|
||||||
*/
|
*/
|
||||||
class PopupMessage {
|
class PopupMessage {
|
||||||
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||||
private static final HashSet<UUID> registeredMessages = new HashSet<>();
|
private static final HashSet<UUID> REGISTERED_MESSAGES = new HashSet<>();
|
||||||
|
|
||||||
final UUID id = UUID.randomUUID();
|
final UUID id = UUID.randomUUID();
|
||||||
private final NamespacedKey key;
|
private final NamespacedKey key;
|
||||||
@ -63,7 +63,7 @@ class PopupMessage {
|
|||||||
advDisplay.add("icon", displayIcon);
|
advDisplay.add("icon", displayIcon);
|
||||||
}
|
}
|
||||||
|
|
||||||
advDisplay.add("title", gson.fromJson(ComponentSerializer.toString(this.title), JsonElement.class));
|
advDisplay.add("title", GSON.fromJson(ComponentSerializer.toString(this.title), JsonElement.class));
|
||||||
advDisplay.addProperty("background", this.background.key);
|
advDisplay.addProperty("background", this.background.key);
|
||||||
advDisplay.addProperty("description", "");
|
advDisplay.addProperty("description", "");
|
||||||
advDisplay.addProperty("frame", this.frame.id);
|
advDisplay.addProperty("frame", this.frame.id);
|
||||||
@ -84,7 +84,7 @@ class PopupMessage {
|
|||||||
}*/
|
}*/
|
||||||
advCriteria.add("mentioned", advTrigger);
|
advCriteria.add("mentioned", advTrigger);
|
||||||
|
|
||||||
return gson.toJson(json);
|
return GSON.toJson(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void grant(final Player pl) {
|
protected void grant(final Player pl) {
|
||||||
@ -110,8 +110,8 @@ class PopupMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected void add() {
|
protected void add() {
|
||||||
if (!registeredMessages.contains(this.id)) {
|
if (!REGISTERED_MESSAGES.contains(this.id)) {
|
||||||
registeredMessages.add(this.id);
|
REGISTERED_MESSAGES.add(this.id);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Bukkit.getUnsafe().loadAdvancement(this.key, getJSON());
|
Bukkit.getUnsafe().loadAdvancement(this.key, getJSON());
|
||||||
@ -122,8 +122,8 @@ class PopupMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected void remove() {
|
protected void remove() {
|
||||||
if (registeredMessages.contains(this.id)) {
|
if (REGISTERED_MESSAGES.contains(this.id)) {
|
||||||
registeredMessages.remove(this.id);
|
REGISTERED_MESSAGES.remove(this.id);
|
||||||
Bukkit.getUnsafe().removeAdvancement(this.key);
|
Bukkit.getUnsafe().removeAdvancement(this.key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,6 +9,7 @@ import org.bukkit.event.inventory.ClickType;
|
|||||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||||
import org.bukkit.inventory.Inventory;
|
import org.bukkit.inventory.Inventory;
|
||||||
import org.bukkit.inventory.ItemStack;
|
import org.bukkit.inventory.ItemStack;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@ -58,12 +59,12 @@ public class SimplePagedGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SimplePagedGui setItem(int row, int col, ItemStack item) {
|
public @NotNull SimplePagedGui setItem(int row, int col, ItemStack item) {
|
||||||
return setItem(col + row * 9, item);
|
return setItem(col + row * 9, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SimplePagedGui setItem(int cell, ItemStack item) {
|
public @NotNull SimplePagedGui setItem(int cell, ItemStack item) {
|
||||||
// set the cell relative to the current page
|
// set the cell relative to the current page
|
||||||
int cellIndex = cell < 0 ? cell : (this.page == 1 || (this.useHeader && cell < 9) ? cell : (cell + (this.page - 1) * (this.rowsPerPage * 9)));
|
int cellIndex = cell < 0 ? cell : (this.page == 1 || (this.useHeader && cell < 9) ? cell : (cell + (this.page - 1) * (this.rowsPerPage * 9)));
|
||||||
|
|
||||||
@ -130,7 +131,7 @@ public class SimplePagedGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Inventory generateInventory(GuiManager manager) {
|
protected @NotNull Inventory generateInventory(@NotNull GuiManager manager) {
|
||||||
this.guiManager = manager;
|
this.guiManager = manager;
|
||||||
|
|
||||||
// calculate pages here
|
// calculate pages here
|
||||||
@ -189,7 +190,7 @@ public class SimplePagedGui extends Gui {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// last row is dedicated to pagation
|
// the last row is dedicated to pagination
|
||||||
final int cells = this.rows * 9;
|
final int cells = this.rows * 9;
|
||||||
for (int i = cells - 9; i < cells; ++i) {
|
for (int i = cells - 9; i < cells; ++i) {
|
||||||
this.inventory.setItem(i, this.footerBackItem != null ? this.footerBackItem : this.blankItem);
|
this.inventory.setItem(i, this.footerBackItem != null ? this.footerBackItem : this.blankItem);
|
||||||
@ -207,7 +208,7 @@ public class SimplePagedGui extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean onClick(GuiManager manager, Player player, Inventory inventory, InventoryClickEvent event) {
|
protected boolean onClick(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory inventory, InventoryClickEvent event) {
|
||||||
int cell = event.getSlot();
|
int cell = event.getSlot();
|
||||||
Map<ClickType, Clickable> conditionals;
|
Map<ClickType, Clickable> conditionals;
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@ import java.util.UUID;
|
|||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
|
|
||||||
public class ChatPrompt implements Listener {
|
public class ChatPrompt implements Listener {
|
||||||
private static final List<UUID> registered = new ArrayList<>();
|
private static final List<UUID> REGISTERED = new ArrayList<>();
|
||||||
|
|
||||||
private final Plugin plugin;
|
private final Plugin plugin;
|
||||||
private final ChatConfirmHandler handler;
|
private final ChatConfirmHandler handler;
|
||||||
@ -25,19 +25,19 @@ public class ChatPrompt implements Listener {
|
|||||||
private OnCancel onCancel = null;
|
private OnCancel onCancel = null;
|
||||||
private Listener listener;
|
private Listener listener;
|
||||||
|
|
||||||
private ChatPrompt(Plugin plugin, Player player, ChatConfirmHandler hander) {
|
private ChatPrompt(Plugin plugin, Player player, ChatConfirmHandler handler) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.handler = hander;
|
this.handler = handler;
|
||||||
|
|
||||||
registered.add(player.getUniqueId());
|
REGISTERED.add(player.getUniqueId());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ChatPrompt showPrompt(Plugin plugin, Player player, ChatConfirmHandler hander) {
|
public static ChatPrompt showPrompt(Plugin plugin, Player player, ChatConfirmHandler handler) {
|
||||||
return showPrompt(plugin, player, null, hander);
|
return showPrompt(plugin, player, null, handler);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ChatPrompt showPrompt(Plugin plugin, Player player, String message, ChatConfirmHandler hander) {
|
public static ChatPrompt showPrompt(Plugin plugin, Player player, String message, ChatConfirmHandler handler) {
|
||||||
ChatPrompt prompt = new ChatPrompt(plugin, player, hander);
|
ChatPrompt prompt = new ChatPrompt(plugin, player, handler);
|
||||||
prompt.startListener(plugin);
|
prompt.startListener(plugin);
|
||||||
player.closeInventory();
|
player.closeInventory();
|
||||||
|
|
||||||
@ -49,11 +49,11 @@ public class ChatPrompt implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isRegistered(Player player) {
|
public static boolean isRegistered(Player player) {
|
||||||
return registered.contains(player.getUniqueId());
|
return REGISTERED.contains(player.getUniqueId());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean unregister(Player player) {
|
public static boolean unregister(Player player) {
|
||||||
return registered.remove(player.getUniqueId());
|
return REGISTERED.remove(player.getUniqueId());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ChatPrompt setOnClose(OnClose onClose) {
|
public ChatPrompt setOnClose(OnClose onClose) {
|
||||||
@ -67,13 +67,13 @@ public class ChatPrompt implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ChatPrompt setTimeOut(Player player, long ticks) {
|
public ChatPrompt setTimeOut(Player player, long ticks) {
|
||||||
taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
|
this.taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, () -> {
|
||||||
if (onClose != null) {
|
if (this.onClose != null) {
|
||||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () ->
|
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, () ->
|
||||||
onClose.onClose(), 0L);
|
this.onClose.onClose(), 0L);
|
||||||
}
|
}
|
||||||
|
|
||||||
HandlerList.unregisterAll(listener);
|
HandlerList.unregisterAll(this.listener);
|
||||||
player.sendMessage("Your action has timed out.");
|
player.sendMessage("Your action has timed out.");
|
||||||
}, ticks);
|
}, ticks);
|
||||||
|
|
||||||
@ -95,20 +95,20 @@ public class ChatPrompt implements Listener {
|
|||||||
|
|
||||||
ChatConfirmEvent chatConfirmEvent = new ChatConfirmEvent(player, event.getMessage());
|
ChatConfirmEvent chatConfirmEvent = new ChatConfirmEvent(player, event.getMessage());
|
||||||
|
|
||||||
player.sendMessage("\u00BB " + event.getMessage());
|
player.sendMessage("» " + event.getMessage());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
handler.onChat(chatConfirmEvent);
|
ChatPrompt.this.handler.onChat(chatConfirmEvent);
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
plugin.getLogger().log(Level.SEVERE, "Failed to process chat prompt", t);
|
plugin.getLogger().log(Level.SEVERE, "Failed to process chat prompt", t);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (onClose != null) {
|
if (ChatPrompt.this.onClose != null) {
|
||||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onClose.onClose(), 0L);
|
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ChatPrompt.this.onClose.onClose(), 0L);
|
||||||
}
|
}
|
||||||
|
|
||||||
HandlerList.unregisterAll(listener);
|
HandlerList.unregisterAll(ChatPrompt.this.listener);
|
||||||
Bukkit.getScheduler().cancelTask(taskId);
|
Bukkit.getScheduler().cancelTask(ChatPrompt.this.taskId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.LOWEST)
|
@EventHandler(priority = EventPriority.LOWEST)
|
||||||
@ -125,18 +125,18 @@ public class ChatPrompt implements Listener {
|
|||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (onCancel != null) {
|
if (ChatPrompt.this.onCancel != null) {
|
||||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onCancel.onCancel(), 0L);
|
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ChatPrompt.this.onCancel.onCancel(), 0L);
|
||||||
} else if (onClose != null) {
|
} else if (ChatPrompt.this.onClose != null) {
|
||||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onClose.onClose(), 0L);
|
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ChatPrompt.this.onClose.onClose(), 0L);
|
||||||
}
|
}
|
||||||
|
|
||||||
HandlerList.unregisterAll(listener);
|
HandlerList.unregisterAll(ChatPrompt.this.listener);
|
||||||
Bukkit.getScheduler().cancelTask(taskId);
|
Bukkit.getScheduler().cancelTask(ChatPrompt.this.taskId);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Bukkit.getPluginManager().registerEvents(listener, plugin);
|
Bukkit.getPluginManager().registerEvents(this.listener, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
public interface ChatConfirmHandler {
|
public interface ChatConfirmHandler {
|
||||||
@ -161,11 +161,11 @@ public class ChatPrompt implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Player getPlayer() {
|
public Player getPlayer() {
|
||||||
return player;
|
return this.player;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getMessage() {
|
public String getMessage() {
|
||||||
return message;
|
return this.message;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -12,13 +12,13 @@ import java.io.BufferedReader;
|
|||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.nio.charset.Charset;
|
import java.nio.charset.Charset;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -191,7 +191,9 @@ public class Locale {
|
|||||||
}
|
}
|
||||||
|
|
||||||
File localeFolder = new File(plugin.getDataFolder(), "locales/");
|
File localeFolder = new File(plugin.getDataFolder(), "locales/");
|
||||||
if (!localeFolder.exists()) localeFolder.mkdirs();
|
if (!localeFolder.exists()) {
|
||||||
|
localeFolder.mkdirs();
|
||||||
|
}
|
||||||
|
|
||||||
if (!fileName.endsWith(FILE_EXTENSION)) {
|
if (!fileName.endsWith(FILE_EXTENSION)) {
|
||||||
fileName = fileName + FILE_EXTENSION;
|
fileName = fileName + FILE_EXTENSION;
|
||||||
@ -202,7 +204,7 @@ public class Locale {
|
|||||||
return updateFiles(plugin, in, destinationFile, builtin);
|
return updateFiles(plugin, in, destinationFile, builtin);
|
||||||
}
|
}
|
||||||
|
|
||||||
try (OutputStream outputStream = new FileOutputStream(destinationFile)) {
|
try (OutputStream outputStream = Files.newOutputStream(destinationFile.toPath())) {
|
||||||
copy(in, outputStream);
|
copy(in, outputStream);
|
||||||
|
|
||||||
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
|
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
|
||||||
@ -217,7 +219,7 @@ public class Locale {
|
|||||||
// Write new changes to existing files, if any at all
|
// Write new changes to existing files, if any at all
|
||||||
private static boolean updateFiles(Plugin plugin, InputStream defaultFile, File existingFile, boolean builtin) {
|
private static boolean updateFiles(Plugin plugin, InputStream defaultFile, File existingFile, boolean builtin) {
|
||||||
try (BufferedInputStream defaultIn = new BufferedInputStream(defaultFile);
|
try (BufferedInputStream defaultIn = new BufferedInputStream(defaultFile);
|
||||||
BufferedInputStream existingIn = new BufferedInputStream(new FileInputStream(existingFile))) {
|
BufferedInputStream existingIn = new BufferedInputStream(Files.newInputStream(existingFile.toPath()))) {
|
||||||
|
|
||||||
Charset defaultCharset = TextUtils.detectCharset(defaultIn, StandardCharsets.UTF_8);
|
Charset defaultCharset = TextUtils.detectCharset(defaultIn, StandardCharsets.UTF_8);
|
||||||
Charset existingCharset = TextUtils.detectCharset(existingIn, StandardCharsets.UTF_8);
|
Charset existingCharset = TextUtils.detectCharset(existingIn, StandardCharsets.UTF_8);
|
||||||
@ -291,29 +293,29 @@ public class Locale {
|
|||||||
*/
|
*/
|
||||||
public boolean reloadMessages() {
|
public boolean reloadMessages() {
|
||||||
if (!this.file.exists()) {
|
if (!this.file.exists()) {
|
||||||
plugin.getLogger().warning("Could not find file for locale \"" + this.name + "\"");
|
this.plugin.getLogger().warning("Could not find file for locale \"" + this.name + "\"");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.nodes.clear(); // Clear previous data (if any)
|
this.nodes.clear(); // Clear previous data (if any)
|
||||||
|
|
||||||
// guess what encoding this file is in
|
// guess what encoding this file is in
|
||||||
Charset charset = TextUtils.detectCharset(file, null);
|
Charset charset = TextUtils.detectCharset(this.file, null);
|
||||||
if (charset == null) {
|
if (charset == null) {
|
||||||
plugin.getLogger().warning("Could not determine charset for locale \"" + this.name + "\"");
|
this.plugin.getLogger().warning("Could not determine charset for locale \"" + this.name + "\"");
|
||||||
charset = StandardCharsets.UTF_8;
|
charset = StandardCharsets.UTF_8;
|
||||||
}
|
}
|
||||||
|
|
||||||
// load in the file!
|
// load in the file!
|
||||||
try (FileInputStream stream = new FileInputStream(file);
|
try (FileInputStream stream = new FileInputStream(this.file);
|
||||||
BufferedReader source = new BufferedReader(new InputStreamReader(stream, charset));
|
BufferedReader source = new BufferedReader(new InputStreamReader(stream, charset));
|
||||||
BufferedReader reader = translatePropertyToYAML(source, charset)) {
|
BufferedReader reader = translatePropertyToYAML(source, charset)) {
|
||||||
Config lang = new Config(file);
|
Config lang = new Config(this.file);
|
||||||
lang.load(reader);
|
lang.load(reader);
|
||||||
translateMsgRoot(lang, file, charset);
|
translateMsgRoot(lang, this.file, charset);
|
||||||
|
|
||||||
// load lists as strings with newlines
|
// load lists as strings with newlines
|
||||||
lang.getValues(true).forEach((k, v) -> nodes.put(k,
|
lang.getValues(true).forEach((k, v) -> this.nodes.put(k,
|
||||||
v instanceof List
|
v instanceof List
|
||||||
? (((List<?>) v).stream().map(Object::toString).collect(Collectors.joining("\n")))
|
? (((List<?>) v).stream().map(Object::toString).collect(Collectors.joining("\n")))
|
||||||
: v.toString()));
|
: v.toString()));
|
||||||
@ -322,7 +324,7 @@ public class Locale {
|
|||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
} catch (InvalidConfigurationException ex) {
|
} catch (InvalidConfigurationException ex) {
|
||||||
Logger.getLogger(Locale.class.getName()).log(Level.SEVERE, "Configuration error in language file \"" + file.getName() + "\"", ex);
|
Logger.getLogger(Locale.class.getName()).log(Level.SEVERE, "Configuration error in language file \"" + this.file.getName() + "\"", ex);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@ -426,7 +428,7 @@ public class Locale {
|
|||||||
* @return applied message
|
* @return applied message
|
||||||
*/
|
*/
|
||||||
private Message supplyPrefix(Message message) {
|
private Message supplyPrefix(Message message) {
|
||||||
return message.setPrefix(this.nodes.getOrDefault("general.nametag.prefix", "[" + plugin.getName() + "]"));
|
return message.setPrefix(this.nodes.getOrDefault("general.nametag.prefix", "[" + this.plugin.getName() + "]"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -477,7 +479,7 @@ public class Locale {
|
|||||||
* @return the locale name
|
* @return the locale name
|
||||||
*/
|
*/
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return this.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void copy(InputStream input, OutputStream output) {
|
private static void copy(InputStream input, OutputStream output) {
|
||||||
|
@ -69,7 +69,7 @@ public class Message {
|
|||||||
* @param sender command sender to send the message to
|
* @param sender command sender to send the message to
|
||||||
*/
|
*/
|
||||||
public void sendMessage(CommandSender sender) {
|
public void sendMessage(CommandSender sender) {
|
||||||
message.sendTo(sender);
|
this.message.sendTo(sender);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -129,7 +129,7 @@ public class Message {
|
|||||||
* @return the prefixed message
|
* @return the prefixed message
|
||||||
*/
|
*/
|
||||||
public String getPrefixedMessage() {
|
public String getPrefixedMessage() {
|
||||||
return TextUtils.formatText((prefix == null ? "" : this.prefix.toText()) + " " + this.message.toText());
|
return TextUtils.formatText((this.prefix == null ? "" : this.prefix.toText()) + " " + this.message.toText());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -170,7 +170,7 @@ public class Message {
|
|||||||
*/
|
*/
|
||||||
public Message processPlaceholder(String placeholder, Object replacement) {
|
public Message processPlaceholder(String placeholder, Object replacement) {
|
||||||
final String place = Matcher.quoteReplacement(placeholder);
|
final String place = Matcher.quoteReplacement(placeholder);
|
||||||
this.message = message.replaceAll("%" + place + "%|\\{" + place + "\\}", replacement == null ? "" : Matcher.quoteReplacement(replacement.toString()));
|
this.message = this.message.replaceAll("%" + place + "%|\\{" + place + "\\}", replacement == null ? "" : Matcher.quoteReplacement(replacement.toString()));
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
@ -13,10 +13,10 @@ public class Lootables {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getLootablesDir() {
|
public String getLootablesDir() {
|
||||||
return lootablesDir;
|
return this.lootablesDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LootManager getLootManager() {
|
public LootManager getLootManager() {
|
||||||
return lootManager;
|
return this.lootManager;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -31,14 +31,14 @@ public abstract class AbstractGuiListEditor extends Gui {
|
|||||||
setButton(2, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
setButton(2, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
||||||
TextUtils.formatText("&cBack")),
|
TextUtils.formatText("&cBack")),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
guiManager.showGUI(event.player, returnGui);
|
this.guiManager.showGUI(event.player, this.returnGui);
|
||||||
((GuiLootEditor) returnGui).paint();
|
((GuiLootEditor) this.returnGui).paint();
|
||||||
});
|
});
|
||||||
setButton(6, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
setButton(6, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
||||||
TextUtils.formatText("&cBack")),
|
TextUtils.formatText("&cBack")),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
guiManager.showGUI(event.player, returnGui);
|
this.guiManager.showGUI(event.player, this.returnGui);
|
||||||
((GuiLootEditor) returnGui).paint();
|
((GuiLootEditor) this.returnGui).paint();
|
||||||
});
|
});
|
||||||
setButton(3, GuiUtils.createButtonItem(XMaterial.ARROW,
|
setButton(3, GuiUtils.createButtonItem(XMaterial.ARROW,
|
||||||
TextUtils.formatText("&aAdd new line")),
|
TextUtils.formatText("&aAdd new line")),
|
||||||
@ -54,7 +54,7 @@ public abstract class AbstractGuiListEditor extends Gui {
|
|||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
gui.setTitle("Enter a new line");
|
gui.setTitle("Enter a new line");
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setItem(4, GuiUtils.createButtonItem(XMaterial.WRITABLE_BOOK,
|
setItem(4, GuiUtils.createButtonItem(XMaterial.WRITABLE_BOOK,
|
||||||
|
@ -29,35 +29,35 @@ public class GuiEditor extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void paint() {
|
private void paint() {
|
||||||
if (inventory != null) {
|
if (this.inventory != null) {
|
||||||
inventory.clear();
|
this.inventory.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
setActionForRange(0, 0, 5, 9, null);
|
setActionForRange(0, 0, 5, 9, null);
|
||||||
|
|
||||||
List<Lootable> lootables = new ArrayList<>(lootManager.getRegisteredLootables().values());
|
List<Lootable> lootables = new ArrayList<>(this.lootManager.getRegisteredLootables().values());
|
||||||
|
|
||||||
double itemCount = lootables.size();
|
double itemCount = lootables.size();
|
||||||
this.pages = (int) Math.max(1, Math.ceil(itemCount / 36));
|
this.pages = (int) Math.max(1, Math.ceil(itemCount / 36));
|
||||||
|
|
||||||
if (page != 1) {
|
if (this.page != 1) {
|
||||||
setButton(5, 2, GuiUtils.createButtonItem(XMaterial.ARROW, "Back"),
|
setButton(5, 2, GuiUtils.createButtonItem(XMaterial.ARROW, "Back"),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
page--;
|
this.page--;
|
||||||
paint();
|
paint();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (page != pages) {
|
if (this.page != this.pages) {
|
||||||
setButton(5, 6, GuiUtils.createButtonItem(XMaterial.ARROW, "Next"),
|
setButton(5, 6, GuiUtils.createButtonItem(XMaterial.ARROW, "Next"),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
page++;
|
this.page++;
|
||||||
paint();
|
paint();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int i = 9; i < 45; i++) {
|
for (int i = 9; i < 45; i++) {
|
||||||
int current = ((page - 1) * 36) - 9;
|
int current = ((this.page - 1) * 36) - 9;
|
||||||
if (current + i >= lootables.size()) {
|
if (current + i >= lootables.size()) {
|
||||||
setItem(i, null);
|
setItem(i, null);
|
||||||
continue;
|
continue;
|
||||||
@ -69,7 +69,7 @@ public class GuiEditor extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setButton(i, getIcon(lootable.getKey()),
|
setButton(i, getIcon(lootable.getKey()),
|
||||||
(event) -> guiManager.showGUI(event.player, new GuiLootableEditor(lootManager, lootable, this)));
|
(event) -> this.guiManager.showGUI(event.player, new GuiLootableEditor(this.lootManager, lootable, this)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -31,19 +31,19 @@ public class GuiEnchantEditor extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void paint() {
|
public void paint() {
|
||||||
Map<String, Integer> lore = loot.getEnchants() == null ? new HashMap<>() : new HashMap<>(loot.getEnchants());
|
Map<String, Integer> lore = this.loot.getEnchants() == null ? new HashMap<>() : new HashMap<>(this.loot.getEnchants());
|
||||||
|
|
||||||
setButton(2, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
setButton(2, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
||||||
TextUtils.formatText("&cBack")),
|
TextUtils.formatText("&cBack")),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
guiManager.showGUI(event.player, returnGui);
|
this.guiManager.showGUI(event.player, this.returnGui);
|
||||||
((GuiLootEditor) returnGui).paint();
|
((GuiLootEditor) this.returnGui).paint();
|
||||||
});
|
});
|
||||||
setButton(6, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
setButton(6, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
||||||
TextUtils.formatText("&cBack")),
|
TextUtils.formatText("&cBack")),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
guiManager.showGUI(event.player, returnGui);
|
this.guiManager.showGUI(event.player, this.returnGui);
|
||||||
((GuiLootEditor) returnGui).paint();
|
((GuiLootEditor) this.returnGui).paint();
|
||||||
});
|
});
|
||||||
setButton(3, GuiUtils.createButtonItem(XMaterial.ARROW,
|
setButton(3, GuiUtils.createButtonItem(XMaterial.ARROW,
|
||||||
TextUtils.formatText("&aAdd new line")),
|
TextUtils.formatText("&aAdd new line")),
|
||||||
@ -59,16 +59,16 @@ public class GuiEnchantEditor extends Gui {
|
|||||||
AnvilGui gui1 = new AnvilGui(event.player, this);
|
AnvilGui gui1 = new AnvilGui(event.player, this);
|
||||||
gui1.setAction((ee -> {
|
gui1.setAction((ee -> {
|
||||||
lore.put(gui.getInputText().toUpperCase().trim(), Integer.parseInt(gui1.getInputText().trim()));
|
lore.put(gui.getInputText().toUpperCase().trim(), Integer.parseInt(gui1.getInputText().trim()));
|
||||||
loot.setEnchants(lore);
|
this.loot.setEnchants(lore);
|
||||||
ee.player.closeInventory();
|
ee.player.closeInventory();
|
||||||
paint();
|
paint();
|
||||||
}));
|
}));
|
||||||
gui1.setTitle("Enter a level");
|
gui1.setTitle("Enter a level");
|
||||||
guiManager.showGUI(event.player, gui1);
|
this.guiManager.showGUI(event.player, gui1);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
gui.setTitle("Enter an enchant");
|
gui.setTitle("Enter an enchant");
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
List<String> enchantments = new ArrayList<>();
|
List<String> enchantments = new ArrayList<>();
|
||||||
@ -93,7 +93,7 @@ public class GuiEnchantEditor extends Gui {
|
|||||||
TextUtils.formatText("&cRemove the last line")),
|
TextUtils.formatText("&cRemove the last line")),
|
||||||
(event -> {
|
(event -> {
|
||||||
lore.remove(lastFinal);
|
lore.remove(lastFinal);
|
||||||
loot.setEnchants(lore);
|
this.loot.setEnchants(lore);
|
||||||
paint();
|
paint();
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
@ -14,12 +14,12 @@ public class GuiEntityEditor extends AbstractGuiListEditor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected List<String> getData() {
|
protected List<String> getData() {
|
||||||
return loot.getOnlyDropFor().stream().map(Enum::name).collect(Collectors.toList());
|
return this.loot.getOnlyDropFor().stream().map(Enum::name).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void updateData(List<String> list) {
|
protected void updateData(List<String> list) {
|
||||||
loot.setOnlyDropFor(list.stream().map(EntityType::valueOf).collect(Collectors.toList()));
|
this.loot.setOnlyDropFor(list.stream().map(EntityType::valueOf).collect(Collectors.toList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -41,52 +41,52 @@ public class GuiLootEditor extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void paint() {
|
public void paint() {
|
||||||
if (inventory != null) {
|
if (this.inventory != null) {
|
||||||
inventory.clear();
|
this.inventory.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
setActionForRange(0, 0, 5, 9, null);
|
setActionForRange(0, 0, 5, 9, null);
|
||||||
|
|
||||||
setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, TextUtils.formatText("&cBack")),
|
setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, TextUtils.formatText("&cBack")),
|
||||||
(event) -> guiManager.showGUI(event.player, returnGui));
|
(event) -> this.guiManager.showGUI(event.player, this.returnGui));
|
||||||
|
|
||||||
setButton(9, GuiUtils.createButtonItem(loot.getMaterial() == null ? XMaterial.BARRIER : loot.getMaterial(),
|
setButton(9, GuiUtils.createButtonItem(this.loot.getMaterial() == null ? XMaterial.BARRIER : this.loot.getMaterial(),
|
||||||
TextUtils.formatText("&7Current Material: &6" + (loot.getMaterial() != null
|
TextUtils.formatText("&7Current Material: &6" + (this.loot.getMaterial() != null
|
||||||
? loot.getMaterial().name() : "None")), TextUtils.formatText(
|
? this.loot.getMaterial().name() : "None")), TextUtils.formatText(
|
||||||
Arrays.asList("",
|
Arrays.asList("",
|
||||||
"&8Click to set the material to",
|
"&8Click to set the material to",
|
||||||
"&8the material in your hand.")
|
"&8the material in your hand.")
|
||||||
)), (event) -> {
|
)), (event) -> {
|
||||||
ItemStack stack = event.player.getInventory().getItemInMainHand();
|
ItemStack stack = event.player.getInventory().getItemInMainHand();
|
||||||
loot.setMaterial(CompatibleMaterial.getMaterial(stack.getType()).get());
|
this.loot.setMaterial(CompatibleMaterial.getMaterial(stack.getType()).get());
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(10, GuiUtils.createButtonItem(XMaterial.PAPER,
|
setButton(10, GuiUtils.createButtonItem(XMaterial.PAPER,
|
||||||
TextUtils.formatText("&7Name Override: &6" + (loot.getName() == null ? "None set" : loot.getName()))),
|
TextUtils.formatText("&7Name Override: &6" + (this.loot.getName() == null ? "None set" : this.loot.getName()))),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
gui.setAction((e -> {
|
gui.setAction((e -> {
|
||||||
loot.setName(gui.getInputText().trim());
|
this.loot.setName(gui.getInputText().trim());
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
e.player.closeInventory();
|
e.player.closeInventory();
|
||||||
}));
|
}));
|
||||||
|
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, loot.getName()));
|
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, this.loot.getName()));
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(11, GuiUtils.createButtonItem(XMaterial.WRITABLE_BOOK,
|
setButton(11, GuiUtils.createButtonItem(XMaterial.WRITABLE_BOOK,
|
||||||
TextUtils.formatText("&7Lore Override:"),
|
TextUtils.formatText("&7Lore Override:"),
|
||||||
TextUtils.formatText(loot.getLore() == null ? Collections.singletonList("&6None set") : loot.getLore())),
|
TextUtils.formatText(this.loot.getLore() == null ? Collections.singletonList("&6None set") : this.loot.getLore())),
|
||||||
(event) -> guiManager.showGUI(event.player, new GuiLoreEditor(loot, this)));
|
(event) -> this.guiManager.showGUI(event.player, new GuiLoreEditor(this.loot, this)));
|
||||||
|
|
||||||
List<String> enchantments = new ArrayList<>();
|
List<String> enchantments = new ArrayList<>();
|
||||||
|
|
||||||
if (loot.getEnchants() != null) {
|
if (this.loot.getEnchants() != null) {
|
||||||
for (Map.Entry<String, Integer> entry : loot.getEnchants().entrySet()) {
|
for (Map.Entry<String, Integer> entry : this.loot.getEnchants().entrySet()) {
|
||||||
enchantments.add("&6" + entry.getKey() + " " + entry.getValue());
|
enchantments.add("&6" + entry.getKey() + " " + entry.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -94,29 +94,29 @@ public class GuiLootEditor extends Gui {
|
|||||||
setButton(12, GuiUtils.createButtonItem(XMaterial.ENCHANTED_BOOK,
|
setButton(12, GuiUtils.createButtonItem(XMaterial.ENCHANTED_BOOK,
|
||||||
TextUtils.formatText("&7Enchantments:"),
|
TextUtils.formatText("&7Enchantments:"),
|
||||||
TextUtils.formatText(enchantments.isEmpty() ? Collections.singletonList("&6None set") : enchantments)),
|
TextUtils.formatText(enchantments.isEmpty() ? Collections.singletonList("&6None set") : enchantments)),
|
||||||
(event) -> guiManager.showGUI(event.player, new GuiEnchantEditor(loot, this)));
|
(event) -> this.guiManager.showGUI(event.player, new GuiEnchantEditor(this.loot, this)));
|
||||||
|
|
||||||
setButton(13, GuiUtils.createButtonItem(
|
setButton(13, GuiUtils.createButtonItem(
|
||||||
loot.getBurnedMaterial() == null
|
this.loot.getBurnedMaterial() == null
|
||||||
? XMaterial.FIRE_CHARGE
|
? XMaterial.FIRE_CHARGE
|
||||||
: loot.getBurnedMaterial(),
|
: this.loot.getBurnedMaterial(),
|
||||||
TextUtils.formatText("&7Current Burned Material: &6"
|
TextUtils.formatText("&7Current Burned Material: &6"
|
||||||
+ (loot.getBurnedMaterial() == null
|
+ (this.loot.getBurnedMaterial() == null
|
||||||
? "None"
|
? "None"
|
||||||
: loot.getBurnedMaterial().name())), TextUtils.formatText(
|
: this.loot.getBurnedMaterial().name())), TextUtils.formatText(
|
||||||
Arrays.asList("",
|
Arrays.asList("",
|
||||||
"&8Click to set the burned material to",
|
"&8Click to set the burned material to",
|
||||||
"&8the material in your hand.")
|
"&8the material in your hand.")
|
||||||
)),
|
)),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
ItemStack stack = event.player.getInventory().getItemInMainHand();
|
ItemStack stack = event.player.getInventory().getItemInMainHand();
|
||||||
loot.setBurnedMaterial(CompatibleMaterial.getMaterial(stack.getType()).get());
|
this.loot.setBurnedMaterial(CompatibleMaterial.getMaterial(stack.getType()).get());
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(14, GuiUtils.createButtonItem(XMaterial.CLOCK,
|
setButton(14, GuiUtils.createButtonItem(XMaterial.CLOCK,
|
||||||
TextUtils.formatText("&7Chance: &6" + loot.getChance()),
|
TextUtils.formatText("&7Chance: &6" + this.loot.getChance()),
|
||||||
TextUtils.formatText(
|
TextUtils.formatText(
|
||||||
Arrays.asList("",
|
Arrays.asList("",
|
||||||
"&8Click to edit this loots",
|
"&8Click to edit this loots",
|
||||||
@ -126,124 +126,124 @@ public class GuiLootEditor extends Gui {
|
|||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
|
|
||||||
gui.setAction((e) -> {
|
gui.setAction((e) -> {
|
||||||
loot.setChance(Double.parseDouble(gui.getInputText()));
|
this.loot.setChance(Double.parseDouble(gui.getInputText()));
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
e.player.closeInventory();
|
e.player.closeInventory();
|
||||||
});
|
});
|
||||||
|
|
||||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getChance())));
|
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getChance())));
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(15, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
setButton(15, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
||||||
TextUtils.formatText("&7Min Drop Amount: &6" + loot.getMin())),
|
TextUtils.formatText("&7Min Drop Amount: &6" + this.loot.getMin())),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
|
|
||||||
gui.setAction((e) -> {
|
gui.setAction((e) -> {
|
||||||
loot.setMin(Integer.parseInt(gui.getInputText()));
|
this.loot.setMin(Integer.parseInt(gui.getInputText()));
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
e.player.closeInventory();
|
e.player.closeInventory();
|
||||||
});
|
});
|
||||||
|
|
||||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER,
|
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER,
|
||||||
String.valueOf(loot.getMin())));
|
String.valueOf(this.loot.getMin())));
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(16, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
setButton(16, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
||||||
TextUtils.formatText("&7Max Drop Amount: &6" + loot.getMax())),
|
TextUtils.formatText("&7Max Drop Amount: &6" + this.loot.getMax())),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
|
|
||||||
gui.setAction((e) -> {
|
gui.setAction((e) -> {
|
||||||
loot.setMax(Integer.parseInt(gui.getInputText()));
|
this.loot.setMax(Integer.parseInt(gui.getInputText()));
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
e.player.closeInventory();
|
e.player.closeInventory();
|
||||||
});
|
});
|
||||||
|
|
||||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getMax())));
|
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getMax())));
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(17, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
setButton(17, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
||||||
TextUtils.formatText("&7Min Item Damage: &6" + loot.getDamageMin())),
|
TextUtils.formatText("&7Min Item Damage: &6" + this.loot.getDamageMin())),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
gui.setAction((e) -> {
|
gui.setAction((e) -> {
|
||||||
loot.setDamageMin(Integer.parseInt(gui.getInputText()));
|
this.loot.setDamageMin(Integer.parseInt(gui.getInputText()));
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
e.player.closeInventory();
|
e.player.closeInventory();
|
||||||
});
|
});
|
||||||
|
|
||||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getDamageMin())));
|
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getDamageMin())));
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(18, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
setButton(18, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
||||||
TextUtils.formatText("&7Max Item Damage: &6" + loot.getDamageMax())),
|
TextUtils.formatText("&7Max Item Damage: &6" + this.loot.getDamageMax())),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
gui.setAction((e) -> {
|
gui.setAction((e) -> {
|
||||||
loot.setDamageMax(Integer.parseInt(gui.getInputText()));
|
this.loot.setDamageMax(Integer.parseInt(gui.getInputText()));
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
e.player.closeInventory();
|
e.player.closeInventory();
|
||||||
});
|
});
|
||||||
|
|
||||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getDamageMax())));
|
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getDamageMax())));
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(19, GuiUtils.createButtonItem(XMaterial.CHEST,
|
setButton(19, GuiUtils.createButtonItem(XMaterial.CHEST,
|
||||||
TextUtils.formatText("&7Allow Looting Enchantment?: &6" + loot.isAllowLootingEnchant())),
|
TextUtils.formatText("&7Allow Looting Enchantment?: &6" + this.loot.isAllowLootingEnchant())),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
loot.setAllowLootingEnchant(!loot.isAllowLootingEnchant());
|
this.loot.setAllowLootingEnchant(!this.loot.isAllowLootingEnchant());
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
event.player.closeInventory();
|
event.player.closeInventory();
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(20, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
setButton(20, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
||||||
TextUtils.formatText("&7Min Child Loot Min: &6" + loot.getChildDropCountMin())),
|
TextUtils.formatText("&7Min Child Loot Min: &6" + this.loot.getChildDropCountMin())),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
|
|
||||||
gui.setAction((e) -> {
|
gui.setAction((e) -> {
|
||||||
loot.setChildDropCountMin(Integer.parseInt(gui.getInputText()));
|
this.loot.setChildDropCountMin(Integer.parseInt(gui.getInputText()));
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
e.player.closeInventory();
|
e.player.closeInventory();
|
||||||
});
|
});
|
||||||
|
|
||||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getChildDropCountMin())));
|
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getChildDropCountMin())));
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
});
|
});
|
||||||
|
|
||||||
setButton(21, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
setButton(21, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
||||||
TextUtils.formatText("&7Min Child Loot Max: &6" + loot.getChildDropCountMax())),
|
TextUtils.formatText("&7Min Child Loot Max: &6" + this.loot.getChildDropCountMax())),
|
||||||
(event) -> {
|
(event) -> {
|
||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
|
|
||||||
gui.setAction((e) -> {
|
gui.setAction((e) -> {
|
||||||
loot.setChildDropCountMax(Integer.parseInt(gui.getInputText()));
|
this.loot.setChildDropCountMax(Integer.parseInt(gui.getInputText()));
|
||||||
|
|
||||||
paint();
|
paint();
|
||||||
e.player.closeInventory();
|
e.player.closeInventory();
|
||||||
});
|
});
|
||||||
|
|
||||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getChildDropCountMax())));
|
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getChildDropCountMax())));
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
});
|
});
|
||||||
|
|
||||||
List<String> entities = new ArrayList<>();
|
List<String> entities = new ArrayList<>();
|
||||||
|
|
||||||
if (loot.getOnlyDropFor() != null) {
|
if (this.loot.getOnlyDropFor() != null) {
|
||||||
for (EntityType entity : loot.getOnlyDropFor()) {
|
for (EntityType entity : this.loot.getOnlyDropFor()) {
|
||||||
entities.add("&6" + entity.name());
|
entities.add("&6" + entity.name());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -251,7 +251,7 @@ public class GuiLootEditor extends Gui {
|
|||||||
setButton(22, GuiUtils.createButtonItem(XMaterial.ENCHANTED_BOOK,
|
setButton(22, GuiUtils.createButtonItem(XMaterial.ENCHANTED_BOOK,
|
||||||
TextUtils.formatText("&7Only Drop For:"),
|
TextUtils.formatText("&7Only Drop For:"),
|
||||||
TextUtils.formatText(entities)),
|
TextUtils.formatText(entities)),
|
||||||
(event) -> guiManager.showGUI(event.player, new GuiEntityEditor(loot, this)));
|
(event) -> this.guiManager.showGUI(event.player, new GuiEntityEditor(this.loot, this)));
|
||||||
|
|
||||||
setButton(4, 0, GuiUtils.createButtonItem(XMaterial.LIME_DYE, TextUtils.formatText("&aCreate new Child Loot")),
|
setButton(4, 0, GuiUtils.createButtonItem(XMaterial.LIME_DYE, TextUtils.formatText("&aCreate new Child Loot")),
|
||||||
(event -> {
|
(event -> {
|
||||||
@ -259,7 +259,7 @@ public class GuiLootEditor extends Gui {
|
|||||||
|
|
||||||
gui.setAction((event1 -> {
|
gui.setAction((event1 -> {
|
||||||
try {
|
try {
|
||||||
loot.addChildLoots(new LootBuilder().setMaterial(XMaterial.valueOf(gui.getInputText().trim())).build());
|
this.loot.addChildLoots(new LootBuilder().setMaterial(XMaterial.valueOf(gui.getInputText().trim())).build());
|
||||||
} catch (IllegalArgumentException ignore) {
|
} catch (IllegalArgumentException ignore) {
|
||||||
event.player.sendMessage("That is not a valid material.");
|
event.player.sendMessage("That is not a valid material.");
|
||||||
}
|
}
|
||||||
@ -269,11 +269,11 @@ public class GuiLootEditor extends Gui {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
gui.setTitle("Enter a material");
|
gui.setTitle("Enter a material");
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
int i = 9 * 5;
|
int i = 9 * 5;
|
||||||
for (Loot loot : loot.getChildLoot()) {
|
for (Loot loot : this.loot.getChildLoot()) {
|
||||||
ItemStack item = loot.getMaterial() == null
|
ItemStack item = loot.getMaterial() == null
|
||||||
? XMaterial.BARRIER.parseItem()
|
? XMaterial.BARRIER.parseItem()
|
||||||
: GuiUtils.createButtonItem(loot.getMaterial(), null,
|
: GuiUtils.createButtonItem(loot.getMaterial(), null,
|
||||||
@ -286,7 +286,7 @@ public class GuiLootEditor extends Gui {
|
|||||||
this.loot.removeChildLoot(loot);
|
this.loot.removeChildLoot(loot);
|
||||||
paint();
|
paint();
|
||||||
} else if (event.clickType == ClickType.LEFT) {
|
} else if (event.clickType == ClickType.LEFT) {
|
||||||
guiManager.showGUI(event.player, new GuiLootEditor(lootManager, loot, this));
|
this.guiManager.showGUI(event.player, new GuiLootEditor(this.lootManager, loot, this));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -33,8 +33,8 @@ public class GuiLootableEditor extends Gui {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void paint() {
|
private void paint() {
|
||||||
if (inventory != null) {
|
if (this.inventory != null) {
|
||||||
inventory.clear();
|
this.inventory.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
setActionForRange(0, 0, 5, 9, null);
|
setActionForRange(0, 0, 5, 9, null);
|
||||||
@ -44,7 +44,7 @@ public class GuiLootableEditor extends Gui {
|
|||||||
AnvilGui gui = new AnvilGui(event.player, this);
|
AnvilGui gui = new AnvilGui(event.player, this);
|
||||||
gui.setAction((event1 -> {
|
gui.setAction((event1 -> {
|
||||||
try {
|
try {
|
||||||
lootable.registerLoot(new LootBuilder().setMaterial(XMaterial.valueOf(gui.getInputText().trim().toUpperCase())).build());
|
this.lootable.registerLoot(new LootBuilder().setMaterial(XMaterial.valueOf(gui.getInputText().trim().toUpperCase())).build());
|
||||||
} catch (IllegalArgumentException ex) {
|
} catch (IllegalArgumentException ex) {
|
||||||
event.player.sendMessage("That is not a valid material.");
|
event.player.sendMessage("That is not a valid material.");
|
||||||
}
|
}
|
||||||
@ -54,14 +54,14 @@ public class GuiLootableEditor extends Gui {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
gui.setTitle("Enter a material");
|
gui.setTitle("Enter a material");
|
||||||
guiManager.showGUI(event.player, gui);
|
this.guiManager.showGUI(event.player, gui);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, TextUtils.formatText("&cBack")),
|
setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, TextUtils.formatText("&cBack")),
|
||||||
(event -> guiManager.showGUI(event.player, returnGui)));
|
(event -> this.guiManager.showGUI(event.player, this.returnGui)));
|
||||||
|
|
||||||
int i = 9;
|
int i = 9;
|
||||||
for (Loot loot : lootable.getRegisteredLoot()) {
|
for (Loot loot : this.lootable.getRegisteredLoot()) {
|
||||||
ItemStack item = loot.getMaterial() == null
|
ItemStack item = loot.getMaterial() == null
|
||||||
? XMaterial.BARRIER.parseItem()
|
? XMaterial.BARRIER.parseItem()
|
||||||
: GuiUtils.createButtonItem(loot.getMaterial(), null,
|
: GuiUtils.createButtonItem(loot.getMaterial(), null,
|
||||||
@ -71,14 +71,14 @@ public class GuiLootableEditor extends Gui {
|
|||||||
setButton(i, item,
|
setButton(i, item,
|
||||||
(event) -> {
|
(event) -> {
|
||||||
if (event.clickType == ClickType.RIGHT) {
|
if (event.clickType == ClickType.RIGHT) {
|
||||||
lootable.removeLoot(loot);
|
this.lootable.removeLoot(loot);
|
||||||
paint();
|
paint();
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.clickType == ClickType.LEFT) {
|
if (event.clickType == ClickType.LEFT) {
|
||||||
guiManager.showGUI(event.player, new GuiLootEditor(lootManager, loot, this));
|
this.guiManager.showGUI(event.player, new GuiLootEditor(this.lootManager, loot, this));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -12,12 +12,12 @@ public class GuiLoreEditor extends AbstractGuiListEditor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected List<String> getData() {
|
protected List<String> getData() {
|
||||||
return loot.getLore();
|
return this.loot.getLore();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void updateData(List<String> list) {
|
protected void updateData(List<String> list) {
|
||||||
loot.setLore(list);
|
this.loot.setLore(list);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -22,7 +22,7 @@ public class Drop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getCommand() {
|
public String getCommand() {
|
||||||
return command;
|
return this.command;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCommand(String command) {
|
public void setCommand(String command) {
|
||||||
@ -30,7 +30,7 @@ public class Drop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int getXp() {
|
public int getXp() {
|
||||||
return xp;
|
return this.xp;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setXp(int xp) {
|
public void setXp(int xp) {
|
||||||
@ -38,7 +38,7 @@ public class Drop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ItemStack getItemStack() {
|
public ItemStack getItemStack() {
|
||||||
return itemStack;
|
return this.itemStack;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setItemStack(ItemStack itemStack) {
|
public void setItemStack(ItemStack itemStack) {
|
||||||
|
@ -71,7 +71,7 @@ public class DropUtils {
|
|||||||
List<StackedItem> stacks = new ArrayList<>();
|
List<StackedItem> stacks = new ArrayList<>();
|
||||||
int maxSize = UltimateStackerApi.getSettings().getMaxItemStackSize() - 64;
|
int maxSize = UltimateStackerApi.getSettings().getMaxItemStackSize() - 64;
|
||||||
for (ItemStack item : items) {
|
for (ItemStack item : items) {
|
||||||
StackedItem stack = stacks.stream().filter(stackedItem -> stackedItem.getItem().getType() == item.getType()).filter(stackedItem -> stackedItem.getAmount() < Integer.MAX_VALUE/2).findFirst().orElse(null);
|
StackedItem stack = stacks.stream().filter(stackedItem -> stackedItem.getItem().getType() == item.getType()).filter(stackedItem -> stackedItem.getAmount() < Integer.MAX_VALUE / 2).findFirst().orElse(null);
|
||||||
if (stack == null) {
|
if (stack == null) {
|
||||||
stacks.add(new StackedItem(item, item.getAmount()));
|
stacks.add(new StackedItem(item, item.getAmount()));
|
||||||
continue;
|
continue;
|
||||||
@ -138,14 +138,6 @@ public class DropUtils {
|
|||||||
return this.amount;
|
return this.amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @deprecated Use {@link #setAmount(int)} instead.
|
|
||||||
*/
|
|
||||||
@Deprecated
|
|
||||||
public void setamount(int amount) {
|
|
||||||
this.amount = amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAmount(int amount) {
|
public void setAmount(int amount) {
|
||||||
this.amount = amount;
|
this.amount = amount;
|
||||||
}
|
}
|
||||||
|
@ -97,7 +97,7 @@ public class Loot {
|
|||||||
private boolean requireCharged = false;
|
private boolean requireCharged = false;
|
||||||
|
|
||||||
public XMaterial getMaterial() {
|
public XMaterial getMaterial() {
|
||||||
return material;
|
return this.material;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMaterial(XMaterial material) {
|
public void setMaterial(XMaterial material) {
|
||||||
@ -105,7 +105,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getCommand() {
|
public String getCommand() {
|
||||||
return command;
|
return this.command;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCommand(String command) {
|
public void setCommand(String command) {
|
||||||
@ -113,7 +113,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int getXp() {
|
public int getXp() {
|
||||||
return xp;
|
return this.xp;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setXp(int xp) {
|
public void setXp(int xp) {
|
||||||
@ -121,7 +121,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return TextUtils.formatText(name);
|
return TextUtils.formatText(this.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
@ -129,7 +129,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getLore() {
|
public List<String> getLore() {
|
||||||
if (lore == null) {
|
if (this.lore == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -147,12 +147,12 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ItemStack getEnchants(ItemStack item) {
|
public ItemStack getEnchants(ItemStack item) {
|
||||||
if (enchants == null) {
|
if (this.enchants == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Create enchantment book
|
// Create enchantment book
|
||||||
if (item.getType().equals(Material.ENCHANTED_BOOK)) {
|
if (item.getType() == Material.ENCHANTED_BOOK) {
|
||||||
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) item.getItemMeta();
|
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) item.getItemMeta();
|
||||||
for (Map.Entry<String, Integer> entry : this.enchants.entrySet()) {
|
for (Map.Entry<String, Integer> entry : this.enchants.entrySet()) {
|
||||||
if (entry.getValue() == null) continue;
|
if (entry.getValue() == null) continue;
|
||||||
@ -172,7 +172,9 @@ public class Loot {
|
|||||||
|
|
||||||
Map<Enchantment, Integer> enchants = new HashMap<>();
|
Map<Enchantment, Integer> enchants = new HashMap<>();
|
||||||
for (Map.Entry<String, Integer> entry : this.enchants.entrySet()) {
|
for (Map.Entry<String, Integer> entry : this.enchants.entrySet()) {
|
||||||
if (entry.getValue() == null) continue;
|
if (entry.getValue() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (entry.getKey().equalsIgnoreCase("RANDOM")) {
|
if (entry.getKey().equalsIgnoreCase("RANDOM")) {
|
||||||
item = ItemUtils.applyRandomEnchants(item, entry.getValue());
|
item = ItemUtils.applyRandomEnchants(item, entry.getValue());
|
||||||
@ -197,11 +199,11 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Integer> getEnchants() {
|
public Map<String, Integer> getEnchants() {
|
||||||
return enchants == null ? null : Collections.unmodifiableMap(enchants);
|
return this.enchants == null ? null : Collections.unmodifiableMap(this.enchants);
|
||||||
}
|
}
|
||||||
|
|
||||||
public XMaterial getBurnedMaterial() {
|
public XMaterial getBurnedMaterial() {
|
||||||
return burnedMaterial;
|
return this.burnedMaterial;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setBurnedMaterial(XMaterial burnedMaterial) {
|
public void setBurnedMaterial(XMaterial burnedMaterial) {
|
||||||
@ -209,7 +211,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public double getChance() {
|
public double getChance() {
|
||||||
return chance;
|
return this.chance;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setChance(double chance) {
|
public void setChance(double chance) {
|
||||||
@ -219,28 +221,25 @@ public class Loot {
|
|||||||
public boolean runChance(int looting, ItemStack murderWeapon) {
|
public boolean runChance(int looting, ItemStack murderWeapon) {
|
||||||
double chance = this.chance;
|
double chance = this.chance;
|
||||||
|
|
||||||
if (enchantChances != null && murderWeapon != null && enchants != null) {
|
if (this.enchantChances != null && murderWeapon != null && this.enchants != null) {
|
||||||
for (Map.Entry<Enchantment, Integer> entry : murderWeapon.getEnchantments().entrySet()) {
|
for (Map.Entry<Enchantment, Integer> entry : murderWeapon.getEnchantments().entrySet()) {
|
||||||
String key = entry.getKey().getName() + ":" + entry.getValue();
|
String key = entry.getKey().getName() + ":" + entry.getValue();
|
||||||
|
|
||||||
if (!enchants.containsKey(key)) {
|
if (!this.enchants.containsKey(key)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
double ch = enchantChances.get(key);
|
if (this.enchantChances.get(key) > chance) {
|
||||||
|
chance = this.enchantChances.get(key);
|
||||||
if (ch > chance) {
|
|
||||||
chance = enchantChances.get(key);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (Math.random() * 100) - (chance + (lootingIncrease == null ? 1
|
return (Math.random() * 100) - (chance + (this.lootingIncrease == null ? 1 : this.lootingIncrease * looting)) < 0 || chance == 100;
|
||||||
: lootingIncrease * looting)) < 0 || chance == 100;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getMin() {
|
public int getMin() {
|
||||||
return min;
|
return this.min;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMin(int min) {
|
public void setMin(int min) {
|
||||||
@ -248,7 +247,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int getMax() {
|
public int getMax() {
|
||||||
return max;
|
return this.max;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMax(int max) {
|
public void setMax(int max) {
|
||||||
@ -256,7 +255,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int getDamageMax() {
|
public int getDamageMax() {
|
||||||
return damageMax == null ? 0 : damageMax;
|
return this.damageMax == null ? 0 : this.damageMax;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDamageMax(int damageMax) {
|
public void setDamageMax(int damageMax) {
|
||||||
@ -264,7 +263,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int getDamageMin() {
|
public int getDamageMin() {
|
||||||
return damageMin == null ? 0 : damageMin;
|
return this.damageMin == null ? 0 : this.damageMin;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDamageMin(int damageMin) {
|
public void setDamageMin(int damageMin) {
|
||||||
@ -272,15 +271,15 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int getAmountToDrop(int looting) {
|
public int getAmountToDrop(int looting) {
|
||||||
return min == max ? (max + getLooting(looting)) : new Random().nextInt((max + getLooting(looting)) - min + 1) + min;
|
return this.min == this.max ? (this.max + getLooting(looting)) : new Random().nextInt((this.max + getLooting(looting)) - this.min + 1) + this.min;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getLooting(int looting) {
|
public int getLooting(int looting) {
|
||||||
return allowLootingEnchant ? looting : 0;
|
return this.allowLootingEnchant ? looting : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isAllowLootingEnchant() {
|
public boolean isAllowLootingEnchant() {
|
||||||
return allowLootingEnchant;
|
return this.allowLootingEnchant;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAllowLootingEnchant(boolean allowLootingEnchant) {
|
public void setAllowLootingEnchant(boolean allowLootingEnchant) {
|
||||||
@ -295,7 +294,7 @@ public class Loot {
|
|||||||
this.childDropCountMin = 1;
|
this.childDropCountMin = 1;
|
||||||
this.childDropCountMax = 1;
|
this.childDropCountMax = 1;
|
||||||
|
|
||||||
if (childLoot == null) {
|
if (this.childLoot == null) {
|
||||||
this.childLoot = new ArrayList<>();
|
this.childLoot = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -303,7 +302,7 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void removeChildLoot(Loot loot) {
|
public void removeChildLoot(Loot loot) {
|
||||||
if (childLoot == null) {
|
if (this.childLoot == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -311,11 +310,11 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<Loot> getChildLoot() {
|
public List<Loot> getChildLoot() {
|
||||||
return childLoot == null ? new ArrayList<>() : new ArrayList<>(childLoot);
|
return this.childLoot == null ? new ArrayList<>() : new ArrayList<>(this.childLoot);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<EntityType> getOnlyDropFor() {
|
public List<EntityType> getOnlyDropFor() {
|
||||||
return onlyDropFor == null ? new ArrayList<>() : new ArrayList<>(onlyDropFor);
|
return this.onlyDropFor == null ? new ArrayList<>() : new ArrayList<>(this.onlyDropFor);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addOnlyDropFor(EntityType... types) {
|
public void addOnlyDropFor(EntityType... types) {
|
||||||
@ -336,23 +335,23 @@ public class Loot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Integer getChildDropCountMin() {
|
public Integer getChildDropCountMin() {
|
||||||
return childDropCountMin;
|
return this.childDropCountMin;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getChildDropCountMax() {
|
public Integer getChildDropCountMax() {
|
||||||
return childDropCountMax;
|
return this.childDropCountMax;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getChildDropCount() {
|
public int getChildDropCount() {
|
||||||
if (childDropCountMin == null || childDropCountMax == null) {
|
if (this.childDropCountMin == null || this.childDropCountMax == null) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Random().nextInt(childDropCountMax - childDropCountMin + 1) + childDropCountMin;
|
return new Random().nextInt(this.childDropCountMax - this.childDropCountMin + 1) + this.childDropCountMin;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isRequireCharged() {
|
public boolean isRequireCharged() {
|
||||||
return requireCharged;
|
return this.requireCharged;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setRequireCharged(boolean requireCharged) {
|
public void setRequireCharged(boolean requireCharged) {
|
||||||
|
@ -30,11 +30,11 @@ public final class LootBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LootBuilder addEnchants(Tuple... tuples) {
|
public LootBuilder addEnchants(Tuple<String, Integer>... tuples) {
|
||||||
Map<String, Integer> enchants = new HashMap<>();
|
Map<String, Integer> enchants = new HashMap<>();
|
||||||
|
|
||||||
for (Tuple tuple : tuples) {
|
for (Tuple<String, Integer> tuple : tuples) {
|
||||||
enchants.put((String) tuple.getKey(), (int) tuple.getValue());
|
enchants.put(tuple.getKey(), tuple.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
this.loot.setEnchants(enchants);
|
this.loot.setEnchants(enchants);
|
||||||
|
@ -33,13 +33,13 @@ public class LootManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Lootable addLootable(Lootable lootable) {
|
public Lootable addLootable(Lootable lootable) {
|
||||||
return registeredLootables.put(lootable.getKey(), lootable);
|
return this.registeredLootables.put(lootable.getKey(), lootable);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeLootable(String key) {
|
public void removeLootable(String key) {
|
||||||
registeredLootables.remove(key);
|
this.registeredLootables.remove(key);
|
||||||
|
|
||||||
File file = new File(lootables.getLootablesDir(), key.toLowerCase() + ".json");
|
File file = new File(this.lootables.getLootablesDir(), key.toLowerCase() + ".json");
|
||||||
file.delete();
|
file.delete();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,12 +58,13 @@ public class LootManager {
|
|||||||
((Math.random() * 100) - rerollChance < 0 || rerollChance == 100) &&
|
((Math.random() * 100) - rerollChance < 0 || rerollChance == 100) &&
|
||||||
loot.runChance(looting, murderWeapon)) {
|
loot.runChance(looting, murderWeapon)) {
|
||||||
|
|
||||||
if (loot.getOnlyDropFor().size() != 0
|
if (!loot.getOnlyDropFor().isEmpty()
|
||||||
&& loot.getOnlyDropFor().stream().noneMatch(type -> looter != null && type == looter)
|
&& loot.getOnlyDropFor().stream().noneMatch(type -> looter != null && type == looter)
|
||||||
|| !isCharged && loot.isRequireCharged())
|
|| !isCharged && loot.isRequireCharged()) {
|
||||||
return toDrop;
|
return toDrop;
|
||||||
|
}
|
||||||
|
|
||||||
if (loot.getChildLoot().size() > 0) {
|
if (!loot.getChildLoot().isEmpty()) {
|
||||||
List<Loot> childLoot = loot.getChildLoot();
|
List<Loot> childLoot = loot.getChildLoot();
|
||||||
Collections.shuffle(childLoot);
|
Collections.shuffle(childLoot);
|
||||||
|
|
||||||
@ -153,9 +154,9 @@ public class LootManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void loadLootables() {
|
public void loadLootables() {
|
||||||
registeredLootables.clear();
|
this.registeredLootables.clear();
|
||||||
|
|
||||||
File dir = new File(lootables.getLootablesDir());
|
File dir = new File(this.lootables.getLootablesDir());
|
||||||
File[] directoryListing = dir.listFiles();
|
File[] directoryListing = dir.listFiles();
|
||||||
|
|
||||||
if (directoryListing != null) {
|
if (directoryListing != null) {
|
||||||
@ -170,7 +171,7 @@ public class LootManager {
|
|||||||
|
|
||||||
Lootable lootable = gson.fromJson(reader, Lootable.class);
|
Lootable lootable = gson.fromJson(reader, Lootable.class);
|
||||||
|
|
||||||
if (lootable.getRegisteredLoot().size() != 0) {
|
if (!lootable.getRegisteredLoot().isEmpty()) {
|
||||||
addLootable(lootable);
|
addLootable(lootable);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -183,13 +184,13 @@ public class LootManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void saveLootables(boolean defaults) {
|
public void saveLootables(boolean defaults) {
|
||||||
File dir = new File(lootables.getLootablesDir());
|
File dir = new File(this.lootables.getLootablesDir());
|
||||||
dir.mkdir();
|
dir.mkdir();
|
||||||
|
|
||||||
// Save to file
|
// Save to file
|
||||||
for (Lootable lootable : registeredLootables.values()) {
|
for (Lootable lootable : this.registeredLootables.values()) {
|
||||||
try {
|
try {
|
||||||
File file = new File(lootables.getLootablesDir(), lootable.getKey().toLowerCase() + ".json");
|
File file = new File(this.lootables.getLootablesDir(), lootable.getKey().toLowerCase() + ".json");
|
||||||
|
|
||||||
if (file.exists() && defaults) {
|
if (file.exists() && defaults) {
|
||||||
continue;
|
continue;
|
||||||
@ -205,11 +206,11 @@ public class LootManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (defaults) {
|
if (defaults) {
|
||||||
registeredLootables.clear();
|
this.registeredLootables.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Lootable> getRegisteredLootables() {
|
public Map<String, Lootable> getRegisteredLootables() {
|
||||||
return Collections.unmodifiableMap(registeredLootables);
|
return Collections.unmodifiableMap(this.registeredLootables);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -22,19 +22,19 @@ public class Lootable {
|
|||||||
public Lootable(String key, Loot... loots) {
|
public Lootable(String key, Loot... loots) {
|
||||||
this.type = key;
|
this.type = key;
|
||||||
|
|
||||||
registeredLoot.addAll(Arrays.asList(loots));
|
this.registeredLoot.addAll(Arrays.asList(loots));
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Loot> getRegisteredLoot() {
|
public List<Loot> getRegisteredLoot() {
|
||||||
return new ArrayList<>(registeredLoot);
|
return new ArrayList<>(this.registeredLoot);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void registerLoot(Loot... loots) {
|
public void registerLoot(Loot... loots) {
|
||||||
registeredLoot.addAll(Arrays.asList(loots));
|
this.registeredLoot.addAll(Arrays.asList(loots));
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getKey() {
|
public String getKey() {
|
||||||
return type;
|
return this.type;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeLoot(Loot loot) {
|
public void removeLoot(Loot loot) {
|
||||||
|
@ -14,14 +14,14 @@ public class EnchantChance {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Enchantment getEnchantment() {
|
public Enchantment getEnchantment() {
|
||||||
return enchantment;
|
return this.enchantment;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getLevel() {
|
public int getLevel() {
|
||||||
return level;
|
return this.level;
|
||||||
}
|
}
|
||||||
|
|
||||||
public double getChanceOverride() {
|
public double getChanceOverride() {
|
||||||
return chanceOverride;
|
return this.chanceOverride;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
package com.craftaro.core.math;
|
package com.craftaro.core.math;
|
||||||
|
|
||||||
public class Eval {
|
public class Eval {
|
||||||
private int pos = -1, ch;
|
private int pos = -1;
|
||||||
|
private int ch;
|
||||||
private final String toParse;
|
private final String toParse;
|
||||||
private final String warningMessage;
|
private final String warningMessage;
|
||||||
|
|
||||||
|
@ -6,13 +6,13 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public class MathUtils {
|
public class MathUtils {
|
||||||
private static final Map<String, Double> cache = new HashMap<>();
|
private static final Map<String, Double> CACHE = new HashMap<>();
|
||||||
|
|
||||||
public static double eval(String toParse) {
|
public static double eval(String toParse) {
|
||||||
return eval(toParse, CraftaroCoreConstants.getProjectName() + " Eval Engine");
|
return eval(toParse, CraftaroCoreConstants.getProjectName() + " Eval Engine");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static double eval(String toParse, String warningMessage) {
|
public static double eval(String toParse, String warningMessage) {
|
||||||
return cache.computeIfAbsent(toParse, t -> new Eval(toParse, warningMessage).parse());
|
return CACHE.computeIfAbsent(toParse, t -> new Eval(toParse, warningMessage).parse());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,6 @@ import java.util.concurrent.ScheduledFuture;
|
|||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class MonitoredThread {
|
public class MonitoredThread {
|
||||||
|
|
||||||
private final String name;
|
private final String name;
|
||||||
private final int timeout;
|
private final int timeout;
|
||||||
private final TimeUnit timeUnit;
|
private final TimeUnit timeUnit;
|
||||||
@ -29,56 +28,57 @@ public class MonitoredThread {
|
|||||||
public void execute(Runnable runnable, boolean nonDisruptable) {
|
public void execute(Runnable runnable, boolean nonDisruptable) {
|
||||||
this.nonDisruptable = nonDisruptable;
|
this.nonDisruptable = nonDisruptable;
|
||||||
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
|
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
|
||||||
executor.execute(() -> {
|
this.executor.execute(() -> {
|
||||||
started = Instant.now();
|
this.started = Instant.now();
|
||||||
this.trace = trace;
|
this.trace = trace;
|
||||||
try {
|
try {
|
||||||
runnable.run();
|
runnable.run();
|
||||||
} catch (Exception e) {
|
} catch (Exception ex) {
|
||||||
StackTraceElement[] newTrace = new StackTraceElement[e.getStackTrace().length + trace.length];
|
StackTraceElement[] newTrace = new StackTraceElement[ex.getStackTrace().length + trace.length];
|
||||||
System.arraycopy(e.getStackTrace(), 0, newTrace, 0, e.getStackTrace().length);
|
System.arraycopy(ex.getStackTrace(), 0, newTrace, 0, ex.getStackTrace().length);
|
||||||
System.arraycopy(trace, 0, newTrace, e.getStackTrace().length, trace.length);
|
System.arraycopy(trace, 0, newTrace, ex.getStackTrace().length, trace.length);
|
||||||
e.setStackTrace(newTrace);
|
ex.setStackTrace(newTrace);
|
||||||
System.out.println("Thread '" + name + "' failed with exception: " + e.getMessage());
|
System.out.println("Thread '" + this.name + "' failed with exception: " + ex.getMessage());
|
||||||
e.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
started = null;
|
this.started = null;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public MonitoredThread start() {
|
public MonitoredThread start() {
|
||||||
if (executor != null) {
|
if (this.executor != null) {
|
||||||
executor.shutdown();
|
this.executor.shutdown();
|
||||||
System.out.println("Thread '" + name + "' was restarted due to a stall. Stack trace:");
|
System.out.println("Thread '" + this.name + "' was restarted due to a stall. Stack trace:");
|
||||||
for (StackTraceElement element : this.trace)
|
for (StackTraceElement element : this.trace) {
|
||||||
System.out.println(" " + element.toString());
|
System.out.println(" " + element.toString());
|
||||||
}
|
}
|
||||||
executor = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, name));
|
}
|
||||||
|
this.executor = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, this.name));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return this.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isStalled() {
|
public boolean isStalled() {
|
||||||
return !nonDisruptable && started != null && started.plusMillis(timeUnit.toMillis(timeout)).isBefore(Instant.now())
|
return !this.nonDisruptable && this.started != null && this.started.plusMillis(this.timeUnit.toMillis(this.timeout)).isBefore(Instant.now())
|
||||||
|| started != null && started.plusMillis(TimeUnit.HOURS.toMillis(1)).isBefore(Instant.now());
|
|| this.started != null && this.started.plusMillis(TimeUnit.HOURS.toMillis(1)).isBefore(Instant.now());
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isRunning() {
|
public boolean isRunning() {
|
||||||
return started != null;
|
return this.started != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Instant getStarted() {
|
public Instant getStarted() {
|
||||||
return started;
|
return this.started;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit timeUnit) {
|
public ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit timeUnit) {
|
||||||
return executor.schedule(runnable, delay, timeUnit);
|
return this.executor.schedule(runnable, delay, timeUnit);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void destroy() {
|
public void destroy() {
|
||||||
executor.shutdownNow();
|
this.executor.shutdownNow();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,6 @@ import java.util.concurrent.ScheduledFuture;
|
|||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class MonitoredThreadPool {
|
public class MonitoredThreadPool {
|
||||||
|
|
||||||
private final HashSet<MonitoredThread> threads = new HashSet<>();
|
private final HashSet<MonitoredThread> threads = new HashSet<>();
|
||||||
private final String name;
|
private final String name;
|
||||||
private final int size;
|
private final int size;
|
||||||
@ -19,13 +18,14 @@ public class MonitoredThreadPool {
|
|||||||
this.size = size;
|
this.size = size;
|
||||||
this.threadTimeout = timeout;
|
this.threadTimeout = timeout;
|
||||||
this.threadTimeoutUnit = timeUnit;
|
this.threadTimeoutUnit = timeUnit;
|
||||||
for (int i = 0; i < size; i++)
|
for (int i = 0; i < size; ++i) {
|
||||||
createThread(name);
|
createThread(name);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public MonitoredThread createThread(String name) {
|
public MonitoredThread createThread(String name) {
|
||||||
MonitoredThread thread = new MonitoredThread((name + "-" + latestThread++).toLowerCase(), threadTimeout, threadTimeoutUnit);
|
MonitoredThread thread = new MonitoredThread((name + "-" + this.latestThread++).toLowerCase(), this.threadTimeout, this.threadTimeoutUnit);
|
||||||
threads.add(thread);
|
this.threads.add(thread);
|
||||||
return thread;
|
return thread;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -49,7 +49,7 @@ public class MonitoredThreadPool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private MonitoredThread getHealthyThread() {
|
private MonitoredThread getHealthyThread() {
|
||||||
for (MonitoredThread thread : threads) {
|
for (MonitoredThread thread : this.threads) {
|
||||||
if (!thread.isRunning()) {
|
if (!thread.isRunning()) {
|
||||||
return thread;
|
return thread;
|
||||||
} else if (thread.isStalled()) {
|
} else if (thread.isStalled()) {
|
||||||
@ -63,9 +63,11 @@ public class MonitoredThreadPool {
|
|||||||
|
|
||||||
public int getRunningThreads() {
|
public int getRunningThreads() {
|
||||||
int runningThreads = 0;
|
int runningThreads = 0;
|
||||||
for (MonitoredThread thread : threads)
|
for (MonitoredThread thread : this.threads) {
|
||||||
if (thread.isRunning())
|
if (thread.isRunning()) {
|
||||||
runningThreads++;
|
runningThreads++;
|
||||||
|
}
|
||||||
|
}
|
||||||
return runningThreads;
|
return runningThreads;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,9 +3,7 @@ package com.craftaro.core.thread;
|
|||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class SingleMonitoredThread extends MonitoredThreadPool {
|
public class SingleMonitoredThread extends MonitoredThreadPool {
|
||||||
|
|
||||||
public SingleMonitoredThread(String name, int timeout, TimeUnit timeUnit) {
|
public SingleMonitoredThread(String name, int timeout, TimeUnit timeUnit) {
|
||||||
super(name, 1, timeout, timeUnit);
|
super(name, 1, timeout, timeUnit);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,6 @@ import java.util.Map;
|
|||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
public abstract class TaskScheduler {
|
public abstract class TaskScheduler {
|
||||||
|
|
||||||
private final SongodaPlugin plugin;
|
private final SongodaPlugin plugin;
|
||||||
private final Map<TaskWrapper, Long> tasks = new ConcurrentHashMap<>();
|
private final Map<TaskWrapper, Long> tasks = new ConcurrentHashMap<>();
|
||||||
private BukkitRunnable runnable;
|
private BukkitRunnable runnable;
|
||||||
@ -18,31 +17,31 @@ public abstract class TaskScheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void startScheduler() {
|
private void startScheduler() {
|
||||||
if (runnable == null || runnable.isCancelled()) {
|
if (this.runnable == null || this.runnable.isCancelled()) {
|
||||||
runnable = new BukkitRunnable() {
|
this.runnable = new BukkitRunnable() {
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
executeTasks();
|
executeTasks();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
runnable.runTaskTimerAsynchronously(plugin, 20L, 20L);
|
this.runnable.runTaskTimerAsynchronously(this.plugin, 20L, 20L);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void stopScheduler() {
|
private void stopScheduler() {
|
||||||
if (runnable != null && !runnable.isCancelled()) {
|
if (this.runnable != null && !this.runnable.isCancelled()) {
|
||||||
runnable.cancel();
|
this.runnable.cancel();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void executeTasks() {
|
private void executeTasks() {
|
||||||
if (tasks.isEmpty()) {
|
if (this.tasks.isEmpty()) {
|
||||||
stopScheduler();
|
stopScheduler();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
long currentTime = System.currentTimeMillis();
|
long currentTime = System.currentTimeMillis();
|
||||||
Iterator<Map.Entry<TaskWrapper, Long>> iterator = tasks.entrySet().iterator();
|
Iterator<Map.Entry<TaskWrapper, Long>> iterator = this.tasks.entrySet().iterator();
|
||||||
|
|
||||||
while (iterator.hasNext()) {
|
while (iterator.hasNext()) {
|
||||||
Map.Entry<TaskWrapper, Long> entry = iterator.next();
|
Map.Entry<TaskWrapper, Long> entry = iterator.next();
|
||||||
@ -55,7 +54,7 @@ public abstract class TaskScheduler {
|
|||||||
public void run() {
|
public void run() {
|
||||||
taskWrapper.getTask().run();
|
taskWrapper.getTask().run();
|
||||||
}
|
}
|
||||||
}.runTaskAsynchronously(plugin);
|
}.runTaskAsynchronously(this.plugin);
|
||||||
} else {
|
} else {
|
||||||
// Run the task synchronously
|
// Run the task synchronously
|
||||||
new BukkitRunnable() {
|
new BukkitRunnable() {
|
||||||
@ -63,7 +62,7 @@ public abstract class TaskScheduler {
|
|||||||
public void run() {
|
public void run() {
|
||||||
taskWrapper.getTask().run();
|
taskWrapper.getTask().run();
|
||||||
}
|
}
|
||||||
}.runTask(plugin);
|
}.runTask(this.plugin);
|
||||||
}
|
}
|
||||||
iterator.remove();
|
iterator.remove();
|
||||||
}
|
}
|
||||||
@ -71,7 +70,7 @@ public abstract class TaskScheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void addTask(Runnable task, long delay, boolean async) {
|
public synchronized void addTask(Runnable task, long delay, boolean async) {
|
||||||
tasks.put(new TaskWrapper(task, async), System.currentTimeMillis() + delay);
|
this.tasks.put(new TaskWrapper(task, async), System.currentTimeMillis() + delay);
|
||||||
startScheduler();
|
startScheduler();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -89,11 +88,11 @@ public abstract class TaskScheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Runnable getTask() {
|
public Runnable getTask() {
|
||||||
return task;
|
return this.task;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isAsync() {
|
public boolean isAsync() {
|
||||||
return async;
|
return this.async;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,25 +7,25 @@ import java.util.Map;
|
|||||||
import java.util.TreeMap;
|
import java.util.TreeMap;
|
||||||
|
|
||||||
public class ColorUtils {
|
public class ColorUtils {
|
||||||
private static final Map<ColorCode, ColorSet<Integer, Integer, Integer>> colorMap = new HashMap<>();
|
private static final Map<ColorCode, ColorSet<Integer, Integer, Integer>> COLOR_MAP = new HashMap<>();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
colorMap.put(ColorCode.BLACK, new ColorSet<>(0, 0, 0));
|
COLOR_MAP.put(ColorCode.BLACK, new ColorSet<>(0, 0, 0));
|
||||||
colorMap.put(ColorCode.DARK_BLUE, new ColorSet<>(0, 0, 170));
|
COLOR_MAP.put(ColorCode.DARK_BLUE, new ColorSet<>(0, 0, 170));
|
||||||
colorMap.put(ColorCode.DARK_GREEN, new ColorSet<>(0, 170, 0));
|
COLOR_MAP.put(ColorCode.DARK_GREEN, new ColorSet<>(0, 170, 0));
|
||||||
colorMap.put(ColorCode.DARK_AQUA, new ColorSet<>(0, 170, 170));
|
COLOR_MAP.put(ColorCode.DARK_AQUA, new ColorSet<>(0, 170, 170));
|
||||||
colorMap.put(ColorCode.DARK_RED, new ColorSet<>(170, 0, 0));
|
COLOR_MAP.put(ColorCode.DARK_RED, new ColorSet<>(170, 0, 0));
|
||||||
colorMap.put(ColorCode.DARK_PURPLE, new ColorSet<>(170, 0, 170));
|
COLOR_MAP.put(ColorCode.DARK_PURPLE, new ColorSet<>(170, 0, 170));
|
||||||
colorMap.put(ColorCode.GOLD, new ColorSet<>(255, 170, 0));
|
COLOR_MAP.put(ColorCode.GOLD, new ColorSet<>(255, 170, 0));
|
||||||
colorMap.put(ColorCode.GRAY, new ColorSet<>(170, 170, 170));
|
COLOR_MAP.put(ColorCode.GRAY, new ColorSet<>(170, 170, 170));
|
||||||
colorMap.put(ColorCode.DARK_GRAY, new ColorSet<>(85, 85, 85));
|
COLOR_MAP.put(ColorCode.DARK_GRAY, new ColorSet<>(85, 85, 85));
|
||||||
colorMap.put(ColorCode.BLUE, new ColorSet<>(85, 85, 255));
|
COLOR_MAP.put(ColorCode.BLUE, new ColorSet<>(85, 85, 255));
|
||||||
colorMap.put(ColorCode.GREEN, new ColorSet<>(85, 255, 85));
|
COLOR_MAP.put(ColorCode.GREEN, new ColorSet<>(85, 255, 85));
|
||||||
colorMap.put(ColorCode.AQUA, new ColorSet<>(85, 255, 255));
|
COLOR_MAP.put(ColorCode.AQUA, new ColorSet<>(85, 255, 255));
|
||||||
colorMap.put(ColorCode.RED, new ColorSet<>(255, 85, 85));
|
COLOR_MAP.put(ColorCode.RED, new ColorSet<>(255, 85, 85));
|
||||||
colorMap.put(ColorCode.LIGHT_PURPLE, new ColorSet<>(255, 85, 255));
|
COLOR_MAP.put(ColorCode.LIGHT_PURPLE, new ColorSet<>(255, 85, 255));
|
||||||
colorMap.put(ColorCode.YELLOW, new ColorSet<>(255, 255, 85));
|
COLOR_MAP.put(ColorCode.YELLOW, new ColorSet<>(255, 255, 85));
|
||||||
colorMap.put(ColorCode.WHITE, new ColorSet<>(255, 255, 255));
|
COLOR_MAP.put(ColorCode.WHITE, new ColorSet<>(255, 255, 255));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class ColorSet<R, G, B> {
|
private static class ColorSet<R, G, B> {
|
||||||
@ -54,7 +54,7 @@ public class ColorUtils {
|
|||||||
|
|
||||||
public static ColorCode fromRGB(int r, int g, int b) {
|
public static ColorCode fromRGB(int r, int g, int b) {
|
||||||
TreeMap<Integer, ColorCode> closest = new TreeMap<>();
|
TreeMap<Integer, ColorCode> closest = new TreeMap<>();
|
||||||
colorMap.forEach((color, set) -> {
|
COLOR_MAP.forEach((color, set) -> {
|
||||||
int red = Math.abs(r - set.getRed());
|
int red = Math.abs(r - set.getRed());
|
||||||
int green = Math.abs(g - set.getGreen());
|
int green = Math.abs(g - set.getGreen());
|
||||||
int blue = Math.abs(b - set.getBlue());
|
int blue = Math.abs(b - set.getBlue());
|
||||||
|
@ -60,7 +60,7 @@ public class NumberUtils {
|
|||||||
*/
|
*/
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public static boolean isNumeric(String s) {
|
public static boolean isNumeric(String s) {
|
||||||
if (s == null || s.equals("")) {
|
if (s == null || s.isEmpty()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,23 +17,24 @@ import java.util.List;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class TextUtils {
|
public class TextUtils {
|
||||||
private static final List<Charset> supportedCharsets = new ArrayList<>();
|
private static final List<Charset> SUPPORTED_CHARSETS = new ArrayList<>();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
supportedCharsets.add(StandardCharsets.UTF_8); // UTF-8 BOM: EF BB BF
|
SUPPORTED_CHARSETS.add(StandardCharsets.UTF_8); // UTF-8 BOM: EF BB BF
|
||||||
supportedCharsets.add(StandardCharsets.ISO_8859_1); // also starts with EF BB BF
|
SUPPORTED_CHARSETS.add(StandardCharsets.ISO_8859_1); // also starts with EF BB BF
|
||||||
// supportedCharsets.add(StandardCharsets.UTF_16LE); // FF FE
|
// supportedCharsets.add(StandardCharsets.UTF_16LE); // FF FE
|
||||||
// supportedCharsets.add(StandardCharsets.UTF_16BE); // FE FF
|
// supportedCharsets.add(StandardCharsets.UTF_16BE); // FE FF
|
||||||
// supportedCharsets.add(StandardCharsets.UTF_16);
|
// supportedCharsets.add(StandardCharsets.UTF_16);
|
||||||
|
|
||||||
// FIXME: One unsupported charset causes other ones not to be tried
|
// FIXME: One unsupported charset causes other ones not to be tried
|
||||||
try {
|
try {
|
||||||
supportedCharsets.add(Charset.forName("windows-1253"));
|
SUPPORTED_CHARSETS.add(Charset.forName("windows-1253"));
|
||||||
supportedCharsets.add(Charset.forName("ISO-8859-7"));
|
SUPPORTED_CHARSETS.add(Charset.forName("ISO-8859-7"));
|
||||||
} catch (Exception ignore) { // UnsupportedCharsetException technically can be thrown, but can also be ignored
|
} catch (
|
||||||
|
Exception ignore) { // UnsupportedCharsetException technically can be thrown, but can also be ignored
|
||||||
}
|
}
|
||||||
|
|
||||||
supportedCharsets.add(StandardCharsets.US_ASCII);
|
SUPPORTED_CHARSETS.add(StandardCharsets.US_ASCII);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String formatText(String text) {
|
public static String formatText(String text) {
|
||||||
@ -41,7 +42,7 @@ public class TextUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static String formatText(String text, boolean capitalize) {
|
public static String formatText(String text, boolean capitalize) {
|
||||||
if (text == null || text.equals("")) {
|
if (text == null || text.isEmpty()) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -103,11 +104,10 @@ public class TextUtils {
|
|||||||
* Note: Do not use semi-colons or § in this string, or they will be lost when decoding!
|
* Note: Do not use semi-colons or § in this string, or they will be lost when decoding!
|
||||||
*
|
*
|
||||||
* @param s string to convert
|
* @param s string to convert
|
||||||
*
|
|
||||||
* @return encoded string
|
* @return encoded string
|
||||||
*/
|
*/
|
||||||
public static String convertToInvisibleLoreString(String s) {
|
public static String convertToInvisibleLoreString(String s) {
|
||||||
if (s == null || s.equals("")) {
|
if (s == null || s.isEmpty()) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -126,14 +126,13 @@ public class TextUtils {
|
|||||||
/**
|
/**
|
||||||
* Convert a string to an invisible colored string <br />
|
* Convert a string to an invisible colored string <br />
|
||||||
* (Not safe to use as lore) <br />
|
* (Not safe to use as lore) <br />
|
||||||
* Note: Do not use semi-colons or § in this string, or they will be lost when decoding!
|
* Note: Do not use semicolons or § in this string, or they will be lost when decoding!
|
||||||
*
|
*
|
||||||
* @param s string to convert
|
* @param s string to convert
|
||||||
*
|
|
||||||
* @return encoded string
|
* @return encoded string
|
||||||
*/
|
*/
|
||||||
public static String convertToInvisibleString(String s) {
|
public static String convertToInvisibleString(String s) {
|
||||||
if (s == null || s.equals("")) {
|
if (s == null || s.isEmpty()) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -147,27 +146,27 @@ public class TextUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Is there a more reliable way?
|
// TODO: Is there a more reliable way?
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes color markers used to encode strings as invisible text
|
* Removes color markers used to encode strings as invisible text
|
||||||
*
|
*
|
||||||
* @param s encoded string
|
* @param s encoded string
|
||||||
*
|
|
||||||
* @return string with color markers removed
|
* @return string with color markers removed
|
||||||
*/
|
*/
|
||||||
public static String convertFromInvisibleString(String s) {
|
public static String convertFromInvisibleString(String s) {
|
||||||
if (s == null || s.equals("")) {
|
if (s == null || s.isEmpty()) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.replaceAll(ChatColor.COLOR_CHAR + ";" + ChatColor.COLOR_CHAR + "|" + ChatColor.COLOR_CHAR, "");
|
return s.replaceAll(ChatColor.COLOR_CHAR + ";" + ChatColor.COLOR_CHAR + "|" + ChatColor.COLOR_CHAR, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Charset detectCharset(File f, Charset def) {
|
public static Charset detectCharset(File file, Charset def) {
|
||||||
byte[] buffer = new byte[2048];
|
byte[] buffer = new byte[2048];
|
||||||
int len;
|
int len;
|
||||||
|
|
||||||
// Read the first 2 KiB of the file and test the file's encoding
|
// Read the first 2 KiB of the file and test the file's encoding
|
||||||
try (FileInputStream input = new FileInputStream(f)) {
|
try (FileInputStream input = new FileInputStream(file)) {
|
||||||
len = input.read(buffer);
|
len = input.read(buffer);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
return null;
|
return null;
|
||||||
@ -205,10 +204,12 @@ public class TextUtils {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Look for last Whitespace Character and ignore potentially broken words/multi-byte characters
|
// Look for the last Whitespace Character and ignore potentially broken words/multibyte characters
|
||||||
int newLen = len;
|
int newLen = len;
|
||||||
for (; newLen > 0; --newLen) {
|
for (; newLen > 0; --newLen) {
|
||||||
if (Character.isWhitespace(data[newLen - 1])) break;
|
if (Character.isWhitespace(data[newLen - 1])) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Buffer got too small? => checking whole buffer
|
// Buffer got too small? => checking whole buffer
|
||||||
@ -219,7 +220,7 @@ public class TextUtils {
|
|||||||
ByteBuffer bBuff = ByteBuffer.wrap(data, 0, newLen).asReadOnlyBuffer();
|
ByteBuffer bBuff = ByteBuffer.wrap(data, 0, newLen).asReadOnlyBuffer();
|
||||||
|
|
||||||
// Check through a list of charsets and return the first one that could decode the buffer
|
// Check through a list of charsets and return the first one that could decode the buffer
|
||||||
for (Charset charset : supportedCharsets) {
|
for (Charset charset : SUPPORTED_CHARSETS) {
|
||||||
if (charset != null && isCharset(bBuff, charset)) {
|
if (charset != null && isCharset(bBuff, charset)) {
|
||||||
return charset;
|
return charset;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user